api_client的tastypie 401错误

时间:2016-09-27 14:05:47

标签: python django tastypie django-unittest

您好我正在尝试为我的应用编写测试用例。 URL ='/ api / project /'。我启用了get,post和put方法以及身份验证。但我仍然收到401错误的帖子请求

class EntryResourceTest(ResourceTestCaseMixin, TestCase):
    class Meta:
        queryset = Project.objects.all()
        resource_name = 'project'
        allowed_methods = ['get', 'post', 'put']
        authentication = Authentication()
        authorization = Authorization()

    def setUp(self):
        super(EntryResourceTest, self).setUp()
        # Create a user.
        self.username = 'daniel'
        self.password = 'pass'
        self.user = User.objects.create_user(self.username, 'daniel@example.com', self.password)

    def login(self):
         return self.api_client.client.login(
        username=self.username, password=self.password)

    def get_credentials(self):
    return self.create_basic(username=self.username, password=self.password)

    def test_post_list(self):
        self.login()
        req_get = self.api_client.get('/api/project/', format='json', authentication=self.get_credentials())      # -> get works and i get 200 status code
        req_post = self.api_client.post('/api/project/', format='json', data=self.post_data, authentication=self.get_credentials())

我使用以下命令运行测试用例,这里得到的工作正常但不是post请求。即使我没有传递身份验证参数,并且使用我在self.login()

中定义的默认登录名,也可以获取请求。
django-admin test myapp.api.project.tests        

1 个答案:

答案 0 :(得分:0)

使用BasicAuthentication代替Authentication

self.create_basic(...)BasicAuthentication创建标题。

def create_basic(self, username, password):
    """
    Creates & returns the HTTP ``Authorization`` header for use with BASIC
    Auth.
    """