def test_fail_omit_password(self, app, form, client, valid_data): """Does our route fail if we omit the `password` on the form?""" with app.app_context(): User.create( name=valid_data['name'], username=valid_data['username'], email=valid_data['email'], password=valid_data['password'], ) invalid_data = { 'username': '******', } resp = client.post(type(self).LOGIN_URL, data=invalid_data, follow_redirects=True) html = BeautifulSoup(resp.data, 'html.parser') errors = html.find_all('p', {'class': 'form-error'}) assert len(errors) == 1 # The first element in our validators will always be `DataRequired()` assert errors[0].decode_contents( ) == form.password.validators[0].message
def test_fail_email_unique(self, app, client, valid_data): """Does our route fail if we send already-existing data for the `email` field?""" with app.app_context(): User.create(name=valid_data['name'], username=valid_data['username'], email=valid_data['email'], password=valid_data['password'], ) # Same email, different username invalid_data = { 'name': 'test test', 'username': '******', 'email': '*****@*****.**', 'password': '******', 'month': 1, # January 1st, 2000. 'day': 1, 'year': 2000, } resp = client.post(type(self).SIGNUP_URL, data=invalid_data, follow_redirects=True) html = BeautifulSoup(resp.data, 'html.parser') errors = html.find_all('p', {'class': 'form-error'}) assert len(errors) == 1 assert errors[0].decode_contents() == 'Email must be unique.'
def test_auth_redirects(self, app, client, valid_data): """Does our login route return a redirect to our dashboard route if authentication is present?""" with app.app_context(): User.create( name=valid_data['name'], username=valid_data['username'], email=valid_data['email'], password=valid_data['password'], ) resp = client.post(type(self).LOGIN_URL, data=valid_data, follow_redirects=False) assert resp.status_code == 302 headers = dict(resp.headers) assert 'Location' in headers assert headers['Location'] == url_for('twitter.dashboard') loginresp = client.get(type(self).LOGIN_URL, follow_redirects=False) loginheaders = dict(loginresp.headers) assert 'Location' in loginheaders assert loginheaders['Location'] == url_for('twitter.dashboard')
def test_route_clears_session(self, app, client, valid_data): """Does the route properly clear our `uid` key out of session?""" with app.test_request_context(): User.create( name=valid_data['name'], username=valid_data['username'], email=valid_data['email'], password=valid_data['password'], ) # I see. So you can't send requests with the # `session_transaction()` open. You have to close it first, then # send a request, and then re-open it to re-examine the session # object. You also can't use out-of-context things (like our # helper functions `do_login`/`do_logout`), so you must set the # keys in session manually. with client.session_transaction() as session: session['uid'] = User.authenticate(valid_data['username'], valid_data['password']).id assert 'uid' in session # Exmaple of persistence between open-close context managers for # `session_transaction()`. with client.session_transaction() as session: assert 'uid' in session resp = client.post(type(self).LOGOUT_URL, follow_redirects=True) with client.session_transaction() as session: assert resp.status_code == 200 assert 'uid' not in session
def sign_up(): form = SignUpForm() if form.validate_on_submit(): name = form.name.data email = form.email.data password = form.password.data #authenticate a user try: User.create(name, email, password) # Sign up successful flash( 'User {}, created with id={}'.format(current_user.email, current_user.id), 'teal') return redirect(url_for('main.index')) except Exception as e: # Sign up unsuccessful if type(e.args[0]) == str: error = e.args[0] # weird bug where not returning json else: error_json = e.args[1] error = json.loads(error_json)['error']['message'] flash("Error: {}".format(error), 'red') return render_template('auth/sign_up.html', title='Sign Up', form=form)
def main(): db.drop_all() db.create_all() User.create('admin', 'password') db.session.add(Genre(name='No genre', is_default=True)) db.session.add_all([ Genre(name='Alcohol'), Genre(name='Non Alcohol'), Genre(name='Food'), Genre(name='Other') ]) db.session.commit()
def register(): form = RegisterForm() if form.validate_on_submit(): if User.query.filter_by(name=form.username.data).first(): flash(f'[{form.username.data}] is already exist.', category='danger') return redirect(url_for('auth.register')) else: User.create(form.username.data, form.password.data) flash('Registration completed') return redirect(url_for('auth.register')) return render_template('auth/register.html', title='Register', form=form)
def test_model_create(self, app): """Does our static method `User.create()` store information in the DB?""" with app.app_context(): User.create(name='tester', username='******', email='*****@*****.**', password='******') user = User.query.first() assert user is not None assert user.name == 'tester' assert user.username == 'testing' assert user.email == '*****@*****.**' assert user.password != 'Qweqweqwe123'
def test_model_write(self, app): """Can our model be used to write data to the DB?""" with app.app_context(): new_user = User.create( name='test test', username='******', email='*****@*****.**', password='******', ) new_post = Post(content='Test post content', user=new_user) reply_post = Post(content='Test reply content', user=new_user) new_post.replies.append(reply_post) db.session.add(new_post) db.session.add(reply_post) db.session.commit() extracted_post = Post.query.first() assert len(Post.query.all()) == 2 assert extracted_post is not None assert extracted_post.content == 'Test post content' assert extracted_post.user == new_user assert len(extracted_post.replies) == 1 extracted_reply = extracted_post.replies[0] assert extracted_reply.user == new_user assert extracted_reply.content == 'Test reply content' assert len(extracted_reply.replies_to) == 1 assert extracted_reply.replies_to[0] == extracted_post
def test_fail_invalid_combination(self, app, client, valid_data): """Does our route fail if we send invalid data?""" with app.app_context(): User.create( name=valid_data['name'], username=valid_data['username'], email=valid_data['email'], password=valid_data['password'], ) # Correct username, but incorrect password. invalid_data = { 'username': '******', 'password': '******', } resp = client.post(type(self).LOGIN_URL, data=invalid_data, follow_redirects=True) html = BeautifulSoup(resp.data, 'html.parser') errors = html.find_all('p', {'class': 'form-error'}) assert len(errors) == 1 # The first element in our validators will always be # `DataRequired()` assert errors[0].decode_contents( ) == 'The username and password you entered did not match our records. Please double-check and try again.' # Correct password but incorrect username. invalid_data = { 'username': '******', 'password': '******', } resp = client.post(type(self).LOGIN_URL, data=invalid_data, follow_redirects=True) html = BeautifulSoup(resp.data, 'html.parser') errors = html.find_all('p', {'class': 'form-error'}) assert len(errors) == 1 # The first element in our validators will always be # `DataRequired()` assert errors[0].decode_contents( ) == 'The username and password you entered did not match our records. Please double-check and try again.'
def user(password): name = 'tester' email = '*****@*****.**' user = User.create(name, email, password) yield user print('') user.destroy()
def test_create_method_returns_a_valid_user_object(_, __): user = User.create(**user_data_sample) assert isinstance(user, User), 'user is not an instance of User' assert isinstance(user.dob, datetime), 'user.dob is not in datetime format' assert isinstance(user.username, str), 'user.username is not a string' assert isinstance(user.id, str), 'user.id is not a string' assert user.id == f'user:{user_data_sample["username"]}', 'user.id does not align well with username' assert sha256_crypt.verify(user_data_sample['password'], user.password),\ 'original password is not verified by hashed password'
def test_route_logs_in(self, app, client, valid_data): """Does our route log us in given valid data via a POST request?""" with app.app_context(): User.create( name=valid_data['name'], username=valid_data['username'], email=valid_data['email'], password=valid_data['password'], ) client.post(type(self).LOGIN_URL, data=valid_data, follow_redirects=True) user = User.query.first() with client.session_transaction() as session: assert 'uid' in session assert session['uid'] == user.id
def test_route_redirects(self, app, client, valid_data): """Does our route return a redirect to our dashboard route after being given valid data via a POST request?""" with app.app_context(): User.create( name=valid_data['name'], username=valid_data['username'], email=valid_data['email'], password=valid_data['password'], ) resp = client.post(type(self).LOGIN_URL, data=valid_data, follow_redirects=False) assert resp.status_code == 302 headers = dict(resp.headers) assert 'Location' in headers assert headers['Location'] == url_for('twitter.dashboard')
def post(self): data = request.get_json() username = data.get('username', None) password = data.get('password', None) first_name = data.get('first_name', None) last_name = data.get('last_name', None) if (username and password and first_name and last_name): new_user = User.create(username, password) if new_user: UserInfo.create(new_user.id, first_name, last_name) return jsonify({'message': 'Successful'}) else: return jsonify({'error': 'Username has been registered'}), 404 return jsonify({'error': 'Cannot perform'}), 404
def signup(): """User signup page.""" form = RegistrationForm() if form.validate_on_submit(): new_user = User.create(form.name.data, form.username.data, form.email.data, form.password.data, ) do_login(new_user) return redirect(url_for('twitter.dashboard')) return render_template('auth/signup.html', form=form)
def test_model_write(self, app): """Can our model be used to write data to the DB?""" with app.app_context(): new_user = User.create( name='test test', username='******', email='*****@*****.**', password='******', ) new_post = Post(content='Test post content', user=new_user) db.session.add(new_post) db.session.commit() extracted_post = Post.query.first() assert extracted_post is not None assert extracted_post.content == 'Test post content' assert extracted_post.user == new_user
def test_user_create(self): User.create('test_user', 'password') user = User.query.filter_by(name='test_user').first() self.assertTrue(user)