python - 使用 django 模型作为 pytest 参数化的参数
问题描述
我正在尝试测试是否允许不同业务组的用户使用 pytest 的参数化功能在 web 应用程序中执行操作,但我无法访问参数化中的固定装置值。
第一种方法:
@pytest.fixture
def mike_user():
user = User(username="mike", email="mike@test.com",)
user.set_password("test")
user.save()
return user
@pytest.fixture
def mike_business_group(mike_user):
bg = BusinessGroup.objects.create(
name="Mike Business Group", user=mike_user
)
bg.save()
return bg.pk
@pytest.mark.django_db
@pytest.mark.parametrize(
"resource, user, serialized_data, success",
[
(
"/business/",
mike_user,
{
"name": "New business",
"description": "Hi Stackoverflow",
"group": mike_business_group,
},
True,
),
],
)
def test_create_model_with_related_owner(
apiclient, user, resource, serialized_data, success
):
apiclient.force_authenticate(user=user)
response = apiclient.post(resource, data=serialized_data)
assert (
response.status_code == 201
) is success
看到lazy_fixture 包,我尝试了以下方法,但它只成功解决mike_user
了第二个分辨率的以下字典值:
{'name': 'Marina L4bs', 'description': 'Happy BioHacking', 'group': <LazyFixture "mike_business_group">}
第二种方法:
@pytest.mark.django_db
@pytest.mark.parametrize(
"resource, user, serialized_data, success",
[
(
"/business/",
pytest.lazy_fixture("mike_user"),
{
"name": "Marina L4bs",
"description": "Happy BioHacking",
"group": pytest.lazy_fixture('mike_business_group'),
},
True,
),
],
)
解决方案
作为第三种方法,我为参数化的第二个参数创建了一个夹具,而不是尝试延迟加载 business_group 的值,但我认为即使它有效,它也不是正确的方法,应该存在更好的方法.
@pytest.fixture
def business_creation_for_mike_business_group(mike_business_group):
return {
"name": "Marina L4bs",
"description": "Happy BioHacking",
"group": mike_business_group,
}
@pytest.mark.django_db
@pytest.mark.parametrize(
"resource, user, serialized_data, success",
[
(
"/business/",
pytest.lazy_fixture("mike_user"),
pytest.lazy_fixture("business_creation_for_mike_business_group"),
True,
),
],
)
推荐阅读
- python - Python subprocess.poll() 问题
- mysql - 我的代码是处理 NodeJS mysql 查询的正确方法吗?
- python - biopython 1.78 MarkovModel.train_visible() training_data 是什么类型的?
- php - 路由器类不返回数组似乎是一些正则表达式问题
- javascript - 如何将数据从 Javascript 推送到 Django 后端
- php - 为什么连接不上
- python - Python List 列表的迭代列表
- powershell - PowerShell:如何在目录树上递归测试路径?
- android - 如何在android中使用单击创建自定义视图
- django - Django - 当用户多次单击提交按钮时防止重复的 POST 请求?