简体   繁体   中英

How can I use pytest to test routes created using flask?

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?

  1. Create test file (for example, test_core.py) in same directory where's your app
  2. 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
  1. 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 ============
  1. Add some test, for example:
def test_helloworld_page(client):

    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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM