简体   繁体   中英

model instance not getting created on triggering signals post save when tested with pytest

While i was trying to test my model, it was linked to a signals file where when.save() is called on that model, the signals file is triggered and then a instance on different model is also created in that signals file.

But when i try to test with Py-test, factory boy and fixtures the instance that was getting created in the signals file for different model is not triggered.

and also User is a foreign key in the candidate model.

Below is the code for reference:

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'

What my end goal is that when a candidate is created a user should also be created in the db, which is not happening as of now.

So can anyone tell me how to debug this,

also any good resource for learning pytest with django can someone suggest that too.

My mistake, it was getting created in the test, i was just using a different o orm query to get the instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM