0

我想用 Model Bakery 创建一个 Person 实例。我的 Person 模型如下所示:

User = get_user_model()

class Person(models.Model):
    user = models.OneToOneField(User, related_name="friend", on_delete=CASCADE)
    country = models.CharField(max_length=100)

我的 baker_recipes.py 看起来像这样:

from model_bakery.recipe import Recipe

User = get_user_model()
test_user = User(username="test_user")

person = Recipe(Person, user = test_user)

我的 tests.py 看起来像这样:

import pytest
from model_bakery import baker

@pytest.mark.django_db()
class TestPerson:
    def setup(self):
        self.person = baker.make_recipe("company.tests.person")

    def test_country_access(self):
        assert True

但是,当我使用此设置运行 pytest 时,出现以下错误:

django.db.utils.IntegrityError: insert or update on table "company_person" violates foreign key constraint "company_person_user_id_4f1cc5d0_fk_auth_user_id"
DETAIL:  Key (user_id)=(411) is not present in table "auth_user".
4

1 回答 1

0
import pytest
from model_bakery import baker

@pytest.mark.django_db()
class TestPerson:
    def setup(self):
        **#replace this** 
        self.person = baker.make_recipe("company.tests.person")
        **#with this**
        self.person = baker.make(Person, ...optional_field_params)

    def test_country_access(self):
        assert a_condition_is_true
        #assert True is not logical here so comented out

NB with baker.make创建的实例在使用baker.prepare设置时被持久化到测试数据库, 另一方面它不会持久化

于 2022-03-03T15:46:45.127 回答