I am developing an API with Django, and I also want to test it, but I am having some trouble doing that. I need to test that to a given URL, what is returned is what I expect, and I want to do so with APITestCase of django rest framework.
The endpoint is something similar: http://localhost:5000/api/v1/rest_of_url/
When I type it in the browser, it return something similar:
{"count": 1, "next": null, "previous": null, "results": [{"stuff": 3, "stuff2": "adf", "stuff3": "asdf", "stuff4": "ff"}]}
So, to test that I wrote the following code in Django:
class TargetApiTestCase(APITestCase):
def test_get(self):
response = self.client.get("/api/v1/rest_of_url/", format='json')
print(response)
print(response.content)
print(response.status_code == status.HTTP_200_OK)
As response I get the following output from the prints statements:
<JsonResponse status_code=200, "application/json">
b'null'
True
But I should get some data, to check. I know that after that I have to query the db to check and use self.assertEqual
, but for now my problem is retrieving data via get
Maybe it is only a problem of settings.
I tried require responde.data, but it responded with an error.
Please, can someone help me? Thank
CodePudding user response:
I couldn't get anything because the database used for testing is only a cached database, created and eliminated immediately after the test is performed.
So, if you want some data to retrieve or use, you need to put them inside the database with the startUp method.
An example for Django can be to put them with some Django ORM query, and then check them, as in the following example:
class TestApiEndpoint(APITestCase):
name = "test"
surname = "test"
description = "Very long text as description"
def setUp(self):
CustomUser.objects.create(
name=self.name,
surname=self.surname,
description=description,
)
def test_get(self):
response = self.client.get("/api/v1/rest_of_url/", format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()["results"]
self.assertEqual(len(data), 1)
self.assertEqual(data[0]['name'], self.name)
....