簡體   English   中英

用於單元測試或 pytest 的 Python 檢測

[英]Python instrumentation for unittests or pytest

我的目標是改變在我的 virtualenv 中運行的每個測試,首先打印(“開始測試”),一旦測試完成就打印(“測試結束”)。

例如:

def test_numpy_func1():
    print("Start test")
    method_to_test.run()
    print("End test")

我的問題是我需要為 pytest 或 unittest 執行的每個測試執行此任務(手動插入不是一種選擇)。

我可以修改 unittest 中的任何特定方法以實現我的目標? 我願意接受建議。

預先感謝所有幫助者

一個簡單的裝飾就足夠了,但這種功能的是后話了測試運行應提供。 (不過,裝飾器比自定義測試運行器更容易定義。)

from functools import wraps


def start_stop_logging(f):
    @wraps(f)
    def _(*args, **kwargs):
        print("Start test")
        f(*args, **kwargs)
        print("End test")
    return _

@start_stop_logging
def test_numpy_func1():
    method_to_test.run()

更好的解決方案可能特定於特定的測試框架。

最后,對於 pytest,我添加了一個 conftest.py 文件並覆蓋了 pytest_runtest_setup() 和 pytest_runtest_teardown() 函數。 對於單元測試,在 case.py 中搜索 run() 函數,您將看到每個測試的 setup() 或 teardown() 用法,因此您可以在調用這些函數之前或之后添加任何您想要的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM