【问题标题】:PyTest - Specify cleanup tests in conftest.pyPyTest - 在 conftest.py 中指定清理测试
【发布时间】:2023-01-11 04:06:34
【问题描述】:

我正在测试需要通过客户端请求启动和关闭 gRPC 服务器的服务。在我的一组集成测试中,我需要指定一组应该在集合中运行任何给定测试之前发生的测试前和测试后操作。 理想情况下,我想将这些测试前/测试后方法保留在 conftest.py 中,或者将它们组织到单独模块中的它们自己的类中。

我可以通过在 conftest.py 中执行以下操作来指定应该运行的第一个测试(启动服务器的测试):

@pytest.fixture(scope="session", autouse=True)
def test_start_server():
    # code to start server

问题是,当我执行另一个测试模块时,仅执行 test_start_server 函数,而不执行文件中后续的 test_shutdown_request 函数:

def test_shutdown_request():
    # code to shutdown server

有没有办法指定要运行的最后一个测试(测试后操作)?
如果可能的话,我不想包含任何第三方依赖项或插件,因为我的项目已经足够了。

【问题讨论】:

    标签: python pytest integration-testing


    【解决方案1】:

    我认为你应该在你的固定装置https://docs.pytest.org/en/6.2.x/fixture.html#yield-fixtures-recommended中使用yield

    @pytest.fixture(scope="session", autouse=True)
    def server():
        # code to start server
        yield
        # code to stop server
    
    def test_some():
        # some tests
    
    def test_more():
        # some tests
    

    此代码为会话创建服务器一次,并在所有测试后关闭服务器。

    【讨论】:

      【解决方案2】:

      是的,可以指定要在集成测试中运行的最后一个测试(测试后操作)。一种方法是在 conftest.py 文件中结合使用 yield 语句和终结器。

      您可以使用 yield 定义启动 gRPC 服务器的夹具,以执行应在关闭服务器之前运行的测试。在终结器函数中,您可以指定应该运行的最后一个测试(关闭服务器的测试)。这是一个如何做到这一点的例子:

      @pytest.fixture(scope="session", autouse=True)
      def test_grpc_server():
          # code to start server
          yield
          # code to shutdown server
          test_shutdown_request()
          
      def test_shutdown_request():
          # code to shutdown server
      

      在此示例中,test_grpc_server fixture 启动 gRPC 服务器,yield 语句允许执行测试。测试完成后,执行终结器函数,依次调用 test_shutdown_request 函数,关闭服务器。

      也可以将 test_shutdown_request 保留在单独的模块或类中,并使用终结器来调用它。

      从 mymodule 导入 MyTestShutDown

      @pytest.fixture(scope="session", autouse=True)
      def test_grpc_server():
          # code to start server
          yield
          # code to shutdown server
          MyTestShutDown.shut_down()
      

      这样您就可以在单独的类、模块或函数中分离您的预测试和后测试操作,并使您的代码更易于维护。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多