Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to test drf serializer validate

I think two way how can i test drf serializer validate

following is my serializer validate code

def validate_md5(self, md5):
    if len(md5) != 40:
        raise serializers.ValidationError("Wrong md5")
    return md5

and it is test code

1)

def test_wrong_validate_md5_2(self):
    url = reverse('apk-list')
    response = self.client.post(url, {'md5':'test'}, format='json')
    self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

2)

def test_wrong_validate_md5(self):
    serializer = ApkSerializer(data=self.apk)

    if len(self.apk.get('md5')) != 40:
        self.assertEqual(serializer.is_valid(), False)
    else:
        self.assertEqual(serializer.is_valid(), True)

what is better than another? or is there best solution?

and ... I practice test-driven coding. is it necessary to write test code as above

like image 555
fuzes Avatar asked Mar 14 '18 05:03

fuzes


1 Answers

The first method actually doesn't test serializer class. It's testing entire 'apk-list' endpoint. Since error may be raised not only in serializer's validate_md5 method, but in any other places even if self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) will be passed you cannot be sure that serializer worked as expected. So second method is preferabe. But instead of if/else in one test caseyou'd better create two different test case: one for correct data another for incorrect and also you can check if error indead related with md5 field:

def test_wrong_validate_md5(self):
    serializer = ApkSerializer(data=self.apk_wrong)
    self.assertEqual(serializer.is_valid(), False)
    self.assertEqual(set(serializer.errors.keys()), set(['md5']))

def test_correct_validate_md5(self):
    serializer = ApkSerializer(data=self.apk_correct)
    self.assertEqual(serializer.is_valid(), True)

UPD

It's also possible to use first method, but in this case you need to parse response data. And check if this data contains error with 'md5' key, something like:

def test_wrong_validate_md5_2(self):
    url = reverse('apk-list')
    response = self.client.post(url, {'md5':'test'}, format='json')
    self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    self.assertEqual(response.data,{'md5': Wrong md5')
like image 141
neverwalkaloner Avatar answered Oct 13 '22 23:10

neverwalkaloner