0

Hi I am trying to write a test case for my app. URL = '/api/project/'. I have enabled get, post and put methods along with authentication. But still i get 401 error for post request

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())

I run the test case using following command , and here get works fine but not the post request. And get request works even if i don't pass authentication parameter as it uses the default login which i have defined in self.login()

django-admin test myapp.api.project.tests        
Naggappan Ramukannan
  • 2,564
  • 9
  • 36
  • 59

1 Answers1

0

Use BasicAuthentication instead of Authentication.

self.create_basic(...) create a headers for BasicAuthentication.

def create_basic(self, username, password):
    """
    Creates & returns the HTTP ``Authorization`` header for use with BASIC
    Auth.
    """
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49