python - 在 Django 中测试 POST 端点时如何包含 csrf token ?

标签 python django testing csrf

我正在学习如何制作一个 api 端点,我正在尝试编写一个测试来查看发布请求是否返回 200 状态代码。我计划编写更多测试以查看端点是否也返回所有预期结果。我不断收到 403 状态代码,我认为这是因为我需要在发布数据中包含一个 csrf token 。在 Django 中测试 POST 端点的好方法是什么?

我的测试:

from django.test import TestCase
from app import settings
import requests

class ProjectEndpoint(TestCase):
   def post_endpoint(self):
      data = {'hello':'23'}
      post_project = requests.post(settings.BASE_URL+'/api/project', params=data)
      self.assertEqual(post_endpoint.status_code, 200)

这个测试一直失败,返回 403 != 200

我认为这是因为 View 受到了 csrf 攻击的保护,但我真的不确定。欣赏某人的任何见解。

最佳答案

实际上,根据 https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#testing,django 不强制(默认情况下)使用测试进行 csrf 检查。 :

The CsrfViewMiddleware will usually be a big hindrance to testing view functions, due to the need for the CSRF token which must be sent with every POST request. For this reason, Django’s HTTP client for tests has been modified to set a flag on requests which relaxes the middleware and the csrf_protect decorator so that they no longer rejects requests. In every other respect (e.g. sending cookies etc.), they behave the same.

If, for some reason, you want the test client to perform CSRF checks, you can create an instance of the test client that enforces CSRF checks:

from django.test import Client

csrf_client = Client(enforce_csrf_checks=True)

但是,这确实需要您使用 Django 客户端与请求;据我所知,Django 不模拟/仪器/等。请求...所以当您运行该单元测试时,您实际上是在访问真实服务器。

另请注意,您应该将测试函数命名为以 test_ 开头的名称

所以像这样(当通过 django manage.py test .ProjectEndpoint 运行时)

def test_post_endpoint(self):
   data = {'hello':'23'}
   c = Client() #above, from django.test import TestCase,Client
   #optional, but may be necessary for your configuration: c.login("username","password")
   response = c.post('/api/project',params=data)
   self.assertEqual(response.status_code, 200)

关于python - 在 Django 中测试 POST 端点时如何包含 csrf token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25003527/

相关文章:

python - 使用 matplotlib 绘图时更改刻度标签的位置(移动)

python - 无法在 Python 3 中打印生成器表达式

python - 在views.py中导入nltk时,Django webapp(在Apache2服务器上)无限期挂起

python - 对 django 模型的对象引用 - 缺少 "object"

python - 哪个版本的 Django REST Framework 受到 IP 欺骗的影响?

ruby-on-rails - RSpec+Capybara 请求规范 w/JS 不工作

java - 用于测试 REST Web 应用程序的 JBehave

python - 带有 pipenv 的 Jupyter 中的 ModuleNotFoundError

python - 使用 rtsp 流时 Tensorflow 对象检测速度慢

c++ - 将 Windows 可执行文件用作 DLL 时如何初始化 C 运行时