Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Flask test_client() doesn't have request.authorization with pytest

I have problem when testing my flask app with pytest.
App is required basic auth which is parameters of request.authorization in flask.
But with pytest, flask.test_client() doesn't have request.authorization.

Here's a code of fixture:

@pytest.yield_fixture(scope='session')
def app()
    app = create_app()

    # some setup code

    ctx = app.app_context()
    ctx.push()
    yield app
    ctx.pop()
    # some teadown code

@pytest.fixture
def test_client(app)
     return app.test_client()

Here's a code of test:

def test_index(test_client):
    res = test_client.get("/", headers={"Authorization": "Basic {user}".format(user=b64encode(b"test_user"))})
    assert res.status_code == 200

When I run this test, I got this error:

E       assert 401 == 200
E        +  where 401 = <Response streamed [401 UNAUTHORIZED]>.status_code

Not only auth failure, but also request.authorization doesn't have any value(None).
Why this happen? Is there any solution?

Thanks.

like image 905
Jony cruse Avatar asked May 14 '15 23:05

Jony cruse


People also ask

How pytest write test cases?

All you need to do is include a function with the test_ prefix. Because you can use the assert keyword, you don't need to learn or remember all the different self. assert* methods in unittest , either. If you can write an expression that you expect to evaluate to True , and then pytest will test it for you.

How do you write a unit test case in python Flask?

First create a file named test_app.py and make sure there isn't an __init__.py in your directory. Open your terminal and cd to your directory then run python3 app.py . If you are using windows then run python app.py instead. Hope this will help you solve your problem.

How do you test a Flask API?

Testing Flask requires that we first import a Flask instance app from our api (created in our application), as seen in the previous snippet. The imported instance then exposes a test_client() method from Flask that contains the features needed to make HTTP requests to the application under test.


1 Answers

I found this solution. Maybe it can help someone:

from requests.auth import _basic_auth_str
headers = {
   'Authorization': _basic_auth_str(username, password),
}

You just have to use the library 'requests'

like image 157
Kevin Vincent Avatar answered Sep 20 '22 14:09

Kevin Vincent