python-3.x - 使用带有来自标记的参数的 pytest 夹具
问题描述
我尝试在 pytest 中创建一个测试用例。我想使用参数化夹具从 @pytest.mark.parametrize 装饰器获取参数并创建更多类型的测试。我的代码现在看起来:
@pytest.mark.parametrize(
"a",
["1", "2"],
ids=["a:1", "a:2"]
)
@pytest.mark.parametrize( # type: ignore
"fixture_a",
[{"b": 1}],
ids=["b:1"],
indirect=["fixture_a"],
)
def test_postgres_basic(fixture_a, a):
...
我想要什么?
我想将参数发送a
给fixture_a
这样的装置request.param
,而不是{"b": 1}
像{"b":1, a: "1"}
and之类的东西{"b":1, a: "2"}
。有可能以某种简单的方式吗?
谢谢
解决方案
a
另一种方法是在要传递给夹具的dict中手动定义值。
import pytest
@pytest.fixture
def fixture_a(request):
print(f"{request.param=}")
return request.param
@pytest.mark.parametrize(
"fixture_a, a",
[
({"a": 1, "b": 1}, "1"),
({"a": 2, "b": 1}, "2"),
],
ids=["a:1", "a:2"],
indirect=["fixture_a"],
)
def test_postgres_basic(fixture_a, a):
print(fixture_a, a)
输出
$ pytest -q -rP
..
[100%]
================================================================================================= PASSES ==================================================================================================
________________________________________________________________________________________ test_postgres_basic[a:1] _________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
request.param={'a': 1, 'b': 1}
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
{'a': 1, 'b': 1} 1
________________________________________________________________________________________ test_postgres_basic[a:2] _________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
request.param={'a': 2, 'b': 1}
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
{'a': 2, 'b': 1} 2
2 passed in 0.06s
推荐阅读
- javascript - jQuery DataTable - “处理中”不出现
- python - Error - Multi-Classification Neural Network using Keras
- reactjs - reactJS - TypeError: Cannot call a class as a function
- redis - 用windows安装文件打包redis
- php - OAI 验证错误
- r - 无法在包“SparkR”中加载 R 代码
- javascript - 在 JavaScript 中使用 ViewPort 作为单位
- android - SQLITE FTS 匹配中文本出现的实际数量
- webpack - Webpack 4 - 非 NPM 供应商目录
- postgresql - 在 postgresql 中使用 execute 将列数据存储在数组中