I am new to pytest and I am not sure how to create a pytest for this route that I created using Flask.
@auth.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('auth.me'))
if request.method == 'POST':
user_name = request.form.get('user_name')
password = request.form.get('password')
user = User.query.filter_by(user_name=user_name).first()
if user:
if check_password_hash(user.password, password):
flash('Logged in successfully!', category='accepted')
login_user(user, remember=True)
return redirect(url_for('auth.me'))
else:
flash("Incorrect password, try again.", category='err' )
else:
flash('Username does not exist', category='err')
pass
# if user is logged in already, redirect to /me
return render_template('login.html')
any guidance would help?
CodePudding user response:
- Create test file (for example, test_core.py) in same directory where's your app
- Enter this code:
import os
import tempfile
import pytest
from app import app
@pytest.fixture
def client():
app.config.update({'TESTING': True})
with app.test_client() as client:
yield client
- If you run the test suite, you may see the output:
$ pytest
================ test session starts ================
rootdir: ./flask/examples/flaskr, inifile: setup.cfg
collected 0 items
=========== no tests ran in 0.07 seconds ============
- Add some test, for example:
def test_empty_db(client):
"""Start with a blank database."""
resp = client.get('/')
assert b'Hello world' in resp.data
Here's client.get
returns response_class object. It have data
property.
More info here: https://flask.palletsprojects.com/en/2.0.x/testing/