python-3.x - 意外的 AssertionError:单个测试未使用上一步中的登录用户
问题描述
我正在关注http://www.patricksoftwareblog.com/flask-tutorial/的教程,我相信它基于https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i -你好世界。适合初学者的好东西。
通过手动(工作正常)与通过 pytest 测试我的代码时,我得到了不同的结果。
我的测试尝试显示需要登录的“组”端点(标准 @login_required 装饰器)。
- 我最初在尝试在没有登录的情况下获取端点时测试用户获取登录页面(“敲门”)。这可以手动和通过 pytest 工作。
- 我登录一个用户。如果我检查登录的响应,我可以清楚地看到“欢迎回来皮特!” 成功消息。
- 我的第二个断言收到来自 URL 的响应,
/login?next=%2Fgroups
表明/groups
调用端点之前没有登录/身份验证,并且断言失败。手动测试它可以按预期工作。为什么单个测试在下一步中不使用相同的用户/会话组合?
测试问题是下面的第一个片段:
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)
解决方案
我将总结我所做的评论,这些评论给出了如何解决这个问题的答案。
使用 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()
创建测试客户端允许您使用各种测试功能,并通过适当的应用程序上下文访问烧瓶请求。
推荐阅读
- vue.js - Vue.Js - App.Vue 组件中的导入组件问题
- unity3d - 试图保存游戏,但每次都卡住了。输出日志说“包丢失???”
- python-3.x - 如何计算 Python 中多个字符串之间的相似度百分比?
- javascript - ReactJS 最佳实践。我应该用箭头功能制作我的所有组件吗?以及非组件功能?
- c# - 为什么我的应用程序只是停止而不继续运行?
- javascript - 如何在javascript中将数组转换为对象时添加其他属性?
- kubernetes - 当 iptables 更改时,kubernetes pod 关闭
- java - ./gradlew clean 使用 react native android 的问题
- c++ - 使用范围解析运算符 :: 定义类外的函数有什么意义?
- algorithm - 为什么“删除”操作在排序数组上被认为是“慢”?