我正在使用unittest
库在 python 中编写测试,我有几个具有不同测试数据的测试环境。
- 存储测试参考数据的最佳方式是什么(我不想将它们放入“test*.py”文件中)?
- 有什么好的方法可以以特殊格式存储(调用方法的输入值,比较的输出值)?
有任何想法吗?
我正在使用unittest
库在 python 中编写测试,我有几个具有不同测试数据的测试环境。
有任何想法吗?
您可以编写一个装饰器,从您的自定义存储中检索数据并将其传递给实际的测试功能。我过去这样做过:
装饰者
from functools import wraps
def data_provider(fn_dp):
def test_decorator(fn_test):
@wraps(fn_test)
def wrapper(self, *args, **kwds):
for data in fn_dp():
try:
fn_test(self, **data)
except AssertionError, e:
raise(AssertionError('{0} - [{1}]'.format(e, data)))
return wrapper
return test_decorator
现在我可以像这样编写我的单元测试:
data = lambda: (
{
'input': '1234',
'expected_op': '1234'
},
{
'input': '1234',
'expected_op': '1234'
}
)
@helper.data_provider(data)
def test_something(self, input, expected_op):
self.assertEqual(input, expected_op)
现在装饰器将为所有数据点调用测试函数。
对于您的具体情况,请查看fn_test(self, **data)
. data_provider
而不是**data
您可以从自定义存储中读取并从此处调用测试功能。
接下来我的解决方案:我有一个存储类,在每次测试之前从 json 文件中获取测试数据(在 setUp 方法中调用):
def setUp(self):
self.data = self.storage.getDataFor(self._testMethodName)
def test_ftu_02_003(self):
self.assertEqual(self.data['title'], self.page.get_title())
self.assertEqual(self.data['header'], self.page.get_header())
和示例 json 文件示例,json 文件名与 py 文件名相同:
{
"test_ftu_02_003":{
"title":"example_title",
"header":"example_title"
}
}
所以我可以用每个环境的文件更改文件夹的路径,并且很容易从 python 代码重写 json 文件。
问题:那么输出数据呢?
答:所有数据都是输入数据(它去输入断言*)