Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send username:password to unittest's app.get() request?

This is part of my unit test in Flask-RESTful.

self.app = application.app.test_client()
rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp))
eq_(rv.status_code,200)

Within the command line I could use curl to send the username:password to the service:

curl -d username:password http://localhost:5000/api/v1.0/1234567

How do I achieve the same within my unit test's get() ?

Since my get/put/post require authentication otherwise the test would fail.

like image 770
Houman Avatar asked Oct 22 '13 17:10

Houman


People also ask

How do you make a basic auth header in Python?

You'll need to import the following first. Part of the basic authentication header consists of the username and password encoded as Base64. In the HTTP header you will see this line Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= . The encoded string changes depending on your username and password.


2 Answers

From RFC 1945, Hypertext Transfer Protocol -- HTTP/1.0

11.1 Basic Authentication Scheme

...

To receive authorization, the client sends the user-ID and password, separated by a single colon (":") character, within a base64 [5] encoded string in the credentials.string.

...

If the user agent wishes to send the user-ID "Aladdin" and password open sesame", it would use the following header field:

  Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

So if you really use http basic authentication you can solution like below, although your curl usage suggests some other authentication scheme.

from base64 import b64encode

headers = {
    'Authorization': 'Basic ' + b64encode("{0}:{1}".format(username, password)).decode('utf-8')
}

rv = self.app.get('api/v1.0/{0}'.format(ios_sync_timestamp), headers=headers)
like image 157
zero323 Avatar answered Nov 15 '22 19:11

zero323


An alternative solution - All credit goes to Doug Black

def request(self, method, url, auth=None, **kwargs):
    headers = kwargs.get('headers', {})
    if auth:
        headers['Authorization'] = 'Basic ' + base64.b64encode(auth[0] + ':' + auth[1])

    kwargs['headers'] = headers

    return self.app.open(url, method=method, **kwargs)

and then use this method in your tests:

resp = self.request('GET', 'api/v1.0/{0}'.format(ios_sync_timestamp), auth=(username, password))
like image 41
Houman Avatar answered Nov 15 '22 17:11

Houman