1

I'm new to testing and I spent a day finding a solution for my problem but I couldn't find any. this is my serializer

serilaizer.py

class LeadSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        user = self.context['user']

        return Lead.objects.create(organizer=user.organizeruser, **validated_data)

    class Meta:
        model = Lead
        fields = ['id', 'first_name', 'last_name', 'age', 'agent', 'category', 'description', 'date_added',
                  'phone_number', 'email', 'converted_date'
                  ]

I have two types of users, organizer, and agent. organizer can create a lead but agent can't. and as you see I don't have organizer field. authenticated user will be added to the organizer field when a Lead is created.

test.py

    def test_if_lead_exist_return_200(self, api_client, leads_factory, user_factory):
        user = user_factory.create(is_organizer=True)
        api_client.force_authenticate(user=User(is_staff=True))

        lead = leads_factory.create()

        serializer = LeadSerializer(context={'request': user})
        print(serializer)
        # here I can see the user

        response = api_client.get(f'/api/leads/{lead.id}/', )

        assert response.status_code == status.HTTP_200_OK

        assert response.data == {
            'id': lead.id,
            'first_name': lead.first_name,
            'last_name': lead.last_name,
            'age': lead.age,
            'organizer': lead.organizer.id,
            'agent': lead.agent.id,
            'category': lead.category.id,
            'description': lead.description,
            'date_added': lead.date_added,
            'phone_number': lead.phone_number,
            'email': lead.email,
            'converted_date': lead.converted_date,

        }

because there is no organizer field in the serialzier test won't pass and this is the result of the test

enter image description here

what can I do here? can I pass the organizer user to the response?

1 Answer 1

1

You should add the organizer into the fields.

class LeadSerializer(serializers.ModelSerializer):
    class Meta:
        model = Lead
        # here I added the `organizer` field
        fields = ['id', 'first_name', 'last_name', 'age', 'agent', 'category', 'description', 'date_added', 'phone_number', 'email', 'converted_date', 'organizer']

    def create(self, validated_data):
        ...
        
Sign up to request clarification or add additional context in comments.

1 Comment

I removed the organizer field coz I didn't want the organizer user to see this field. anyway, I added it again and made it read-only and problem solved. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.