django - 测试 Django REST 框架

标签 django django-rest-framework django-testing

我正在开发第一个使用 Django REST Framework 的项目,但在测试 API 时遇到问题。我收到了 403 Forbidden 错误,而不是预期的 200 或 201。但是,API 按预期工作。

我一直在经历DRF Testing docs ,这一切看起来很简单,但我相信我的客户没有登录。通常在我的 Django 项目中,我混合使用了 Factory boy 和 django webtest,我已经取得了很多成功。经过几天的摆弄之后,我并没有发现测试 DRF API 时有同样的快乐。

我不确定这是否与我在 DRF APITestCase/APIClient 中做错的事情有关,或者与 django 测试的一般问题有关。

我只是粘贴以下代码,而不是发布序列化器/ View 集,因为 API 在浏览器中工作,看来我只是在 APITestCase 中的 APIClient 身份验证方面遇到问题。

# settings.py
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}


# tests.py
from django.test import TestCase

from rest_framework.test import APITestCase, APIClient

from accounts.models import User
from .factories import StaffUserFactory


class MainSetUp(TestCase):
    def setUp(self):
        self.user = StaffUserFactory
        self.api_root = '/api/v0/'
        self.client = APIClient()


class APITests(MainSetUp, APITestCase):

    def test_create_feedback(self):
        """
        Ensure we can create a new account object.
        """
        self.client.login(username='staffuser', password='staffpassword')

        url = '%sfeedback/' % self.api_root
        data = {
            'feedback': 'this is test feedback'
        }
        response = self.client.post(url, data, user=self.user)

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data, data)


# factories.py
from factory.django import DjangoModelFactory

from django.contrib.auth import get_user_model

User = get_user_model()


class UserFactory(DjangoModelFactory):
    class Meta:
        model = User


class StaffUserFactory(UserFactory):
    username = 'staffuser'
    password = 'staffpassword'
    email = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcccbded9d9ffdad2ded6d391dcd0d2" rel="noreferrer noopener nofollow">[email protected]</a>'
    first_name = 'Staff'
    last_name = 'User'
    is_staff = True

最佳答案

我以前从未使用过 DjangoModelFactory,但看来您必须在将用户设置为 StaffUserFactory 后调用 create 。 http://factoryboy.readthedocs.org/en/latest/_modules/factory/django.html#DjangoModelFactory

class MainSetUp(TestCase):
    def setUp(self):
        self.user = StaffUserFactory
        self.user.create()
        self.api_root = '/api/v0/'
        self.client = APIClient()

关于django - 测试 Django REST 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28591497/

相关文章:

python - 在仍然理智的情况下在 Django 中设置通用外键

python - 将迁移文件添加到存储库是好的做法吗?

python - 使用 Django 中的自定义字段扩展 django.contrib.auth.models.User 模型

django-rest-framework - 如何在 ViewSet 文档字符串中明确记录可能的 REST 操作?

django - Django在测试中测试存储的 session 数据

django - 我在哪里复制我的 Apache docker 镜像中的 VirtualHost 指令?

python - 如何在django模板中获取类

python - JSONField 在 Django 3.1 中不允许为空

python - 如何对 ValidationError 进行单元测试并断言使用了正确的代码?

python - 如何在 Django 中使用 LiveServerTestCase 和 Selenium 测试登录功能