Use test database database for views testing

Viewed 92

I am writing tests for my django application views and i am a beginner at this. I know that before running tests a new database is generated which only contains data that is being created at the time of running of tests but in my view's tests i am making API calls by url on my server which is using my default database not the test database in following way.

  def test_decline_activity_valid_permission(self):
        url = 'http://myapp:8002/api/v1/profile/' + self.profileUUID + '/document/' + \
              self.docUUID + '/decline/'
        response = requests.post(
            url,
            data=json.dumps(self.payload_valid_permission),
            headers=self.headers,
        )
        self.assertEquals(response.status_code, status.HTTP_201_CREATED)

i want to know that if we can use test database for our testing our views or not. And what is difference between using request and using Client?

1 Answers

You could try using Django's LiveServerTestCase. That works like TransactionTestCase but will start up a server on localhost pointing at the test database. It gets started/stopped at the beginning/end of each test.

You could then configure the URL in your test to point at that local server. Django provides self.live_server_url for accessing the URL of the server.

As mentioned in the comments, Django's test client allows you to test views without making real HTTP requests. Whereas the requests library that you're using in your test, will send and receive real HTTP request and responses.

Related