Экземпляр модели не создается при срабатывании сигналов после сохранения при тестировании с помощью pytest

Пока я пытался протестировать свою модель, она была связана с файлом сигналов, где при вызове функции save() на этой модели срабатывает файл сигналов, а затем в этом файле сигналов также создается экземпляр на другой модели.

Но когда я пытаюсь протестировать с помощью Py-test, factory boy и fixtures, экземпляр, который создавался в файле сигналов для разных моделей, не срабатывает

а также User является внешним ключом в модели кандидата.

Ниже приведен код для справки:

signals.py

@receiver(post_save, sender=Candidate, dispatch_uid="create_candidate_user")
def create_candidate_user(instance, **kwargs):
    """
    Create candidate user does not exist
    """
    if instance.user is None:
        try:
            user = None
            if instance.email or instance.mobile:
                email_user = None
                mobile_user = None
                mobile = instance.mobile
                if instance.mobile and not instance.mobile.startswith("+"):
                    mobile = f"+91{instance.mobile}"
                if instance.email:
                    try:
                        email_user = User.objects.get(email=instance.email)
                    except User.DoesNotExist as ode:
                        print(ode, f"for {instance.email}")

                if mobile:
                    try:
                        mobile_user = User.objects.get(mobile=mobile)
                    except User.DoesNotExist as ode:
                        print(ode, f"for {mobile}")

                if email_user and mobile_user:
                    if email_user != mobile_user:
                        raise Exception(
                            f"Duplicate Users found! ids are: {email_user.id} and {mobile_user.id}"
                        )
                    else:
                        user = email_user
                elif email_user or mobile_user:
                    if email_user is not None:
                        user = email_user
                        if mobile:
                            user.mobile = mobile
                    if mobile_user is not None:
                        user = mobile_user
                        if instance.email:
                            user.email = instance.email
                else:
                    query = {}
                    if instance.email:
                        query["email"] = instance.email
                    if mobile:
                        query["mobile"] = mobile
                    user = User.objects.create(
                        password=BaseUserManager().make_random_password(),
                        **query,
                    )
                if user:
                    existing_role = get_user_role(user.id)
                    if "Candidate" not in existing_role:
                        role = Role.objects.get(name="Candidate")
                        user.new_role.add(role)
                    user.name = instance.name
                    if instance.company and instance.company != user.company:
                        user.company = instance.company
                    user.save()
                    Candidate.objects.filter(id=instance.id).update(user=user)
            else:
                raise Exception("Email or Mobile number is not provided")

        except Exception as ex:
            raise Exception(ex)

factories.py

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

class CandidateFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Candidate

    name = "Aman Mishra"
    email = "aman.mishra@codemonk.in"
    mobile = "+918439803019"
    user = factory.SubFactory(UserFactory)

conftest.py

from tests.factories import UserFactory, CandidateFactory, RoleFactory, PermissionFactory

register(UserFactory)
register(RoleFactory)
register(CandidateFactory)
register(PermissionFactory)

# User app model Fixture

@pytest.fixture()
def user_creation(db, user_factory):
    user = user_factory.create()

@pytest.fixture()
def roles_create_candidate(db, role_factory):
    roles = role_factory.create(name="Candidate")
    return roles


#Candidate app model Fixture

@pytest.fixture
def candidate_create(db, candidate_factory):
    candidate = candidate_factory.create()
    return candidate

test_candidate_models.py

def test_candidate_model_str(roles_create_candidate , candidate_create,):
    assert candidate_create.__str__() == 'Aman Mishra'

Моя конечная цель состоит в том, чтобы при создании кандидата также создавался пользователь в базе данных, чего сейчас не происходит.

Кто-нибудь может подсказать мне, как это отладить,

также любой хороший ресурс для изучения pytest с django может кто-нибудь посоветовать это тоже.

Моя ошибка, он создавался в тесте, я просто использовал другой o илим запрос для получения экземпляра.

Вернуться на верх