【问题标题】:How can I specify a configuration for setting up pytest fixtures when I start the pytest test runner?启动 pytest 测试运行程序时,如何指定设置 pytest 固定装置的配置?
【发布时间】:2019-10-14 19:20:55
【问题描述】:

我的测试依赖于特定环境(例如 dev、qa、生产)的 id

在我的测试中,我使用fixtures 使一组ID 在会话中可用。

@pytest.fixture(scope="session", autouse=True)
def test_entities(request):
    test_entities = None
    path = os.path.join(base_path, "data/test_entities_dev.json")        ...
    ... 
    <Get from File>
    ...
    return test_entities

我为给定测试检索的测试实体将取决于环境。我想指定在我开始 pytest 会话时要打开的文件。例如“data/test_entities_qa.json”而不是“data/test_entities_dev.json”。如何使用 pytest 做到这一点?

【问题讨论】:

    标签: python pytest fixtures


    【解决方案1】:

    如果我理解正确,您可以在每个环境中提供不同的命令行参数。在这种情况下,您应该查看Okken's answer

    【讨论】:

      【解决方案2】:

      我的完整解决方案借用this SO post

      1) 在 conftest.py 中使用 pytest 钩子

      # conftest.py
      def pytest_addoption(parser):
          parser.addoption("--env", action="store", default="dev")
      

      2) 在fixtures.py 中使用这种模式:

      @pytest.fixture(scope="session", autouse=True) 
      def get_env(pytestconfig):
          return pytestconfig.getoption("env")
      
      @pytest.fixture(scope="session", autouse=True)
      def test_entities(request, get_env):
          filename = "data/dev_entities.json"
          if get_env == 'qa':
              filename = "data/qa_entities.json"
          elif get_env == 'prod':
               filename = "data/prod_entities.json"
          ...
          <Get entities from file>
          ...
          return entities
      

      【讨论】:

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