我正在为一个应用程序编写django unittests,该应用程序具有HTTP get,put和post方法的模块 . 我一直是referencing rest_framework的APITestCase方法,用于为POST方法编写unittest .
这是我的POST方法unittest的代码:
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)
通过运行此测试用例,我得到了这个输出:
$ python manage.py test lib.IngredientTestCase.test_postByTestCase
FDestroying测试数据库的别名'默认'...
================================================== ====================
FAIL:test_postByTestCase(lib.tests.IngredientTestCase)
回溯(最近一次调用最后一次):文件“C:\ Apache2 \ htdocs \ iLab \ api \ lib \ tests.py”,第42行,在test_postByTestCase中self.assertEqual(response.status_code,status.HTTP_201_CREATED)AssertionError:401!= 201
在5.937s中进行1次测试
失败(失败= 1)
我试过传递HTTP_AUTHORIZATION标记值,但它没有帮助 .
1 回答
401
错误表示您的请求未经授权 . 在尝试POST
请求之前,您的应用程序是否需要在测试中设置经过身份验证的用户 .在您将用户登录到客户端后,您应该能够正确调用API并查看
201
响应 .