1 回答

TA贡献1779条经验 获得超6个赞
对我来说,这听起来很像参数化测试,pytest 对此有支持,基本上你可以编写一个测试并提供输入参数,以及预期的。因此,您只需编写一个测试,但足够通用以支持不同的参数,从而减少了需要维护的代码。在幕后 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"})
])
这将为 is_admin (True/False) 和其他参数的每个组合执行测试,好吗?
添加回答
举报