def get_app(): app = Tipfy(rules=[ Rule('/login', name='auth/login', handler=LoginHandler), Rule('/logout', name='auth/logout', handler=LogoutHandler), Rule('/signup', name='auth/signup', handler=SignupHandler), ]) return app
def test_redirect_relative_uris(self): class MyHandler(RequestHandler): def get(self): return self.redirect(self.request.args.get('redirect')) app = Tipfy(rules=[ Rule('/foo/bar', name='test1', handler=MyHandler), Rule('/foo/bar/', name='test2', handler=MyHandler), ]) client = app.get_test_client() response = client.get('/foo/bar/', query_string={'redirect': '/baz'}) self.assertEqual(response.headers['Location'], 'http://localhost/baz') response = client.get('/foo/bar/', query_string={'redirect': './baz'}) self.assertEqual(response.headers['Location'], 'http://localhost/foo/bar/baz') response = client.get('/foo/bar/', query_string={'redirect': '../baz'}) self.assertEqual(response.headers['Location'], 'http://localhost/foo/baz') response = client.get('/foo/bar', query_string={'redirect': '/baz'}) self.assertEqual(response.headers['Location'], 'http://localhost/baz') response = client.get('/foo/bar', query_string={'redirect': './baz'}) self.assertEqual(response.headers['Location'], 'http://localhost/foo/baz') response = client.get('/foo/bar', query_string={'redirect': '../baz'}) self.assertEqual(response.headers['Location'], 'http://localhost/baz')
def get_rules(app): """Returns a list of URL rules for the Feed application. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [ HandlerPrefix('apps.feed.handlers.', [ Rule('/feed/blog/', endpoint='feed/blog', handler='BlogFeedHandler'), Rule('/feed/blog/tag/<tag>/', endpoint='feed/blog', handler='BlogFeedHandler'), Rule('/feed/product/', endpoint='feed/shop', handler='ProductFeedHandler'), Rule('/feed/product/tag/<tag>/', endpoint='feed/shop', handler='ProductFeedHandler'), ]), ] return rules
def test_custom_error_handlers(self): app = Tipfy([ Rule('/', handler=AllMethodsHandler, name='home'), Rule('/broken', handler=BrokenHandler, name='broken'), ], debug=False) app.error_handlers = { 404: Handle404, 405: Handle405, 500: Handle500, } client = app.get_test_client() res = client.get('/nowhere') self.assertEqual(res.status_code, 404) self.assertEqual(res.data, '404 custom handler') res = client.put('/broken') self.assertEqual(res.status_code, 405) self.assertEqual(res.data, '405 custom handler') self.assertEqual(res.headers.get('Allow'), 'GET') res = client.get('/broken') self.assertEqual(res.status_code, 500) self.assertEqual(res.data, '500 custom handler')
def test_rule_empty_2(self): rule = Rule('/', endpoint='home', handler='test.home:HomeHandler', defaults={'foo': 'bar'}) rule_2 = rule.empty() assert rule_2.handler == 'test.home:HomeHandler' assert rule_2.endpoint == 'home' assert rule_2.defaults == {'foo': 'bar'}
def get_rules(): # Fake get_rules() for testing. return [ Rule('/_tasks/process-mymodel/', name='tasks/process-mymodel', handler='%s.TaskTestModelEntityTaskHandler' % __name__), Rule('/_tasks/process-mymodel/<string:key>', name='tasks/process-mymodel', handler='%s.TaskTestModelEntityTaskHandler' % __name__), ]
def get_app(): return Tipfy(rules=[ Rule('/', name='xmpp-test', handler='resources.xmpp_handlers.XmppHandler'), Rule('/test2', name='xmpp-test', handler='resources.xmpp_handlers.XmppHandler2'), ], debug=True)
def test_redirect_empty(self): class HandlerWithRedirect(RequestHandler): def get(self, **kwargs): return self.redirect('/', empty=True) app = Tipfy(rules=[ Rule('/', name='home', handler=AllMethodsHandler), Rule('/redirect-me', name='redirect', handler=HandlerWithRedirect), ]) client = app.get_test_client() response = client.get('/redirect-me', follow_redirects=False) self.assertEqual(response.data, '')
def get_rules(app): rules = [ Rule('/links/add', endpoint="links/add", handler='apps.links.handlers.AddLinkHandler'), Rule('/links/review', endpoint="links/review", handler='apps.links.handlers.ReviewLinksHandler'), Rule('/links/change', endpoint="links/change-status", handler='apps.links.handlers.ChangeLinkStatusHandler'), ] return rules
def get_rules(app): """Returns a list of URL rules for the Users application. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [ HandlerPrefix('apps.user.handlers.', [ Rule('/sign-in/', endpoint='auth/login', handler='LoginHandler'), Rule('/sign-out/', endpoint='auth/logout', handler='LogoutHandler'), Rule('/sign-up/', endpoint='auth/signup', handler='SignupHandler'), Rule('/create-account/', endpoint='auth/register', handler='RegisterHandler'), Rule('/auth/facebook/', endpoint='auth/facebook', handler='FacebookHandler'), Rule('/auth/google/', endpoint='auth/google', handler='GoogleHandler'), Rule('/your/', endpoint='user/profile', handler='ProfileHandler'), Rule('/verify/<verification_code>/', endpoint='user/verify', handler='VerifyProfileHandler'), ]), ] return rules
def get_rules(app): """Returns a list of URL rules for the Hello, World! application. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [ Rule('/hello', endpoint='hello-world', handler='apps.hello_world.handlers.HelloWorldHandler'), Rule('/pretty', endpoint='hello-world-pretty', handler='apps.hello_world.handlers.PrettyHelloWorldHandler'), ] return rules
def get_rules(app): rules = [ HandlerPrefix('apps.mail.handlers.', [ Rule('/_ah/mail/inbound', endpoint='mail/incoming', handler='IncomingMailHandler'), Rule('/mail/send/', endpoint='mail/send', handler='OrderMailHandler'), Rule('/mail/verify/<user_key>/', endpoint='mail/verify', handler='VerificationMailHandler'), ]) ] return rules
def test_set_delete_cookie(self): class MyHandler(BaseHandler): def get(self): res = self.request.cookies.get('test') if not res: res = 'undefined' self.session_store.set_cookie('test', 'a cookie value') else: self.session_store.delete_cookie('test') return Response(res) rules = [Rule('/', name='test', handler=MyHandler)] app = self._get_app('/') app.router.add(rules) client = app.get_test_client() response = client.get('/') self.assertEqual(response.data, 'undefined') response = client.get('/', headers={ 'Cookie': '\n'.join(response.headers.getlist('Set-Cookie')), }) self.assertEqual(response.data, 'a cookie value') response = client.get('/', headers={ 'Cookie': '\n'.join(response.headers.getlist('Set-Cookie')), }) self.assertEqual(response.data, 'undefined') response = client.get('/', headers={ 'Cookie': '\n'.join(response.headers.getlist('Set-Cookie')), }) self.assertEqual(response.data, 'a cookie value')
def test_set_session_datastore(self): class MyHandler(BaseHandler): def get(self): session = self.session_store.get_session(backend='datastore') res = session.get('key') if not res: res = 'undefined' session = DatastoreSession(None, 'a_random_session_id') session['key'] = 'a session value' self.session_store.set_session(self.session_store.config['cookie_name'], session, backend='datastore') return Response(res) rules = [Rule('/', name='test', handler=MyHandler)] app = self._get_app('/') app.router.add(rules) client = app.get_test_client() response = client.get('/') self.assertEqual(response.data, 'undefined') response = client.get('/', headers={ 'Cookie': '\n'.join(response.headers.getlist('Set-Cookie')), }) self.assertEqual(response.data, 'a session value')
def get_url_rules(): # Fake get_rules() for testing. rules = [ Rule('/_ah/queue/deferred', name='tasks/deferred', handler='tipfy.appengine.taskqueue.DeferredHandler'), ] return Map(rules)
def test_handle_exception_2(self): res = 'I fixed it!' class MyMiddleware(object): def handle_exception(self, handler, exception): raise ValueError() class MyHandler(RequestHandler): middleware = [MyMiddleware()] def get(self, **kwargs): raise ValueError() class ErrorHandler(RequestHandler): def handle_exception(self, exception): return Response(res) app = Tipfy(rules=[ Rule('/', name='home', handler=MyHandler), ], debug=False) app.error_handlers[500] = ErrorHandler client = app.get_test_client() response = client.get('/') self.assertEqual(response.data, res)
def test_middleware_multiple_changes(self): class MyHandler(RequestHandler): middleware = [SessionMiddleware(), i18n.I18nMiddleware()] def get(self, **kwargs): locale = self.i18n.locale return Response(locale) app = Tipfy(rules=[ Rule('/', name='home', handler=MyHandler) ], config={ 'tipfy.sessions': { 'secret_key': 'secret', }, 'tipfy.i18n': { 'locale_request_lookup': [('args', 'lang'), ('session', '_locale')], } }) client = app.get_test_client() response = client.get('/') self.assertEqual(response.data, 'en_US') response = client.get('/?lang=pt_BR') self.assertEqual(response.data, 'pt_BR') response = client.get('/') self.assertEqual(response.data, 'pt_BR') response = client.get('/?lang=en_US') self.assertEqual(response.data, 'en_US') response = client.get('/') self.assertEqual(response.data, 'en_US')
def test_set_get_secure_cookie(self): class MyHandler(BaseHandler): def get(self): response = Response() cookie = self.session_store.get_secure_cookie('test') or {} res = cookie.get('test') if not res: res = 'undefined' self.session_store.set_secure_cookie(response, 'test', {'test': 'a secure cookie value'}) response.data = res return response rules = [Rule('/', name='test', handler=MyHandler)] app = self._get_app('/') app.router.add(rules) client = app.get_test_client() response = client.get('/') self.assertEqual(response.data, 'undefined') response = client.get('/', headers={ 'Cookie': '\n'.join(response.headers.getlist('Set-Cookie')), }) self.assertEqual(response.data, 'a secure cookie value')
def test_handle_exception(self): app = Tipfy([ Rule('/', handler=AllMethodsHandler, name='home'), Rule('/broken', handler=BrokenHandler, name='broken'), Rule('/broken-but-fixed', handler=BrokenButFixedHandler, name='broken-but-fixed'), ], debug=False) client = app.get_test_client() response = client.get('/broken') self.assertEqual(response.status_code, 500) response = client.get('/broken-but-fixed') self.assertEqual(response.status_code, 200) self.assertEqual(response.data, 'That was close!')
def get_rules(app): """Returns a list of URL rules for the Hello, World! application. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [ Rule('/', endpoint='home', handler='apps.account.handlers.HomeHandler'), Rule('/auth/login', endpoint='auth/login', handler='apps.account.handlers.LoginHandler'), Rule('/auth/logout', endpoint='auth/logout', handler='apps.account.handlers.LogoutHandler'), Rule('/auth/signup', endpoint='auth/signup', handler='apps.account.handlers.SignupHandler'), Rule('/auth/register', endpoint='auth/register', handler='apps.account.handlers.RegisterHandler'), Rule('/auth/request', endpoint='auth/request', handler='apps.account.handlers.RequestAccountHandler'), Rule('/content', endpoint='content/index', handler='apps.account.handlers.ContentHandler'), ] return rules
def get_rules(app): """Returns a list of URL rules for the Blog application. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [ HandlerPrefix('apps.blog.handlers.', [ Rule('/news/', endpoint='blog/index', handler='BlogIndexHandler'), Rule('/news/tag/<tag>/', endpoint='blog/tag', handler='BlogTagListHandler'), Rule('/news/archive/', endpoint='blog/archive', handler='BlogArchiveHandler'), Rule('/news/<int:year>/', endpoint='blog/archive/year', handler='BlogArchiveHandler'), Rule('/news/<int:year>/<int:month>/', endpoint='blog/archive/year/month', handler='BlogArchiveHandler'), Rule('/news/<int:year>/<int:month>/<int:day>/', endpoint='blog/archive/year/month/day', handler='BlogArchiveHandler'), Rule('/news/<int:year>/<int:month>/<int:day>/<slug>/', endpoint='blog/post', handler='BlogPostHandler'), ]), ] return rules
def test_user_model(self): app = get_app() app.router.add(Rule('/', name='home', handler=HomeHandler)) request = Request.from_values('/') local.current_handler = RequestHandler(app, request) store = AuthStore(local.current_handler) self.assertEqual(store.user_model, User)
def test_get_config(self): app = Tipfy(rules=[ Rule('/', name='home', handler=AllMethodsHandler), ], config={'foo': { 'bar': 'baz', }}) with app.get_test_handler('/') as handler: self.assertEqual(handler.get_config('foo', 'bar'), 'baz')
def get_rules(app): """Returns a list of URL rules for the Pages application. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [ HandlerPrefix('apps.pages.handlers.', [ Rule('/', endpoint='pages/welcome', handler='WelcomePageHandler'), Rule('/page/<slug>/', endpoint='pages/show', handler='PageHandler'), Rule('/not-found/', endpoint='notfound', handler='ErrorHandler'), ]), ] return rules
def get_rules(app): """Returns a list of URL rules for the Hello, World! application. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [ Rule('/job/<jobid>', endpoint='job', handler='apps.job.handlers.JobHandler'), Rule('/quote/submit', endpoint='job-quote-submit', handler='apps.job.handlers.SubmitQuoteHandler'), Rule('/quote/approve', endpoint='job-quote-approve', handler='apps.job.handlers.ApproveQuoteHandler'), Rule('/quote/reject', endpoint='job-quote-reject', handler='apps.job.handlers.RejectQuoteHandler'), Rule('/layout/approve', endpoint='job-layout-approve', handler='apps.job.handlers.ApproveLayoutHandler'), Rule('/layout/reject', endpoint='job-layout-reject', handler='apps.job.handlers.RejectLayoutHandler'), Rule('/job/advance', endpoint='job-advance', handler='apps.job.handlers.AdvanceJobHandler'), Rule('/job/regress', endpoint='job-regress', handler='apps.job.handlers.RegressJobHandler'), Rule('/job/im', endpoint='job-im', handler='apps.job.handlers.CommunicateHandler'), Rule('/job/ims', endpoint='job-ims', handler='apps.job.handlers.GetCommunicationForJobHandler') ] return rules
def test_signup_url(self): app = get_app() app.router.add(Rule('/', name='home', handler=HomeHandler)) with app.get_test_context() as request: request.app.router.match(request) store = AuthStore(request) self.assertEqual( store.signup_url(), request.app.router.url_for(request, 'auth/signup', dict(redirect='/')))
def get_app(self): return Tipfy(rules=[ Rule('/', name='home', handler=RequestHandler) ], config={ 'tipfy.sessions': { 'secret_key': 'secret', }, 'tipfy.i18n': { 'timezone': 'UTC' }, })
def test_set_get_messages(self): class MyHandler(BaseHandler): @cached_property def messages(self): """A list of status messages to be displayed to the user.""" messages = [] flashes = self.session.get_flashes(key='_messages') for msg, level in flashes: msg['level'] = level messages.append(msg) return messages def set_message(self, level, body, title=None, life=None, flash=False): """Adds a status message. :param level: Message level. Common values are "success", "error", "info" or "alert". :param body: Message contents. :param title: Optional message title. :param life: Message life time in seconds. User interface can implement a mechanism to make the message disappear after the elapsed time. If not set, the message is permanent. :returns: None. """ message = {'title': title, 'body': body, 'life': life} if flash is True: self.session.flash(message, level, '_messages') else: self.messages.append(message) def get(self): self.set_message('success', 'a normal message value') self.set_message('success', 'a flash message value', flash=True) return Response('|'.join(msg['body'] for msg in self.messages)) rules = [Rule('/', name='test', handler=MyHandler)] app = self._get_app('/') app.router.add(rules) client = app.get_test_client() response = client.get('/') self.assertEqual(response.data, 'a normal message value') response = client.get('/', headers={ 'Cookie': '\n'.join(response.headers.getlist('Set-Cookie')), }) self.assertEqual(response.data, 'a flash message value|a normal message value')
def test_url_for(self): app = Tipfy(rules=[ Rule('/', name='home', handler=AllMethodsHandler), Rule('/about', name='about', handler='handlers.About'), Rule('/contact', name='contact', handler='handlers.Contact'), ]) with app.get_test_handler('/') as handler: self.assertEqual(handler.url_for('home'), '/') self.assertEqual(handler.url_for('about'), '/about') self.assertEqual(handler.url_for('contact'), '/contact') # Extras self.assertEqual(handler.url_for('about', _anchor='history'), '/about#history') self.assertEqual(handler.url_for('about', _full=True), 'http://localhost/about') self.assertEqual( handler.url_for('about', _netloc='www.google.com'), 'http://www.google.com/about') self.assertEqual(handler.url_for('about', _scheme='https'), 'https://localhost/about')
def setUp(self): app = Tipfy(rules=[ Rule('/', name='home', handler=RequestHandler) ], config={ 'tipfy.sessions': { 'secret_key': 'secret', }, 'tipfy.i18n': { 'timezone': 'UTC' }, }) local.current_handler = RequestHandler(app, Request.from_values('/'))
def test_user_required_if_authenticated_middleware(self): class MyHandler(HomeHandler): middleware = [UserRequiredIfAuthenticatedMiddleware()] app = get_app() app.router.add(Rule('/', name='home', handler=MyHandler)) client = app.get_test_client() response = client.get('/') self.assertEqual(response.status_code, 200) self.assertEqual(response.data, 'home sweet home')
def test_rule_empty(self): rule = Rule('/', endpoint='home', handler='test.home:HomeHandler') rule_2 = rule.empty() assert rule_2.handler == 'test.home:HomeHandler' assert rule_2.endpoint == 'home'