Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

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

For Python 3, try the following example:

from base64 import b64encode
headers = {
    'Authorization': 'Basic %s' % b64encode(b"username:password").decode("ascii")
}

self.app.get("foo/", headers=headers)

If you'd like to use dynamic variables for username and password, then try something like:

'Basic %s' % b64encode(bytes(username + ':' + password, "utf-8")).decode("ascii")

See also: Python, HTTPS GET with basic authentication

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top