def register(): """Registers the user.""" if g.user: return redirect(url_for('timeline')) error = None if request.method == 'POST': if not request.form['username']: error = 'You have to enter a username' elif not request.form['email'] or \ '@' not in request.form['email']: error = 'You have to enter a valid email address' elif not request.form['password']: error = 'You have to enter a password' elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif get_user_id(request.form['username']) is not None: error = 'The username is already taken' else: db = get_db() db.execute( '''insert into user ( username, email, pw_hash) values (?, ?, ?)''', [ request.form['username'], request.form['email'], generate_password_hash(request.form['password']) ]) db.commit() flash('You were successfully registered and can login now') return redirect(url_for('login')) return render_template('register.html', error=error)
def test_build_error_handler(): app = keyes.Keyes(__name__) # Test base case, a URL which results in a BuildError. with app.test_request_context(): pytest.raises(BuildError, keyes.url_for, 'spam') # Verify the error is re-raised if not the current exception. try: with app.test_request_context(): keyes.url_for('spam') except BuildError as err: error = err try: raise RuntimeError('Test case where BuildError is not current.') except RuntimeError: pytest.raises( BuildError, app.handle_url_build_error, error, 'spam', {}) # Test a custom handler. def handler(error, endpoint, values): # Just a test. return '/test_handler/' app.url_build_error_handlers.append(handler) with app.test_request_context(): assert keyes.url_for('spam') == '/test_handler/'
def test_route_decorator_custom_endpoint(): app = keyes.Keyes(__name__) app.debug = True @app.route('/foo/') def foo(): return keyes.request.endpoint @app.route('/bar/', endpoint='bar') def for_bar(): return keyes.request.endpoint @app.route('/bar/123', endpoint='123') def for_bar_foo(): return keyes.request.endpoint with app.test_request_context(): assert keyes.url_for('foo') == '/foo/' assert keyes.url_for('bar') == '/bar/' assert keyes.url_for('123') == '/bar/123' c = app.test_client() assert c.get('/foo/').data == b'foo' assert c.get('/bar/').data == b'bar' assert c.get('/bar/123').data == b'123'
def register(): """Registers the user.""" if g.user: return redirect(url_for('timeline')) error = None if request.method == 'POST': if not request.form['username']: error = 'You have to enter a username' elif not request.form['email'] or \ '@' not in request.form['email']: error = 'You have to enter a valid email address' elif not request.form['password']: error = 'You have to enter a password' elif request.form['password'] != request.form['password2']: error = 'The two passwords do not match' elif get_user_id(request.form['username']) is not None: error = 'The username is already taken' else: db = get_db() db.execute('''insert into user ( username, email, pw_hash) values (?, ?, ?)''', [request.form['username'], request.form['email'], generate_password_hash(request.form['password'])]) db.commit() flash('You were successfully registered and can login now') return redirect(url_for('login')) return render_template('register.html', error=error)
def test_url_generation(): app = keyes.Keyes(__name__) @app.route('/hello/<name>', methods=['POST']) def hello(): pass with app.test_request_context(): assert keyes.url_for('hello', name='test x') == '/hello/test%20x' assert keyes.url_for('hello', name='test x', _external=True) == \ 'http://localhost/hello/test%20x'
def test_url_for_with_scheme(self): app = keyes.Keyes(__name__) @app.route('/') def index(): return '42' with app.test_request_context(): assert keyes.url_for('index', _external=True, _scheme='https') == 'https://localhost/'
def test_url_for_with_anchor(self): app = keyes.Keyes(__name__) @app.route('/') def index(): return '42' with app.test_request_context(): assert keyes.url_for('index', _anchor='x y') == '/#x%20y'
def login(): """Logs the user in.""" if g.user: return redirect(url_for('timeline')) error = None if request.method == 'POST': user = query_db('''select * from user where username = ?''', [request.form['username']], one=True) if user is None: error = 'Invalid username' elif not check_password_hash(user['pw_hash'], request.form['password']): error = 'Invalid password' else: flash('You were logged in') session['user_id'] = user['user_id'] return redirect(url_for('timeline')) return render_template('login.html', error=error)
def add_entry(): if not session.get('logged_in'): abort(401) db = get_db() db.execute('insert into entries (title, text) values (?, ?)', [request.form['title'], request.form['text']]) db.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries'))
def test_static_files(): app = keyes.Keyes(__name__) app.testing = True rv = app.test_client().get('/static/index.html') assert rv.status_code == 200 assert rv.data.strip() == b'<h1>Hello World!</h1>' with app.test_request_context(): assert keyes.url_for('static', filename='index.html') == \ '/static/index.html' rv.close()
def login(): error = None if request.method == 'POST': if request.form['username'] != app.config['USERNAME']: error = 'Invalid username' elif request.form['password'] != app.config['PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('You were logged in') return redirect(url_for('show_entries')) return render_template('login.html', error=error)
def add_message(): """Registers a new message for the user.""" if 'user_id' not in session: abort(401) if request.form['text']: db = get_db() db.execute('''insert into message (author_id, text, pub_date) values (?, ?, ?)''', (session['user_id'], request.form['text'], int(time.time()))) db.commit() flash('Your message was recorded') return redirect(url_for('timeline'))
def test_basic_url_generation(): app = keyes.Keyes(__name__) app.config['SERVER_NAME'] = 'localhost' app.config['PREFERRED_URL_SCHEME'] = 'https' @app.route('/') def index(): pass with app.app_context(): rv = keyes.url_for('index') assert rv == 'https://localhost/'
def follow_user(username): """Adds the current user as follower of the given user.""" if not g.user: abort(401) whom_id = get_user_id(username) if whom_id is None: abort(404) db = get_db() db.execute('insert into follower (who_id, whom_id) values (?, ?)', [session['user_id'], whom_id]) db.commit() flash('You are now following "%s"' % username) return redirect(url_for('user_timeline', username=username))
def unfollow_user(username): """Removes the current user as follower of the given user.""" if not g.user: abort(401) whom_id = get_user_id(username) if whom_id is None: abort(404) db = get_db() db.execute('delete from follower where who_id=? and whom_id=?', [session['user_id'], whom_id]) db.commit() flash('You are no longer following "%s"' % username) return redirect(url_for('user_timeline', username=username))
def test_proper_test_request_context(): app = keyes.Keyes(__name__) app.config.update( SERVER_NAME='localhost.localdomain:5000' ) @app.route('/') def index(): return None @app.route('/', subdomain='foo') def sub(): return None with app.test_request_context('/'): assert keyes.url_for('index', _external=True) == \ 'http://localhost.localdomain:5000/' with app.test_request_context('/'): assert keyes.url_for('sub', _external=True) == \ 'http://foo.localhost.localdomain:5000/' try: with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): pass except ValueError as e: assert str(e) == ( "the server name provided " "('localhost.localdomain:5000') does not match the " "server name from the WSGI environment ('localhost')" ) app.config.update(SERVER_NAME='localhost') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): pass app.config.update(SERVER_NAME='localhost:80') with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): pass
def test_proper_test_request_context(): app = keyes.Keyes(__name__) app.config.update(SERVER_NAME='localhost.localdomain:5000') @app.route('/') def index(): return None @app.route('/', subdomain='foo') def sub(): return None with app.test_request_context('/'): assert keyes.url_for('index', _external=True) == \ 'http://localhost.localdomain:5000/' with app.test_request_context('/'): assert keyes.url_for('sub', _external=True) == \ 'http://foo.localhost.localdomain:5000/' try: with app.test_request_context( '/', environ_overrides={'HTTP_HOST': 'localhost'}): pass except ValueError as e: assert str(e) == ( "the server name provided " "('localhost.localdomain:5000') does not match the " "server name from the WSGI environment ('localhost')") app.config.update(SERVER_NAME='localhost') with app.test_request_context( '/', environ_overrides={'SERVER_NAME': 'localhost'}): pass app.config.update(SERVER_NAME='localhost:80') with app.test_request_context( '/', environ_overrides={'SERVER_NAME': 'localhost:80'}): pass
def test_url_with_method(self): from keyes.views import MethodView app = keyes.Keyes(__name__) class MyView(MethodView): def get(self, id=None): if id is None: return 'List' return 'Get %d' % id def post(self): return 'Create' myview = MyView.as_view('myview') app.add_url_rule('/myview/', methods=['GET'], view_func=myview) app.add_url_rule('/myview/<int:id>', methods=['GET'], view_func=myview) app.add_url_rule('/myview/create', methods=['POST'], view_func=myview) with app.test_request_context(): assert keyes.url_for('myview', _method='GET') == '/myview/' assert keyes.url_for('myview', id=42, _method='GET') == '/myview/42' assert keyes.url_for('myview', _method='POST') == '/myview/create'
def add_message(): """Registers a new message for the user.""" if 'user_id' not in session: abort(401) if request.form['text']: db = get_db() db.execute( '''insert into message (author_id, text, pub_date) values (?, ?, ?)''', (session['user_id'], request.form['text'], int(time.time()))) db.commit() flash('Your message was recorded') return redirect(url_for('timeline'))
def timeline(): """Shows a users timeline or if no user is logged in it will redirect to the public timeline. This timeline shows the user's messages as well as all the messages of followed users. """ if not g.user: return redirect(url_for('public_timeline')) return render_template('timeline.html', messages=query_db(''' select message.*, user.* from message, user where message.author_id = user.user_id and ( user.user_id = ? or user.user_id in (select whom_id from follower where who_id = ?)) order by message.pub_date desc limit ?''', [session['user_id'], session['user_id'], PER_PAGE]))
def test_nosubdomain(): app = keyes.Keyes(__name__) app.config['SERVER_NAME'] = 'example.com' @app.route('/<company_id>') def view(company_id): return company_id with app.test_request_context(): url = keyes.url_for('view', company_id='xxx') with app.test_client() as c: response = c.get(url) assert 200 == response.status_code assert b'xxx' == response.data
def timeline(): """Shows a users timeline or if no user is logged in it will redirect to the public timeline. This timeline shows the user's messages as well as all the messages of followed users. """ if not g.user: return redirect(url_for('public_timeline')) return render_template( 'timeline.html', messages=query_db( ''' select message.*, user.* from message, user where message.author_id = user.user_id and ( user.user_id = ? or user.user_id in (select whom_id from follower where who_id = ?)) order by message.pub_date desc limit ?''', [session['user_id'], session['user_id'], PER_PAGE]))
def test_templates_and_static(test_apps): from blueprintapp import app c = app.test_client() rv = c.get('/') assert rv.data == b'Hello from the Frontend' rv = c.get('/admin/') assert rv.data == b'Hello from the Admin' rv = c.get('/admin/index2') assert rv.data == b'Hello from the Admin' rv = c.get('/admin/static/test.txt') assert rv.data.strip() == b'Admin File' rv.close() rv = c.get('/admin/static/css/test.css') assert rv.data.strip() == b'/* nested file */' rv.close() # try/finally, in case other tests use this app for Blueprint tests. max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] try: expected_max_age = 3600 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age: expected_max_age = 7200 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age rv = c.get('/admin/static/css/test.css') cc = parse_cache_control_header(rv.headers['Cache-Control']) assert cc.max_age == expected_max_age rv.close() finally: app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default with app.test_request_context(): assert keyes.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt' with app.test_request_context(): with pytest.raises(TemplateNotFound) as e: keyes.render_template('missing.html') assert e.value.name == 'missing.html' with keyes.Keyes(__name__).test_request_context(): assert keyes.render_template('nested/nested.txt') == 'I\'m nested'
def test_inject_blueprint_url_defaults(): app = keyes.Keyes(__name__) bp = keyes.Blueprint('foo.bar.baz', __name__, template_folder='template') @bp.url_defaults def bp_defaults(endpoint, values): values['page'] = 'login' @bp.route('/<page>') def view(page): pass app.register_blueprint(bp) values = dict() app.inject_url_defaults('foo.bar.baz.view', values) expected = dict(page='login') assert values == expected with app.test_request_context('/somepage'): url = keyes.url_for('foo.bar.baz.view') expected = '/login' assert url == expected
def index(): raise keyes.abort(keyes.redirect(keyes.url_for('test')))
def index(): return keyes.url_for('.about')
def test_url_generation_requires_server_name(): app = keyes.Keyes(__name__) with app.app_context(): with pytest.raises(RuntimeError): keyes.url_for('index')
def test_url_generation_without_context_fails(): with pytest.raises(RuntimeError): keyes.url_for('index')
def logout(): """Logs the user out.""" flash('You were logged out') session.pop('user_id', None) return redirect(url_for('public_timeline'))
def index(): return keyes.url_for('app_index')
def about(): return keyes.url_for('.index')
def frontend_page2(): return keyes.url_for('.frontend_index')
def app_index(): return keyes.url_for('test.index')
def something_else(): return keyes.url_for('about', lang_code='en')
def logout(): session.pop('logged_in', None) flash('You were logged out') return redirect(url_for('show_entries'))
def backend_index(): return keyes.url_for('myapp.frontend.frontend_index')