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

时间:2014-02-13 09:46:20

标签: django unit-testing python-2.7 django-rest-framework

我正在为一个应用程序编写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测试数据库的别名'default'...

=============================================== =======================

失败:test_postByTestCase(lib.tests.IngredientTestCase)

追踪(最近一次通话):   在test_postByTestCase中输入文件“C:\ Apache2 \ htdocs \ iLab \ api \ lib \ tests.py”,第42行     self.assertEqual(response.status_code,status.HTTP_201_CREATED) 断言错误:401!= 201


5.937s中的Ran 1测试

失败(失败= 1)

我尝试过传递HTTP_AUTHORIZATION标记值,但它没有帮助。

1 个答案:

答案 0 :(得分: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响应。