简体   繁体   English

如何使用 pytest 测试使用 Flask 创建的路由?

[英]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.我是 pytest 的新手,我不确定如何为我使用 Flask 创建的这条路线创建一个 pytest。

@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在您的应用所在的同一目录中创建测试文件(例如 test_core.py)
  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.这里的client.get返回response_class对象。 It have data property.它具有data属性。

More info here: https://flask.palletsprojects.com/en/2.0.x/testing/更多信息在这里: https : //flask.palletsprojects.com/en/2.0.x/testing/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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