0

我正在 Django 中编写一个自动化测试,以检查 webhook 是否在应用程序上工作。测试将一堆 JSON 发送到 webhook 并检查调用是否已记录在数据库中。然而,我遇到的问题是测试调用了http://localhost URL,因此数据保存在我的本地开发数据库中,而不是测试创建的临时数据库中。所以我现在没有办法检查电话是否已接到。

什么是正确的解决方案?

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))


4

1 回答 1

3

使用可以在测试中执行请求的Djangos客户端。

例子:

from django.test import Client

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

另一种方法是使用 Django 的LiveServerTestCase

您可以使用self.live_server_url而不是直接编写http://localhost.

这个测试用例设置了一个监听本地主机的实时服务器。

于 2020-04-28T12:04:13.853 回答