简体   繁体   English

在Django Rest Framework中使用身份验证测试POST

[英]Testing POST with authentication in Django Rest Framework

I'm trying to test POSTing data to a view in django-rest-framework that requires authentication. 我正在尝试将POST数据测试到需要身份验证的django-rest-framework中的视图。 But I can't. 但我不能。 I've read many threads of supposed solutions, but can't find any that solves to me. 我已经阅读了很多假设的解决方案,但找不到任何可以解决的问题。

Serializer: 串行:

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

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

View: 视图:

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

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

Test: 测试:

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()

I receive this error: 我收到此错误:

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

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

Had read drf Testing documentation but can't see what I'm doing wrong. 曾读过drf测试文档,但看不出我做错了什么。

The right way to create a user is using User.objects.create_user() as teach official Django documentation . 创建用户的正确方法是使用User.objects.create_user()作为教授官方Django文档 When using create_user() method the password parameter is hashed before saving in database, while common create() method does not do that. 使用create_user()方法时,密码参数在保存到数据库之前进行哈希处理,而常见的create()方法不会这样做。

Also, it's necessary login with 此外,它必须登录

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

instead user.password as password parameter in APIClient.client.login() method, as pointed out by @oz-main. 相反, user.password作为APIClient.client.login()方法中的password参数,正如@ oz-main所指出的那样。

I don't think you can't access to user.password as you are trying to. 我不认为你不能像你想的那样访问user.password Also, I'd give some advices: 另外,我会给出一些建议:

  • Since you're using APITestCase . 因为你正在使用APITestCase Try to use setUp method to create your user in database. 尝试使用setUp方法在数据库中创建用户。 That way you will be able to re-use that user in other cases 这样,您就可以在其他情况下重复使用该用户
  • Follow pep8 guidelines to write your code. 按照pep8指南编写代码。 test_POSTing_a_new_researcher is a very weird method name test_POSTing_a_new_researcher是一个非常奇怪的方法名称
  • Take a look at factory boy , it might make your life easier by replacing the fixture approach 看看工厂男孩 ,通过更换夹具方法可能会让您的生活更轻松

Good resource for testing: http://www.obeythetestinggoat.com/ 良好的测试资源: http//www.obeythetestinggoat.com/

base on the test case you've written the test user is not logged in because you are trying to log in a user using the hashed password and not the nep-lab1 . 根据您编写的测试用例,测试用户未登录,因为您尝试使用散列密码而不是nep-lab1登录用户。 you can test if you've successfully logged in by: 您可以测试您是否已成功登录:

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

and since the user is not logged your test on posting a new researcher via api would result to FORBIDDEN (403) http response and not CREATED (201) 并且由于用户未登录您通过api发布新研究员的测试将导致FORBIDDEN (403)http响应而不是CREATED (201)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM