【问题标题】:Run pytest test suite against multiple database versions针对多个数据库版本运行 pytest 测试套件
【发布时间】:2020-01-25 16:55:42
【问题描述】:

我构建了一个在后端使用数据库的应用程序。对于集成测试,我在 Docker 中启动数据库并使用 pytest 运行测试套件。

我使用带有autouse=True 的会话范围固定装置来启动 Docker 容器:

@pytest.fixture(scope='session', autouse=True)
    def run_database():                     
        # setup code skipped ...

        # start container with docker-py
        container.start()

        # yield container to run tests
        yield container

        # stop container afterwards
        container.stop()

我使用另一个会话范围的夹具将数据库连接传递给测试函数:

@pytest.fixture(scope='session')
def connection():
    return Connection(...)

现在我可以运行一个测试函数了:

def test_something(connection):
    result = connection.run(...)
    assert result == 'abc'

但是,我想针对多个不同版本的数据库运行我的测试函数。

我可以在 run_database() 夹具中运行多个 Docker 容器。如何参数化我的测试函数,以便它们针对两个不同的 connection() 固定装置运行?

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    @Guy 的回答有效!

    我找到了解决该问题的另一种方法。可以对夹具进行参数化。每个使用夹具的测试函数都会运行多次:https://docs.pytest.org/en/latest/fixture.html#parametrizing-fixtures

    因此,我参数化了connection() 函数:

    @pytest.fixture(scope='session', params=['url_1', 'url_2'])
    def connection(request):
        yield Connection(url=request.param)
    

    现在每个使用connection 夹具的测试函数都会运行两次。优点是您不必更改/调整/标记现有的测试功能。

    【讨论】:

      【解决方案2】:

      您可以发送一个产生连接的函数并使用@pytest.mark.parametrize 传递它。如果您将run_database() 的范围更改为class,它将在每个测试中运行

      def data_provider():
          connections = [Connection(1), Connection(2), Connection(3)]
          for connection in connections:
              yield connection
      
      
      @pytest.fixture(scope='class', autouse=True)
      def run_database():
          container.start()
          yield container
          container.stop()
      
      
      @pytest.mark.parametrize('connection', data_provider())
      @pytest.mark.testing
      def test_something(connection):
          result = connection.run()
          assert result == 'abc'
      

      如果您将@pytest.mark.parametrize('connection', data_provider()) 添加到run_database(),连接也会被传递到那里。

      【讨论】:

      • 感谢您的回答,这行得通!但是,我没有弄清楚如何在其他测试模块中导入data_provider() 函数。我找到了一个不同的解决方案,并将发布另一个答案以供参考。
      • @MartinPreusse 你的意思是你的文件中有几个test_?还是几个 .py 文件,每个文件都有一个测试?
      • 我在几个文件夹中有几个.py 文件(它们都包含几个test_ 函数)。测试文件的文件夹不应该是 Python 包,所以我不知道如何导入。
      • @MartinPreusse 您可以将data_provider() 放在不同的文件中,甚至是conftest.py,然后从那里导入。
      猜你喜欢
      • 1970-01-01
      • 2012-02-05
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      相关资源
      最近更新 更多