使用JWT授权对Django Rest API进行单元测试失败

时间:2017-11-23 11:57:49

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

我有以下问题: 每当我运行我的单元测试来测试我的Django REST API时,即使我在测试期间为我创建的User对象粘贴了正确的Token,我也会获得401 Unauthorized。但是,我希望回复是200 ..

以下是代码:

class TestWebApi(APITestCase):

  def setUp(self):
      self.factory = APIRequestFactory()
      self.client = Client()
      self.user = User.objects.create_user('testuser', None, '12345a')
      Employee.objects.create(name='Test', surname='Employee1', role="frontend", account=User.objects.get(username='testuser'))

  def test_api_employee(self):
      user = self.user
      token = json.loads(self.client.post('/api/get_jwt_token/', data={'username': 'testuser', 'password': '12345a'}).content)['token']
      response = self.client.get('/api/v2/employees/', HTTP_Authorization="JWT {0}".format(token))
      employees = Employee.objects.all()
      serializer = EmployeeSerializer(employees, many=True)
      self.assertEqual(response.status_code, status.HTTP_200_OK)
      json_response = response.json()
      self.assertEqual(json_response, serializer.data)

提前致谢!

0 个答案:

没有答案