首页 > 解决方案 > 意外的 AssertionError:单个测试未使用上一步中的登录用户

问题描述

我正在关注http://www.patricksoftwareblog.com/flask-tutorial/的教程,我相信它基于https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i -你好世界。适合初学者的好东西。

通过手动(工作正常)与通过 pytest 测试我的代码时,我得到了不同的结果。

我的测试尝试显示需要登录的“组”端点(标准 @login_required 装饰器)。

测试问题是下面的第一个片段:

def test_groups(app):
    assert b'Knock knock' in get(app, "/groups").data
    login(app, "pete@testmail.com", "pete123")
    assert b'Test group 1' in get(app, "/groups").data

我的“获取”功能供参考:

def get(app, endpoint: str):
    return app.test_client().get(endpoint, follow_redirects=True)

我的“登录”功能供参考:

def login(app, email="testuser@testmail.com", password="testing"):
    return app.test_client().post('/login', data=dict(email=email, password=password), follow_redirects=True)

该应用程序(来自@pytest.mark.usefixtures('app')在测试模块中导入的conftest夹具)供参考:

@pytest.fixture
def app():
    """An application for the tests."""
    _app = create_app(DevConfig)
    ctx = _app.test_request_context()
    ctx.push()

    yield _app

    ctx.pop()

登录路径供参考:

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(email=form.email.data).first()
            if user is not None and user.is_correct_password(form.password.data):
                user.authenticated = True
                user.last_login = user.current_login
                user.current_login = datetime.now()
                user.insert_user()
                login_user(user)
                flash(f'Welcome back {user.name}!', 'success')
                return redirect(url_for('our_awesome_group.index'))
            else:
                flash('Incorrect credentials! Did you already register?', 'error')
        else:
            flash_errors(form)
    return render_template('login.html', form=form)

团体路线供参考:

@app.route('/groups')
@login_required
def groups():
    groups_and_users = dict()
    my_group_uuids = Membership.list_groups_per_user(current_user)
    my_groups = [Group.query.filter_by(uuid=group).first() for group in my_group_uuids]
    for group in my_groups:
        user_uuids_in_group = Membership.list_users_per_group(group)
        users_in_group = [User.query.filter_by(uuid=user).first() for user in user_uuids_in_group]
        groups_and_users[group] = users_in_group
    return render_template('groups.html', groups_and_users=groups_and_users)

标签: python-3.xflaskloginresponsepytest

解决方案


我将总结我所做的评论,这些评论给出了如何解决这个问题的答案。

使用 Pytest 和 Flask 创建测试应用程序时,有几种不同的方法可以实现。

创建具有适当应用程序上下文的测试客户端的建议方法是使用以下内容:

@pytest.fixture
def client():
    """ Creates the app from testconfig, activates test client and context then makes the db and allows the test client
    to be used """
app = create_app(TestConfig)

client = app.test_client()

ctx = app.app_context()
ctx.push()

db.create_all()


yield client

db.session.close()
db.drop_all() 
ctx.pop()

这会在推送应用程序上下文的同时创建客户端,以便您可以注册数据库等内容并将表创建到测试客户端。

第二种方法是在 OP 的问题中显示使用app.test_request 上下文

@pytest.fixture
def app():
    """An application for the tests."""
    _app = create_app(DevConfig)
    ctx = _app.test_request_context()
    ctx.push()

    yield _app

    ctx.pop()

然后在另一个 pytest 夹具中创建测试客户端

@pytest.fixture 
def client(app): 
   return app.test_client()

创建测试客户端允许您使用各种测试功能,并通过适当的应用程序上下文访问烧瓶请求。


推荐阅读