Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UUID fails unit pytest due to formatting?

I am returning a user’s UUID in my serializier and this works fine. However, when writing a unit test to test this return the test fails despite them being called the same way. Below is a simplified version of my code.

My serializers.py:

class UserSerializer(serializers.ModelSerializer):
    user_sso = serializers.SerializerMethodField("get_user_sso")

    class Meta:
        model = get_user_model()
        fields = (
            "user_sso",
        )

    def get_user_sso(self, user):
        return user.profile.sso_id

My unit test in test_views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class TestUserAPIView(BaseAPIViewTest):
    factory = factories.UserFactory

    def expected_response(self, user):
        return {
            "user_sso": user.profile.sso_id,
        }

The failed test message (the user generated from a factory is the top one):

E         -   'user_sso': UUID('f696d740-bdd5-43a3-8f58-406b7a1e117d')},
E         ?               -----                                      -
E         +   'user_sso': 'f696d740-bdd5-43a3-8f58-406b7a1e117d'},

How do I make this test pass?

I do not have the word ‘UUID(‘ at the begining of my current output which looks to be the problem but I’m not sure how to remove this without everything making a string? Many thanks.

>Solution :

Please take the outcome of the str(…) as response, otherwise it will take the UUID itself, so:

class UserSerializer(serializers.ModelSerializer):
    user_sso = serializers.SerializerMethodField("get_user_sso")
    
    # …
    
    def get_user_sso(self, user):
        return str(user.profile.sso_id)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading