I have been trying to write basic login test using the python requests module. I designed the API endpoints using Flask which renders the HTML pages. Below is the HTML form for the login:
<form action="" method="post" id="login" >
<div class="msg"></div>
<label style="margin: 10px;"><b>User Name
</b>
</label>
<input style="margin: 10px;" id="username" name="username" type="text" placeholder="Enter Your Username" class="textbox"/>
<br><br>
<label style="margin: 10px;"><b>Password
</b>
</label>
<input style="margin: 10px;" id="password" name="password" type="password" placeholder="Enter Your Password" class="textbox"/>
<br><br>
<input type="submit" name="log" id="log" value="Log In"></br></br>
<br><br>
<input type="checkbox" id="check">
<span>Remember me</span>
<br><br>
<a style="font-family: 'Arial';" href="#">Forgot Password</a>
</form>
The Flask API endpoint for login is as below:
@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)
The Python requests test for this is as below:
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
My worry now is that this test always passes even if I give incorrect credentials like in the above case, an empty password. I really tried a lot of different approaches but still don't understand why it keeps passing. However, this feature seems to work properly when testing manually. I would really appreciate it if someone can help me with this as it is something urgently needed from my side. Thank you!
Aucun commentaire:
Enregistrer un commentaire