【问题标题】:Interval between tests in pytestpytest 中的测试间隔
【发布时间】:2018-05-25 23:39:57
【问题描述】:

是否有在 pytest 中添加测试间隔的常见做法?目前集成测试失败,但如果单独运行测试,则可以正常工作。

【问题讨论】:

    标签: sleep pytest intervals


    【解决方案1】:

    如果您想在模块中拆解模块的每个功能

    import time
    def teardown_function(function):   # the function parameter is optional
        time.sleep(3)
    

    如果你想在一个类中对类的每个方法进行拆卸,你有两个选择。

    1. 在此您无法访问调用的方法:
    class TestClass:
        def teardown(self):
            time.sleep(1)
    
    1. 如果您需要访问它:
    class TestClass:
        def teardown_method(self, method):
            print(method)
            time.sleep(1)
    

    如果您想要一个将在课程结束后调用一次的拆卸:

    @classmethod
    def teardown_class(cls):
        print(cls)
        time.sleep(2)
    

    所有这些方法都以相同的方式进行设置。你可以看到the documentation。对于更复杂的实现,请使用 fixtures

    【讨论】:

      【解决方案2】:

      您可以在 pytest 中使用 autouse 固定装置在测试用例之间自动休眠:

      @pytest.fixture(autouse=True)
      def slow_down_tests():
          yield
          time.sleep(1)
      

      这个fixture将自动用于所有测试用例,并将执行到一个测试用例,因此它可以正常运行,但是当测试完成时,执行将返回到这个fixture并运行sleep。

      【讨论】:

        【解决方案3】:

        可以在每个测试的teardown方法中插入time.sleep(1),即:

        class TestClass:
            def setup(self):
                pass
        
            def teardown(self):
                time.sleep(1) # sleep for 1 second
        

        【讨论】:

          猜你喜欢
          • 2020-12-14
          • 2018-02-07
          • 1970-01-01
          • 2018-04-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多