Django REST Framework: how to properly use the HyperlinkedModelSerializer url field in unit tests

Viewed 3876

So I have models Actor and Role and a default REST API using Viewsets and the HyperlinkedModelSerializer.

My goal: a unit test that creates a Role with an associated Actor.

My test code is currently:

def test_post_create_role_for_actor(self):

    # default actor
    actor = ActorFactory() 

    # inherits HyperlinkedModelSerializer
    actor_serialized = ActorSerializer(actor) 

    postdata = {
        'role': 'mydummyrole',
        'actor': actor_serialized.data['url']
    }

    ret = self.client.post(self.url, json.dumps(postdata), content_type='application/json')

    self.assertEqual(ret.status_code, 201)
    self.assertTrue(Role.objects.filter(role='mydummyrole', actor_id=actor.id).exists())

Now this looks very ugly to me, especially the serialization to retrieve the generated url field. In fact, I get a deprecation warning:

DeprecationWarning: Using HyperlinkedIdentityField without including the request in the serializer context is deprecated. Add context={'request': request} when instantiating the serializer.

But the "url" field as generated by the serializer seems unrelated to any request. What is the proper way to fetch this field? I feel that I'm missing a concept here. Or two.

TIA!

1 Answers
Related