【问题标题】:Testing POST with authentication in Django Rest Framework在 Django Rest Framework 中使用身份验证测试 POST
【发布时间】:2017-08-15 07:16:04
【问题描述】:

我正在尝试测试将数据发布到django-rest-framework 中需要身份验证的视图。但我不能。我已经阅读了许多假设解决方案的主题,但找不到任何对我有用的解决方案。

序列化器:

class ResearcherSerializer(serializers.ModelSerializer):
    studies = serializers.PrimaryKeyRelatedField(
        many=True, queryset=Study.objects.all()
    )

    class Meta:
        model = Researcher
        fields = ('id', 'first_name', 'surname', 'email', 'studies')

查看:

class ResearcherSerializer(serializers.ModelSerializer):
    studies = serializers.PrimaryKeyRelatedField(
        many=True, queryset=Study.objects.all()
    )

    class Meta:
        model = Researcher
        fields = ('id', 'first_name', 'surname', 'email', 'studies')

测试:

class ResearcherAPITest(APITestCase):
    base_url = reverse('api_researchers')
# ...

def test_POSTing_a_new_researcher(self):
    user = User.objects.create(username='lab1', password='nep-lab1')
    self.client.login(username=user.username, password=user.password)
    response = self.client.post(
        self.base_url,
        {
            'first_name': 'João',
            'surname': 'das Rosas',
        }
    )
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
    new_researcher = Researcher.objects.first()
    self.assertEqual(new_researcher.first_name, 'João')
    self.client.logout()

我收到此错误:

FAIL: test_POSTing_a_new_researcher (experiments.tests.test_api.ResearcherAPITest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/caco/Workspace/nep-system/nep/experiments/tests/test_api.py", line 130, in test_POSTing_a_new_researcher
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
AssertionError: 403 != 201

----------------------------------------------------------------------

已阅读 drf 测试文档,但看不到我做错了什么。

【问题讨论】:

    标签: python django unit-testing django-rest-framework


    【解决方案1】:

    创建用户的正确方法是使用User.objects.create_user() 作为教official Django documentation。使用create_user() 方法时,密码参数在保存到数据库之前会进行哈希处理,而常见的create() 方法则不会这样做。

    另外,需要登录

    self.client.login(username=user.username, password='nep-lab1')
    

    正如@oz-main 指出的那样,APIClient.client.login() 方法中的password 参数改为user.password

    【讨论】:

      【解决方案2】:

      基于您编写的测试用例 测试用户未登录,因为您尝试使用散列密码而不是nep-lab1 登录用户。您可以通过以下方式测试您是否已成功登录:

      print self.client.login(username=user.username, password=`nep-lab1`)
      # True if logged in and False if not
      

      并且由于用户没有记录您通过 api 发布新研究人员的测试将导致FORBIDDEN(403) http 响应而不是CREATED(201)

      【讨论】:

      • 事实上,打印user.password 会得到'nep-lab1'。我在这里发现创建用户的正确方法是使用User.objects.create_user() 而不是User.objects.create() 像常见的模型类。第一种方法为我们散列密码。无论如何感谢您的回复。你让我对那个错误敞开心扉。
      【解决方案3】:

      我认为您不能像您尝试的那样访问user.password。另外,我会给出一些建议:

      • 由于您使用的是APITestCase。尝试使用 setUp 方法在数据库中创建您的用户。这样您就可以在其他情况下重复使用该用户
      • 按照 pep8 指南编写代码。test_POSTing_a_new_researcher 是一个非常奇怪的方法名称
      • 看看factory boy,它可能会通过更换夹具方法让您的生活更轻松

      测试的好资源:http://www.obeythetestinggoat.com/

      【讨论】:

      • 感谢您的提示。我在这里验证了 user.password 是可以访问的。顺便说一句,我正在使用 obeythetestinggoat.com 学习 Django TDD,这是一个很棒的资源。但是有一个快速附录涵盖了测试 API,特别是 django-rest-framework。没有身份验证测试。不管怎样,谢谢你的帮助。
      猜你喜欢
      • 2015-06-01
      • 2018-07-04
      • 2013-12-29
      • 2015-06-04
      • 2016-01-09
      • 2013-05-03
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多