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.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With