【问题标题】:Producing multiple pytest fixtures生产多个 pytest 夹具
【发布时间】:2017-06-14 22:08:53
【问题描述】:

我正在测试一些带有几个参数的工程方程,这些参数返回浮点数组。为了测试所有情况,我想使用一些固定装置。我目前将测试用例存储在一个简单的文件中,加载它们,然后返回感兴趣的测试用例。有没有更好的方法来做到这一点?

@pytest.fixture(params=[0, 1, 2])
def test_case(request):
    fpath = pathlib.Path(__file__).parent
    fpath /= 'test_data' / 'test_cases.json'
    test_cases = json.load(fpath.open())
    return test_cases[request.param]

def test_function(test_case):
    # Run the test

【问题讨论】:

  • 我不确定我是否理解了这个问题。为什么不直接在 python 文件中内联数组?
  • 因为Python文件中的数据相当复杂
  • 你的意思是 JSON 文件?如果是,并且您必须将数据保存在 JSON 文件中,那么就差不多了。您可以通过例如使用pytest_generate_tests 钩子扫描目录并为那里的每个文件运行测试来对此代码进行轻微改进。这样当你创建一个新的 JSON 文件时,它会自动添加到测试中。

标签: python pytest fixtures


【解决方案1】:

您可以使用pytest_generate_tests

def pytest_generate_tests(metafunc):
    if 'test_case' in metafunc.fixturenames:
        fpath = pathlib.Path(__file__).parent
        fpath /= 'test_data' / 'test_cases.json'
        test_cases = json.load(fpath.open())
        metafunc.fixturenames.append('test_case')
        metafunc.parametrize(
            'test_case',
            test_cases)

【讨论】:

  • 但实际上它不会改善任何东西.. 你能澄清一下为什么你想要“更好的方法”,你的方法有什么问题吗?
  • 我只是在寻找改进我的方法/风格的方法。我找不到任何像我一样生成多个测试的文档,所以我想我可能错误地考虑了这个问题。
猜你喜欢
  • 2021-09-11
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多