对我来说,这听起来很像参数化测试,pytest支持这一点,基本上你可以编写一个测试,并提供输入参数,以及预期的。
编写泛型测试可能会引入一些逻辑(正如您在我的示例中看到的),但在我看来,您可以接受这种逻辑
@pytest.mark.parametrize('is_admin,expected_status_code,expected_error', [
(True, 200, {}),
(False, 401, {"fail": "login"})
])
def test_sample(is_admin, expected_status_code, expected_data):
# do your setup
if is_admin:
user = create_super_user()
else:
user = normal_user()
# do your request
response = client.get('something')
# make assertion on response
assert response.status_code == expected_status_code
assert response.data == expected_data
您还可以有多个参数层,例如:
@pytest.mark.parametrize('is_admin', [
True,
False
])
@pytest.mark.parametrize('some_condition,expected_status_code,expected_error', [
(True, 200, {}),
(False, 401, {"fail": "login"})
])
这将执行对isu admin(True/False)和其他参数的每个组合的测试,不错吧?
在此处查看文档
pytest parametrize tests
如果不使用pytest,请检查执行类似操作的库
Parameterized testing with any Python test framework