Django POST Method Unit Test failing with Assertionerror 401
我正在为一个应用程序编写DjangoUnitTests,该应用程序具有带有HTTP GET、PUT和POST方法的模块。我一直在引用REST框架的apitesscase方法来编写post方法的unittest。
以下是我的Post方法单元测试代码:
1 2 3 4 5 | def test_postByTestCase(self): url = reverse('lib:ingredient-detail',args=('123',)) data = {'name':'test_data','status':'draft','config':'null'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) |
通过运行这个测试用例,我得到了这个输出:
1 | $ python manage.py test lib.IngredientTestCase.test_postByTestCase |
fdesroying别名"default"的测试数据库…
=========================================================
失败:测试后字节测试用例(lib.tests.ingredienttestcase)回溯(最近一次呼叫的最后一次):文件"c:apache2htdocsilabapilib ests.py",第42行,位于测试字节大小写中self.assertequal(response.status_code,status.http_201_created)断言者错误:401!= 201
在5.937s内运行1次测试
失败(失败=1)
我尝试传递http_授权令牌值,但没有帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # my_api_test.py def setUp: # Set up user self.user = User(email="[email protected]") # NB: You could also use a factory for this password = 'some_password' self.user.set_password(password) self.user.save() # Authenticate client with user self.client = Client() self.client.login(email=self.user.email, password=password) def test_postByTestCase(self): url = reverse('lib:ingredient-detail',args=('123',)) data = {'name':'test_data','status':'draft','config':'null'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) |
一旦您将用户登录到您的客户机,那么您应该能够正确地调用您的API并看到一个