简体   繁体   English

用于单元测试或 pytest 的 Python 检测

[英]Python instrumentation for unittests or pytest

My goal is to alter every test that runs in my virtualenv, to first print("Start test") and once the test is done to print("End of test").我的目标是改变在我的 virtualenv 中运行的每个测试,首先打印(“开始测试”),一旦测试完成就打印(“测试结束”)。

For Example:例如:

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

My problem is that I need to perform this task for every test that pytest or unittest executes (manual insertion is not an option).我的问题是我需要为 pytest 或 unittest 执行的每个测试执行此任务(手动插入不是一种选择)。

Is there any specific method inside unittest that I can modify in order to achieve my goal?我可以修改 unittest 中的任何特定方法以实现我的目标? Im open to suggestion.我愿意接受建议。

Thanks in advance for all the helpers预先感谢所有帮助者

A simple decorator would suffice, though this kind of feature is something the test runner should provide.一个简单的装饰就足够了,但这种功能的是后话了测试运行应提供。 (The decorator is much easier to define than a custom test runner, though.) (不过,装饰器比自定义测试运行器更容易定义。)

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

Better solutions would probably be specific to a particular test framework.更好的解决方案可能特定于特定的测试框架。

Eventually, for pytest I added a conftest.py file and override the pytest_runtest_setup() and pytest_runtest_teardown() functions.最后,对于 pytest,我添加了一个 conftest.py 文件并覆盖了 pytest_runtest_setup() 和 pytest_runtest_teardown() 函数。 For unittest, search for run() function in case.py and you will see the usage of setup() or teardown() for each test, so you could add anything you want before or after calling those functions.对于单元测试,在 case.py 中搜索 run() 函数,您将看到每个测试的 setup() 或 teardown() 用法,因此您可以在调用这些函数之前或之后添加任何您想要的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM