I have a test class in Django Rest Framework which contains a function which passes the test if it is the only function in the class, or fails if it is one of two or more functions.
If I run the below code as is, i.e. def test_audio_list(self) function remains commented out, the test passes as per the two assert statements.
If I uncomment def test_audio_list(self) function and run the tests, the def test_audio_retrieve(self) function will fail with a 404 whilst def test_audio_list(self) will pass.
Here is my full test case (with def test_audio_list(self): commented out).
class AudioTests(APITestCase):
# setup a test user and a factory
# factory = APIRequestFactory()
test_user = None
def setUp(self):
importer()
self.test_user = User(username='jim', password='monkey123', email='jim@jim.com')
self.test_user.save()
# def test_audio_list(self):
# """
# Check that audo returns a 200 OK
# """
# factory = APIRequestFactory()
# view = AudioViewSet.as_view(actions={'get': 'list'})
#
# # Make an authenticated request to the view...
# request = factory.get('/api/v1/audio/')
# force_authenticate(request, user=self.test_user)
# response = view(request, pk="1")
#
# self.assertContains(response, 'audio/c1ha')
# self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_audio_retrieve(self):
"""
Check that audo returns a 200 OK
"""
factory = APIRequestFactory()
view = AudioViewSet.as_view(actions={'get': 'retrieve'})
# Make an authenticated request to the view...
request = factory.get('/api/v1/audio/')
force_authenticate(request, user=self.test_user)
response = view(request, pk="1")
self.assertContains(response, 'audio/c1ha')
self.assertEqual(response.status_code, status.HTTP_200_OK)
Running python manage.py test on the above will produce no errors. But if I uncomment def test_audio_list(self) function, def test_audio_retrieve(self) will fail with the following:
======================================================================
FAIL: test_audio_retrieve (api.tests.AudioTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/code/api/tests.py", line 96, in test_audio_retrieve
self.assertContains(response, 'audio/c1ha')
File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py", line 446, in assertContains
response, text, status_code, msg_prefix, html)
File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py", line 418, in _assert_contains
" (expected %d)" % (response.status_code, status_code)
AssertionError: 404 != 200 : Couldn't retrieve content: Response code was 404 (expected 200)
Note. If I change the order of the functions in the class, i.e. place def test_audio_retrieve(self) before def test_audio_list(self), the result is still the same.
I'm assuming I must be doing something wrong here, but I just cannot put my finger on it.
Any help is much appreciated.
Cheers,
C