首页 文章

Django Rest框架JWT认证测试

提问于
浏览
6

我正在设置DRF以使用JWT令牌认证 . 我似乎在DRF-JWT表示它正常工作,但我无法通过登录测试成功运行 .

我已经完成了django-rest-framework-jwt docs中的安装步骤,并且我能够成功运行卷曲 $ curl -X POST -d "username=admin&password=abc123" http://localhost:8000/api-token-auth/ 并获取令牌 .

我期待我的测试也能将一个令牌传回给我,但显然我没有将它设置正确 .

# tests.py
class LoginTests(APITestCase):
    def setUp(self):
        self.user = NormalUserFactory.create()
        self.jwt_url = reverse('jwt_login')

    def test_token_get_not_allowed(self):
        # do not allow GET requests to the login page
        response = self.client.get(self.jwt_url)
        self.assertEqual(response.data.get('detail'), 'Method "GET" not allowed.')

    def test_token_login_fail_incorrect_credentials(self):
        # pass in incorrect credentials
        data = {
            'username': self.user.username,
            'password': 'inCorrect01'
        }
        response = self.client.post(self.jwt_url, data)
        self.assertEqual(response.data.get('non_field_errors'), 
            ['Unable to login with provided credentials.'])

    def test_token_login_success(self):
        data = {
            'username': self.user.username,
            'password': 'normalpassword',
        }
        response = self.client.post(self.jwt_url, data)
        print(response.data.get("token"))
        self.assertNotEqual(response.data.get("token"), None)

前两个单元测试成功运行,但第三个单元测试不会返回令牌,而是返回 {'non_field_error':'Unable to login with provided credentials.'} ,这是我在凭据不正确时所期望的 .

要创建User实例(和其他模型实例),我使用的是factory_boy . 创建实例的相同方法适用于此项目中的其他应用程序以及其他项目,并且我已验证用户确实存在于测试数据库中 .

# factories.py
class UserFactory(DjangoModelFactory):
    class Meta:
        model = User

    native_language = 'es'


class NormalUserFactory(UserFactory):
    username = 'normaluser'
    password = 'normalpassword'
    email = 'user@email.com'
    first_name = 'John'
    last_name = 'Doe'

这里是我的相关设置:

# settings.py
REST_FRAMEWORK = {
    'API_ROOT': '/v1/',
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}

1 回答

  • 2

    请尝试以下代码:

    tests.py

    class LoginTests(APITestCase):
        def setUp(self):
            self.user = NormalUserFactory.create()
            self.jwt_url = reverse('jwt_login')    
        def test_post_form_failing_jwt_auth(self):
                """
                Ensure POSTing form over JWT auth without correct credentials fails
                """
                data = {
                    'username': self.user.username,
                    'password': 'inCorrect01'
                }
                response = self.client.post(self.jwt_url, data)
                self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
    

相关问题