I'm new to Pytest. I want to test my views which require login (decorated with @login_required
).
I have following test function:
def test_add_new_post(self, client, user):
login_user(user)
assert current_user == user
data = {
'title': 'This is test post',
'body': 'This is test body'
}
client.post(url_for('posts.add_new'), data=data)
assert Post.query.count() == 1
where the client
is:
@pytest.fixture(scope='session')
def client(request, app):
return app.test_client()
The assert current_user == user
returns True
, but the client.post
returns the login page, because the login_required
redirects to a login page. Why is this happening and what is the correct way of doing this?
This worked for me (based on this comment):
def test_with_authenticated_user(app):
@app.login_manager.request_loader
def load_user_from_request(request):
return User.query.first()
# now you can call client.post or similar methods
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