首页 > 解决方案 > 单元测试返回错误,“详细信息:密钥(用户名)=(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”

标签: pythonunit-testingflask

解决方案


尝试做:

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


推荐阅读