【问题标题】:Python instrumentation for unittests or pytest用于单元测试或 pytest 的 Python 检测
【发布时间】:2021-12-09 06:27:51
【问题描述】:

我的目标是改变在我的 virtualenv 中运行的每个测试,首先是 print("Start test"),一旦测试完成,就变成 print("End of test")。

例如:

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

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

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

提前感谢所有帮助者

【问题讨论】:

    标签: python unit-testing pytest python-unittest instrumentation


    【解决方案1】:

    最终,对于 pytest,我添加了一个 conftest.py 文件并覆盖了 pytest_runtest_setup() 和 pytest_runtest_teardown() 函数。 对于 unittest,在 case.py 中搜索 run() 函数,您将看到每个测试的 setup() 或 teardown() 用法,因此您可以在调用这些函数之前或之后添加任何您想要的内容。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 谢谢@chepner。我想到了这个解决方案,但没有满足我对通用实现的要求。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 2021-10-19
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多