首页 文章

Django POST方法单元测试失败,出现Assertionerror 401

提问于
浏览
2

我正在为一个应用程序编写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 回答

  • 1

    401 错误表示您的请求未经授权 . 在尝试 POST 请求之前,您的应用程序是否需要在测试中设置经过身份验证的用户 .

    # my_api_test.py
    
    def setUp:
        # Set up user
        self.user = User(email="foo@bar.com") # 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并查看 201 响应 .

相关问题