Django休息框架认证测试

时间:2015-01-30 04:18:59

标签: django django-rest-framework django-authentication django-testing

我正在尝试使用JWT进行身份验证的测试用例,在这种情况下使用django-rest-framework-jwt,然后使用curl我得到下一个,所以:

curl -X POST -d "email=testuser@test.com&password=testing" http://localhost:8000/api/auth/token/

获取:

{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo0LCJlbWFpbCI6InRlc3R1c2VyQHRlc3QuY29tIiwiZXhwIjoxNDIyNTkxMTQ5LCJ1c2VybmFtZSI6InRlc3R1c2VyQHRlc3QuY29tIn0.OT8ggcZYWxcbSy0Vv8u5PA3QISIdarNXTVuvu4QQjnw"}

但是,当我运行我的测试用例时:

class BaseTestCase(TestCase):

    def setUp(self):
        self.csrf_client = APIClient(enforce_csrf_checks=True)
        self.email = 'testuser@test.com'
        self.name = 'test user'
        self.password = 'testing'
        user = Usuario.objects.create_user(email=self.email, name=self.name, password=self.password)
        user.save()
        self.data = {
            'email': self.email,
            'password': self.password
        }
        self.url = '/api/auth/token/'


class ObtainJSONWebTokenTests(BaseTestCase):

    def test_jwt_login_json(self):
        """
        Ensure JWT login view using JSON POST works.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post(self.url, self.data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)

    def test_jwt_login_json_incomplete_creds(self):
        """
        Ensure JWT login view using JSON POST fails
        if incomplete credentials are used.
        """
        client = APIClient(enforce_csrf_checks=True)

        self.data = {
            'email': self.email
        }
        response = client.post(self.url, self.data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)

我明白了:

Creating test database for alias 'default'...
F.
======================================================================
FAIL: test_jwt_login_json (user.tests.ObtainJSONWebTokenTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/rizotas/Proyects/django/src/rescue/user/tests.py", line 34, in test_jwt_login_json
    self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
AssertionError: 400 != 200 : ReturnDict([('non_field_errors', ['Unable to login with provided credentials.'])])

----------------------------------------------------------------------
Ran 2 tests in 0.374s

FAILED (failures=1)
Destroying test database for alias 'default'...

任何想法?

非常感谢!

更新

我的设置

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    #'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'debug_toolbar',
    'debug_panel',
    ...)


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
       'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    'TEST_REQUEST_RENDERER_CLASSES': (
        'rest_framework.renderers.MultiPartRenderer',
        'rest_framework.renderers.JSONRenderer',
        #'rest_framework.renderers.YAMLRenderer'
    )
}

3 个答案:

答案 0 :(得分:5)

有同样的问题。显然,当您使用默认序列化程序和路径localhost:8000 / users /创建用户时,不会保存密码。通过运行curl请求然后查询数据库来确认。

按照本网站的说明操作:http://www.django-rest-framework.org/api-guide/serializers/#hyperlinkedmodelserializer这是我的新UserSerializer类:

class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name', 'email', 'password')
    extra_kwargs = {'password': {'write_only': True}}

def create(self, validated_data):
    user = User(
        email=validated_data['email'],
        username=validated_data['username']
    )
    user.set_password(validated_data['password'])
    user.save()
    return user

此代码假定用户名和电子邮件都是必填字段。显然,这可以根据您自己的业务逻辑进行更改

希望这有帮助,

伊沙伊

答案 1 :(得分:1)

我不是准备测试它的计算机,但我相信Django在测试时使用一个单独的数据库,分别在测试的开始和结束时创建和销毁。如果您还没有在测试中创建用户,则必须尝试使用​​它登录。测试数据库不包含由这些凭据验证的用户。

答案 2 :(得分:0)

在您的cURL示例中,您不是传入JSON,而是传递标准POST正文。看起来'/ api / auth / token /'解析为的视图不接受JSON。此cURL命令应以相同的方式失败

curl -H "Content-Type: application/json" -d '{"email":"xyz","password":"xyz"}' http://localhost:8000/api/auth/token/

如果您发布了观看代码,可能会有所帮助。