【问题标题】:pytest: Parametrizing from function output / from directory structurepytest:从函数输出/从目录结构参数化
【发布时间】:2020-10-10 11:23:14
【问题描述】:

我正在尝试从目录结构构建测试用例参数和预期输出。目录结构如下:

__init__.py
foo.py
testing/
├── test_foo/
│   ├── __init__.py
│   ├── case-0001/
│   │   ├── input_1.json
│   │   ├── intput_2.json
│   │   └── output.json
│   ├── case-0002/
│   │   ├── input_1.json
│   │   ├── intput_2.json
│   │   └── output.json
│   └── test_fooFunc.py

我已经写了一个函数,我们称之为makeIO(..),它从每个测试用例中获取文件并返回一个格式为([input_1_contents, input_2_contents], [output_contents])的元组。

我正在努力将元组传递给 test_foo.py。到目前为止,这是我所拥有的:

@pytest.fixture
def makeIO():
    ...
    return IOtuple

IOtuple = makeIO(..)


@pytest.mark.parametrize("test_input,expected", IOtuple)
def test_two(test_input, expected):
    assert foo.fooFunc(test_input) == expected

奇怪的部分:一切正常并且测试通过当且仅当我从 @ 删除 @pytest.fixture 装饰器987654328@。如果我把它留在那里,我会收到这个错误:Fixture "makeIO" called directly. Fixtures are not meant to be called directly, but are created automatically when test functions request them as parameters.

有没有更 Pythonic 和优雅的方式来实现我的目标?是否会推荐任何替代目录结构或功能?另外,我认为我只是错过了固定装置的要点,希望能澄清一下为什么以及如何使用它们(文档没有为我澄清)。


免责声明:我对 pytest 完全陌生,因此我感谢所有有助于拉平学习曲线的资源。

【问题讨论】:

  • 没错:你不能直接调用一个fixture,你必须把它传递给一个测试或者另一个fixture。对于参数,您只需使用普通函数,因为装饰器是在加载时评估的——这是执行此操作的标准方法。至于一般的固定装置:documentation 也有一些示例,对于关于固定装置的具体问题,SO 上有很多答案。

标签: python unit-testing pytest regression-testing parametrized-testing


【解决方案1】:

从我的函数中删除 @pytest.fixture 正是我想要的,现在可以通过从该函数获得的值对函数进行参数化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2014-12-31
    相关资源
    最近更新 更多