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

Houman picture Houman · Oct 22, 2013 · Viewed 7.7k times · Source

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.

Answer

zero323 picture zero323 · Oct 22, 2013

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)