Unitest DRF with CONTEXT
I am wondering if anyone could help me with the appropriate way to create a unitest in DRF when using context inside a serializer.
as you can see in the serializer below, I am adding a field called distance to my serializer.
class CompanySerializer(serializers.ModelSerializer): """Serializer for companies.""" distance = serializers.SerializerMethodField() class Meta: model = Company fields = ['id', 'company_name', 'lat', 'long', 'logo', 'distance']
def get_distance(self, company):
"""Return context"""
print(self.context)
return self.context['distances'][company.pk]
Then when calling the unitest I get an error: KeyError: 'distances'
COMPANY_URL = reverse('company:company-list')
def test_company_list_limited_to_user(self):
"""Test list of companies is limited to authenticated user."""
other_user = create_user(
email='other@example.com', password='password123'
)
create_company(user=other_user)
create_company(user=self.user)
res = self.client.get(COMPANY_URL)
companies = Company.objects.filter(user=self.user)
serializer = CompanySerializer(companies, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
Is there a better way to write this test, so it can pass? I did check and the context distance is create and passed to the serializer with no issue, but the test is not passing :/
Tks a lot!
Kind regards Victor Almeida