Django unit tests fail when ran as a whole and there is GET call to the API

316 views Asked by At

I am facing an issue when I run the tests of my django app with the command

python manage.py test app_name OR

python manage.py test

All the test cases where I am fetching some data by calling the GET API, they seem to fail because there is no data in the response in spite of there being in the test data. The structure which I have followed in my test suite is there is a base class of django rest framework's APITestCase and a set_up method which creates test objects of different models used in the APIs and I inherit this class in my app's test_views class for any particular API such as

class BaseTest(APITestCase):
  def set_up(self):
       '''
       create the test objects which can be accessed by the main test 
       class.
       '''
       self.person1=  Person.objects.create(.......)

class SomeViewTestCase(BaseTest):
  def setUp(self):
        self.set_up()
  def test_some_api(self):

    url='/xyz/'
    self.client.login(username='testusername3',password='testpassword3')

    response=self.client.get(url,{'person_id':self.person3.id})
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    self.assertEqual(len(response.data),6)

So whenever I run the test as ./manage.py test abc.tests.test_views.SomeViewTestCase it works fine, but when I run as ./manage.py test abc

The test above response.data has 0 entries and similarly, with the other tests within the same class the data is just not fetched and hence all the asserts fail.

How can I ensure the successful run of the test when they are run as a whole because during deployment they have to go through CI?

The versions of the packages and system configuration are as follows:

Django Version -1.6

Django Rest Framework - 3.1.1

Python -2.7

Operating System - Mac OS(Sierra)

Appreciate the help.Thanks.

1

There are 1 answers

1
AudioBubble On

Your test methods are executed in arbitrary order... And after each test, there's a tearDown() method that takes care to "rollback to initial state" so you have isolation between tests execution.

The only part that is shared among them is your setUp() method. that is invoked each time a test runs.

This means that if the runner start from the second test method and you only declare your response.data in your first test, all tests are gonna fail apart the posted one.

Hope it helps...