0

I'm writing an automated test in Django to check that a webhook is working on the application. The test sends a bunch of JSON to the webhook and will check that the call has been logged in the database. The problem I'm hitting however is that the test calls the http://localhost URL and the data is thus saved in my local dev database and not in the temporary database created by the test. So I now have no way to check the call has been received.

Whats the right solution for this?

from django.test import TestCase
import requests
from monzo.models import Transaction, RequestLog

class WebhookChecks(TestCase):
    fixtures = ['db.json', ]
    def test_simple_expense(self):

        my_json = '{"type": "transaction.created", REMOVED FOR SECURITY }'

        url = 'http://localhost/some_url/webhook/'
        headers = {'Content-Type': 'application/json'}
        r = requests.post(url, data=my_json, headers=headers)

        if not "200" in str(r):
            print("Something didn't work out. Error: "+str(r))

        self.assertTrue("200" in str(r))


rcx935
  • 217
  • 5
  • 15

1 Answers1

3

Use Djangos Client with which you can perform requests in your tests.

Example:

from django.test import Client

c = Client()
c.get('/some_url/..')

Another way is to use Djangos LiveServerTestCase.

You can use self.live_server_url instead of directly writing http://localhost.

This testcase sets up a live server which listens to localhost.

wfehr
  • 2,185
  • 10
  • 21
  • No need for a LiveServerTestCase here - it will work just as well with the test client (well, it should at least). – bruno desthuilliers Apr 28 '20 at 12:09
  • @brunodesthuilliers right, adjusted the answer to use the built-in `Client`. – wfehr Apr 28 '20 at 12:15
  • I used the LiveServerTestCase which worked fine. With the built in Client() could that be used to POST JSON though? – rcx935 Apr 28 '20 at 12:33
  • @rcx935 As of the [docs](https://docs.djangoproject.com/en/3.0/topics/testing/tools/#django.test.Client.post) you should be able to post json, yes. – wfehr Apr 28 '20 at 12:40