如何使用参数化将dict传递给单元测试



我有一个dicts列表:

MY_LIST = [ 
{ 'key1': {'a': 1, 'b':2 } },
{ 'key2': {'a': 1, 'b':2 } } 
]

如何使用参数化将dict传递给django单元测试?例如

@parameterized.expand(MY_LIST):
def test_mytest(self, dict_item):
print(dict_item.items())

结果为AttributeError: 'str' object has no attribute 'items',因为dict正被转换为字符串。

如文档中所述:

The @parameterized and @parameterized.expand decorators accept a list or iterable of tuples or param(...), or a callable which returns a list or iterable

所以我会尝试将MY_LIST转换为:

MY_LIST = [ 
({ 'key1': {'a': 1, 'b': 2}},),
({ 'key2': {'a': 1, 'b': 2}},), 
]

这使得它成为一个元组列表,其中包含一个要应用于正在测试的方法的参数。

您可以创建一个NamedTuple来给您的参数密钥

from typing import NamedTuple
class TestParameters(NamedTuple):
firstParam: str
secondParam: int

@parameterized.expand([TestParameters(
firstParam="firstParam",
secondParam="secondParam"
)
]
def test(self, firstParam, secondParam):
...

如果你出于不同的原因需要它作为dict,你也可以做这个

@parameterized.expand([TestParameters(
firstParam="firstParam",
secondParam="secondParam"
)
]
def test(self, *args):
test_params = TestParams(*args)._asdict()

对我有用的是将dict打包到一个列表中(其中只有一个dict(。类似:

MY_LIST = [[d] for d in MY_LIST]

之后,您可能希望打开它(如:dict_item[0](,但并非如此

最新更新