Issue
I've been experimenting with Flask, following a series by Corey Schafer on Youtube. I've tried to break off some of the concepts and build a very simplistic password application.
Thus far it works fine, but I'm wondering how I can build tests to insure that it's verifying password basic password validity. (THIS IS NOT TESTING PASSWORD MATCHING).
Obviously, in the application, it confirms if the password meets the minimum standards that being DataRequired()
and Length(min=8)
But how I can confirm it's correct in a unittest module? I'm having trouble visualizing how to build that out...
You can find a repo here: https://github.com/branhoff/password-tester
The basic format of my code is primarily a Registration form and the actual flask route that renders the functionality.
password_tester.py
from flask import Flask, render_template, flash
from forms import RegistrationForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
@app.route("/")
@app.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash(f'Sucess!', 'success')
return render_template('register.html', title='Register', form=form)
if __name__ == '__main__':
app.run(debug=True)
forms.py
from flask_wtf import FlaskForm
from wtforms import PasswordField, SubmitField
from wtforms.validators import DataRequired, Length
class RegistrationForm(FlaskForm):
password = PasswordField('Password', validators=[DataRequired(), Length(min=8)])
submit = SubmitField('Submit')
tests I've tried I've tried the following code as a test. But the status code is always the same, no matter what I change the password to... so I'm not really understanding how to actually test the result.
def test_pass_correct(self):
tester = app.test_client(self)
response = tester.post('/register', data=dict(password=''))
self.assertEqual(response.status_code, 200)
Solution
It's not very elegant, but in my html template, I print out the error message if there is one. And I can test that the message is somewhere in the HTML statement.
So something like this seems to work:
# Ensure that the password-tester behaves correctly given correct credentials
def test_pass_correct(self):
tester = app.test_client(self)
response = tester.post('/register', data=dict(password='testtest'))
self.assertFalse(b'Field must be at least 8 characters long.' in response.data)
# Ensure that the password-tester behaves correctly given incorrect credentials
def test_pass_incorrect(self):
tester = app.test_client(self)
response = tester.post('/register', data=dict(password='test'))
self.assertTrue(b'Field must be at least 8 characters long.' in response.data)
Answered By - Hofbr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.