2016-09-27 64 views
0

嗨我想为我的应用程序编写一个测试用例。 URL ='/ api/project /'。我已启用获取,发布和放置方法以及身份验证。但我仍然得到401错误POST请求401错误为api_client tastypie

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, '[email protected]', 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   

回答

0

使用BasicAuthentication,而不是Authentication

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

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