gbrennon
gbrennon

Reputation: 979

What to test in a simple DRF API?

So, I'm not a test expert and sometimes, when using packages like DRF, I think what should I test on the code...

If I write custom functions for some endpoints, I understand I should test this because I've written this code and there are no tests for this... But the DRF codebase is pretty tested.

But if I'm writing a simple API that only extends ModelSerializer and ModelViewSet what should I be testing?

The keys in the JSON serialized? The relations?

What should I be testing?

Upvotes: 1

Views: 1001

Answers (2)

Deepansh
Deepansh

Reputation: 73

Testing your ModelSerializer, Check the request payload against your expected Model fields.

Testing your ModelViewSet, Check the response HTTP_Status_Code against the expected Status codes for your viewsets. You can also test for your response data.

A good resource - https://realpython.com/test-driven-development-of-a-django-restful-api/

Upvotes: 1

Mohammad hp
Mohammad hp

Reputation: 526

Even if you're only using automated features and added absolutely no customization on your serializer and viewset, and it's obvious to you that this part of the code works smoothly, you still need to write tests.

Code tends to get large, and some other person might be extending your code, or you might go back to your code a few months later and not remember how your implementation was. Knowing that tests are passing will inform other people (or yourself in the distant future) that you're code is working without having to read it and dive into the implementation details, which makes your code reliable.

The person using your API might be using it at a service and not even be interested in what framework or language you used for implementation, but only wants to be sure that the features he/she requires work properly. How can we ensure this? One way is to write tests and pass them.

That's why it's very important to write complete and reliable tests so people can safely use or extend your code knowing that the tests are passing and everything is OK.

Upvotes: 2

Related Questions