Using Basic HTTP access authentication in Django testing framework

前端 未结 6 1468
栀梦
栀梦 2020-12-08 01:41

For some of my Django views I\'ve created a decorator that performs Basic HTTP access authentication. However, while writing test cases in Django, it took me a while to wor

6条回答
  •  广开言路
    2020-12-08 02:33

    For python3, you can base64-encode your username:password string:

    base64.b64encode(b'username:password')
    

    This returns bytes, so you need to transfer it into an ASCII string with .decode('ascii'):

    Complete example:

    import base64
    
    from django.test import TestCase
    
    class TestClass(TestCase):
       def test_authorized(self):
           headers = {
               'HTTP_AUTHORIZATION': 'Basic ' + 
                    base64.b64encode(b'username:password').decode("ascii")
           }
           response = self.client.get('/', **headers)
           self.assertEqual(response.status_code, 200)
    

提交回复
热议问题