单元测试返回错误,表示"DETAIL: Key (username)=(test123) already exists.'"



我目前正试图测试一个闪光消息,我希望出现当有人试图与已在使用的用户名注册。然而,我不确定如何去做这个方法,我目前使用的是不工作。下面是我的测试代码:

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)已经存在。TypeError:需要bytes-like object,而不是'str'

try doing:

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前缀使字符串成为字节字面值)

最新更新