django - Django Unittest如何调整client.post以在request.META中设置数据
问题描述
我试图通过将数据发布到视图来测试视图,但视图使用 request.META 中的键/值。如何调整我的 client.post 以确保填充 request.META 数据?
以下示例不起作用!
来自单元测试的示例:
with mock.patch("......") as gt:
header = {'SOME_SIGNATURE': 'BLAH'}
gt.side_effect = ValueError
response = self.client.post('/webhook/', data={'input': 'hi'},
content_type='application/json', follow=False,
secure=False, extra=header)
self.assertEqual(response.status_code, 400)
视图中的代码:
def my_webhook_view(request):
# Extract Data from Webhook
payload = request.body
# THIS LINE CAUSES MY UNITTESTS TO FAIL
sig_header = request.META['HTTP_SOME_SIGNATURE']
......
解决方案
extra
不是post
方法的单独参数,而是包罗万象的关键字参数变量。要传递您的标头,只需使用:
response = self.client.post('/webhook/', data={'input': 'hi'},
content_type='application/json', follow=False,
secure=False, **header)
此外,请确保HTTP_
在标题列表中包含前缀。
推荐阅读
- kubernetes - Kubernetes API 使用 Minikube 创建 CRD,部署 pod 处于挂起状态
- angular - 将文件从 Angular 上传到 Laravel。不工作
- laravel - 在未来某个时间运行 Cron 作业,但只有一次(Laravel)
- mysql - 使用表中的时间间隔在另一个中选择
- amazon-web-services - AWS CDK 多个应用程序
- java - 如何在集合中通过 id 查找?
- sql-server - PowerShell 导入模块 SqlServer 无法加载 PSSnapins.dll
- python - 单击按钮打开窗口,关闭当前窗口?
- node.js - AWS 环境变量独立于 shell
- android - 尝试在空对象引用上调用虚拟方法“long com.mesibo.api.JNIAPI.random()”