我有一个 Django 应用程序,需要处理以下内容:
- 我的一个观点是,需要向同一应用程序的另一个 URL 端点发出 POST 请求。
- 为此,我使用了该
requests
模块。我组装我需要调用的端点的 URL,转储 POST 参数,然后执行调用。 - 这在大多数情况下都可以正常工作,但是在测试时会失败,因为与我交谈的 URL 对应的视图对测试环境的状态一无所知。
代码与此类似:
from django.conf import settings
import json
def view1(request, *args, **kwargs):
url = 'http://api.%s/view2/' % settings.DOMAIN
r = requests.post(
url,
data=json.dumps({'key': 'value'}),
)
// Notice that the ``url`` is a url of the actual deployed application,
// and therefore knows nothing about testing and its state. That's where
// it goes wrong.
问题是,有没有一种方法可以在测试中正确运行?我使用django.test.client.Client
该类来创建我的测试请求。据我所知,此类的实例直接与 URL 映射器对话。因此url
,我在视图中构建的只是对已部署应用程序的外部 http 请求,而不是测试应用程序。
谢谢。