首页 > 解决方案 > 用于单元测试或 pytest 的 Python 检测

问题描述

我的目标是改变在我的 virtualenv 中运行的每个测试,首先打印(“开始测试”),一旦测试完成就打印(“测试结束”)。

例如:

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

我的问题是我需要为 pytest 或 unittest 执行的每个测试执行此任务(手动插入不是一个选项)。

unittest 中是否有任何特定方法可以修改以实现我的目标?我愿意接受建议。

提前感谢所有帮助者

标签: pythonunit-testingpytestpython-unittestinstrumentation

解决方案


一个简单的装饰器就足够了,尽管这种特性是测试运行器应该提供的。(不过,装饰器比自定义测试运行器更容易定义。)

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()

更好的解决方案可能特定于特定的测试框架。


推荐阅读