python - 单元测试返回错误,“详细信息:密钥(用户名)=(test123)已经存在。”
问题描述
我目前正在尝试测试当有人尝试使用已在使用的用户名注册时我希望出现的 Flash 消息。但是,我不确定如何去做,因为我目前使用的方法不起作用。这是我的测试代码:
with app.test_client() as client:
resp = client.post('/register', data={'firstname': 'test',
'lastname': 'dummy',
'username': 'test123',
'email': 'dummytest@test.com',
'password': 'password',
'image': None,
'state': 'Texas',
'vax_date': None,
'covid_status': None},
follow_redirects=True)
assert b'Username already taken' in resp.data
with self.assertRaises(IntegrityError) as context:
db.session.commit()
这是实际的端点:
if form.validate_on_submit():
try:
user = User.signup(
firstname=form.firstname.data,
lastname=form.lastname.data,
username=form.username.data,
email=form.email.data,
password=form.password.data,
image=form.image.data,
state=form.state.data,
vax_date=form.vax_date.data,
covid_status=form.covid_status.data)
db.session.commit()
except IntegrityError:
flash("Username already taken", 'danger')
return render_template('users/register.html', form=form)
do_login(user)
return redirect('/user')
else:
return render_template('users/register.html', form=form)
我得到的错误是DETAIL: Key (username)=(test123) already exists。 TypeError:需要一个类似字节的对象,而不是“str”
解决方案
尝试做:
with app.test_client() as client:
resp = client.post('/register', data={'firstname': 'test',
'lastname': 'dummy',
'username': 'test123',
'email': 'dummytest@test.com',
'password': 'password',
'image': None,
'state': 'Texas',
'vax_date': None,
'covid_status': None},
follow_redirects=True)
assert b'Username already taken' in resp.data
with self.assertRaises(IntegrityError) as context:
db.session.commit()
(注意 b 前缀使字符串成为字节文字)
推荐阅读
- arrays - SwiftUI中数组的值和标题列表
- javascript - Javascript:如何更改 URL 中的路径名
- jbpm - 在 JBPM 脚本任务中,我可以访问流程变量的最后更新信息吗
- javascript - 额外的编码查询来自哪里,它是什么意思?
- javascript - 如何验证正则表达式模式以检查 mimetype?
- android - 如何在 Android Studio 中无缝循环播放视频
- reactjs - 当抽屉打开/关闭时,抽屉的屏幕组件正在重新渲染
- linux - AWK 的终端错误表示超出限制
- android - 如何在 Flutter 中测试应用购买 [IAP][测试]
- react-native - 使用 react-native 可滚动时开玩笑失败