python - 如何为我用 Flask 编写的登录 API 编写 python 请求测试,以呈现相同的 HTML 表单?
问题描述
我一直在尝试使用 python requests 模块编写基本的登录测试。我使用渲染 HTML 页面的 Flask 设计了 API 端点。下面是登录的 HTML 表单:
<form action="{{ url_for('login') }}" method="post" id="login" >
<div class="msg"><p class = "messagep">{{ msg }}</p></div>
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label" >Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Username" id="username" name="username">
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</div>
<input type="checkbox" id="check">
<span>Remember me</span> </br></br>
<div class="right">
<a style="font-family: 'Arial';" href="#">Forgot Password</a>
<button type="submit" class="btn btn-light mb-2" name="log" >Submit</button>
</div>
</form>
用于登录的 Flask API 端点如下:
@app.route('/login', methods=['GET', 'POST'])
def login():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username = request.form['username']
password = request.form['password']
if not username or not password:
msg = 'Please enter your username/password!'
return render_template('login.html', msg=msg)
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", [username, password])
account = cursor.fetchone()
if account:
session['loggedin'] = True
# session['id'] = account['id']
session['username'] = account['username']
session['fname'] = account['first_name']
msg = 'Logged in successfully !'
return redirect(url_for("home"))
else:
msg = 'Incorrect username / password !'
elif request.method == 'POST':
msg = 'Please fill out the form !'
elif request.method == 'GET':
uname = session.get("username", "Unknown")
if uname == "Unknown":
return render_template('login.html')
else:
return redirect(url_for("home"))
return render_template('login.html', msg=msg)
对此的 Python 请求测试如下:
def check_sign_in():
try:
credentials = {'username': 'test', 'password': ''}
session = requests.Session()
response = session.post('http://127.0.0.1:5000/login', data=credentials)
assert response.status_code == 200
print('Sign in successful!')
except AssertionError as e:
print('Sign in error!')
e.args += ('Received response code:', response.status_code)
raise
我现在担心的是,即使我在上述情况下提供了不正确的凭据(如空密码),该测试也始终通过。我尝试了很多不同的方法,但仍然不明白为什么它一直通过。但是,手动测试时,此功能似乎可以正常工作。
解决方案
推荐阅读
- nginx - 在 Nginx 中提供 Base64 GIF
- python - 如何以特定顺序打印列表字典?
- prolog - 如果只有一个合乎逻辑的答案,如何询问序言
- java - 如何退出递归函数调用
- python - 在 Django 中自动返回“无”的 ID 字段
- python - LSTM 混淆中的时间步长
- python - 在 pandas DataFrame 中计算平均值时,如何过滤掉使用 <5 个值来计算平均值的行?
- javascript - 即使从 api 推送值,我的数组也返回空
- ffmpeg - 当我尝试使用网络摄像头的原始流时,为什么 ffmpeg 会挂起?
- react-native - 导入“@highcharts/highcharts-react-native”的问题 - 模块解析失败:意外的令牌