繁体   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