def test_form_csrf_validation(app):
app.config['WTF_CSRF_SECRET_KEY'] = 'top secret !!!'
class TestForm(SanicForm):
msg = StringField('Note', validators=[DataRequired(), Length(max=10)])
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
async def index(request):
form = TestForm(request)
if request.method == 'POST' and form.validate():
return response.text('validated')
content = render_form(form)
return response.html(content)
req, resp = app.test_client.get('/')
assert resp.status == 200
assert 'csrf_token' in resp.text
token = re.findall(csrf_token_pattern, resp.text)[0]
assert token
payload = {'msg': 'happy', 'csrf_token': token}
req, resp = app.test_client.post('/', data=payload)
assert resp.status == 200
assert 'validated' in resp.text
payload = {'msg': 'happy'}
req, resp = app.test_client.post('/', data=payload)
assert resp.status == 200
# should fail, no CSRF token in payload
assert 'validated' not in resp.text
评论列表
文章目录