def test_nested_prefixes(self): "Reverse with nested prefexes" app = ( web.prefix("/news/<section>") | web.namespace("news") | web.cases( web.match(), web.prefix("/<int:id>") | web.namespace("item") | web.cases( web.match(), web.prefix("/docs") | web.namespace("docs") | web.cases(web.match(), web.match("/<int:id>", "item")), ), ) ) r = web.Reverse.from_handler(app) # Normal behavior self.assertEqual(r.news(section="top").as_url, "/news/top") self.assertEqual(r.news(section="top").item(id=1).as_url, "/news/top/1") self.assertEqual(r.news(section="top").item(id=1).docs.as_url, "/news/top/1/docs") self.assertEqual(r.news(section="top").item(id=1).docs.item(id=2).as_url, "/news/top/1/docs/2") # Exceptional behavior self.assertRaises(UrlBuildingError, lambda: r.news.as_url) # XXX this one raises KeyError, not UrlBuildingError self.assertRaises(UrlBuildingError, lambda: r.news(foo="top").as_url) self.assertRaises(UrlBuildingError, lambda: r.news(section="top").item.as_url) self.assertRaises(UrlBuildingError, lambda: r.news(section="top").item(id=1).docs()) self.assertRaises(UrlBuildingError, lambda: r.news(section="top")()) self.assertRaises(UrlBuildingError, lambda: r.news.item)
def test_nested_prefixes(self): 'Reverse with nested prefexes' app = web.prefix('/news/<section>', name='news') | web.cases( web.match(), web.prefix('/<int:id>', name='item') | web.cases( web.match(), web.prefix('/docs', name='docs') | web.cases( web.match(), web.match('/<int:id>', 'item')))) r = web.Reverse.from_handler(app) # Normal behavior self.assertEqual(r.news(section='top').as_url, '/news/top') self.assertEqual(r.news(section='top').item(id=1).as_url, '/news/top/1') self.assertEqual(r.news(section='top').item(id=1).docs.as_url, '/news/top/1/docs') self.assertEqual(r.news(section='top').item(id=1).docs.item(id=2).as_url, '/news/top/1/docs/2') # Exceptional behavior self.assertRaises(UrlBuildingError, lambda: r.news.as_url) # XXX this one raises KeyError, not UrlBuildingError self.assertRaises(UrlBuildingError, lambda: r.news(foo='top').as_url) self.assertRaises(UrlBuildingError, lambda: r.news(section='top').item.as_url) self.assertRaises(UrlBuildingError, lambda: r.news(section='top').item(id=1).docs()) self.assertRaises(UrlBuildingError, lambda: r.news(section='top')()) self.assertRaises(UrlBuildingError, lambda: r.news.item)
def app(self): if isinstance(self.stream, Loner): prefix = web.prefix('/'+self.action, name=self.action) else: prefix = web.prefix('/<idconv:item>/'+self.action, name=self.action, convs={'idconv': self.stream.id_converter}) return prefix | self.PrepareItemHandler(self) | self
def app(self): if isinstance(self.stream, Loner): prefix = web.prefix('/' + self.action, name=self.action) else: prefix = web.prefix('/<idconv:item>/' + self.action, name=self.action, convs={'idconv': self.stream.id_converter}) return prefix | self.PrepareItemHandler(self) | self
def test_nested_namespaces(self): def test_ns(env, data): self.assertEqual(env.namespace, "ns1.ns2") return 1 app = web.prefix("/ns1", name="ns1") | web.prefix("/ns2", name="ns2") | web.match() | test_ns self.assertEqual(web.ask(app, "/ns1/ns2"), 1)
def app(self): return web.prefix('/tray') | web.cases( Rule('/<int:tray>', self.tray), web.prefix('/_') | web.method('POST', strict=True) | web.cases( Rule('/put', self.put_to_tray), Rule('/user/put', self.put_to_user_tray), Rule('/delete', self.delete_from_tray), ) )
def test_nested_namespaces(self): def test_ns(env, data): return env.namespace app = web.prefix('/ns1', name="ns1") | \ web.prefix('/ns2', name="ns2") | \ web.match() | test_ns self.assertEqual(web.ask(app, '/ns1/ns2'), 'ns1.ns2')
def test_multiple_params(self): app = ( web.prefix("/persons/<int:person_id>") | web.namespace("persons") | web.cases(web.prefix("/news") | web.namespace("news") | web.match("/<int:news_id>", "item")) ) r = web.Reverse.from_handler(app) r1 = r.persons(person_id=1).news.item(news_id=2) self.assertEqual(r1.as_url, "/persons/1/news/2") self.assertEqual(r.build_url("persons.news.item", person_id=1, news_id=2), "/persons/1/news/2")
def app(self): if isinstance(self.stream, Loner): prefix = web.prefix('/log', name=self.action) else: prefix = web.prefix('/<idconv:item>/log', name=self.action, convs={'idconv': self.stream.id_converter}) return prefix | self.PrepareItemHandler(self) | web.cases( web.match('') | self, web.match('/<int:log_id>', 'entry') | self.log_entry, )
def test_prefix_after_namespace(self): app = web.prefix('/news', name='news') | web.prefix('/<section>') | web.cases( web.match(), web.match('/<int:id>', 'item'), ) r = web.Reverse.from_handler(app) self.assertEqual(r.build_url('news.item', section='top', id=1), '/news/top/1') self.assertEqual(r.build_url('news', section='top'), '/news/top') self.assertEqual(r.news(section='top').item(id=1).as_url, '/news/top/1') self.assertEqual(r.news(section='top').as_url, '/news/top')
def test_nested_prefix_without_ns(self): chain = web.prefix('/docs', name='docs') | web.cases( web.match('/', name='all'), web.prefix('/news') | web.cases( web.match('/', 'news_index'), web.match('/all', 'news_all') ) ) r = web.Reverse.from_handler(chain) self.assertEqual(r.docs.all.as_url, '/docs/') self.assertEqual(r.docs.news_index.as_url, '/docs/news/')
def test_multiple_params2(self): app = web.prefix('/persons') | web.namespace('persons') |\ web.prefix('/<int:person_id>') | web.cases( web.prefix('/news') | web.namespace('news') | web.match('/<int:news_id>', 'item') ) r = web.Reverse.from_handler(app) r1 = r.persons.news(person_id=1).item(news_id=2) self.assertEqual(r1.as_url, '/persons/1/news/2') self.assertEqual(r.build_url('persons.news.item', person_id=1, news_id=2), '/persons/1/news/2')
def test_nested_cases_with_prefixes(self): "Reverse with nested web.cases with web.prefixes" chain = web.cases( web.match("/", "index"), web.prefix("/docs") | web.cases(web.match("/<int:id>", "doc"), web.match("/list", "docs")), web.prefix("/news") | web.cases(web.match("/<int:id>", "news"), web.match("/list", "newslist")), ) r = web.Reverse.from_handler(chain) self.assertEqual(r.index.as_url, "/") self.assertEqual(r.docs.as_url, "/docs/list") self.assertEqual(r.newslist.as_url, "/news/list") self.assertEqual(r.doc(id=1).as_url, "/docs/1") self.assertEqual(r.news(id=1).as_url, "/news/1")
def prefix_handler(self): @web.request_filter def set_models(env, data, nxt): # assert data.version in self.versions_dict.keys() env.models = getattr(env.models, data.version) env.models = getattr(env.models, data.lang) env.version = data.version env.lang = data.lang return nxt(env, data) version_prefix = web.prefix('/<any("%s"):version>' % ('","'.join(self.versions_dict.keys()))) lang_prefix = web.prefix('/<any("%s"):lang>' % ('","'.join(self.langs_dict.keys()))) # return version_prefix | set_models | \ return super(PublishStreamNoState, self).prefix_handler | version_prefix | lang_prefix | set_models
def test_match_fragment(self): app = web.prefix('/x') | web.cases( web.match('/', 'index', fragment='index'), web.match('/', 'cyrillic', fragment=u'я'), web.match('/', 'page', fragment='page<int:page>'), web.prefix('/z', name="z") | web.cases( web.match('', name="", fragment="z") ) ) r = web.Reverse.from_handler(app) self.assertEqual(r.index.as_url, '/x/#index') self.assertEqual(r.cyrillic.as_url, '/x/#%D1%8F') self.assertEqual(r.page(page=1).as_url, '/x/#page1') self.assertEqual(r.z.as_url, '/x/z#z')
def test_prefix_ns_shortcut(self): view = lambda e, d: None chain = web.prefix('prefix', name='namespace') | view assert isinstance(chain.next_handler, web.namespace) self.assertEqual(chain.next_handler.namespace, 'namespace') self.assertEqual(chain.next_handler.next_handler, view)
def test_multiple_params_with_params_in_endpoints(self): app = ( web.prefix("/persons/<int:person_id>") | web.namespace("persons") | web.cases( web.match("/index/<page>", ""), web.prefix("/news") | web.namespace("news") | web.cases(web.match("/index/<news_page>", ""), web.match("/<int:news_id>", "item")), ) ) r = web.Reverse.from_handler(app) self.assertEqual(r.persons(person_id=1, page=2).as_url, "/persons/1/index/2") self.assertEqual(r.build_url("persons", person_id=1, page=2), "/persons/1/index/2") self.assertRaises(UrlBuildingError, lambda: r.persons(person_id=1).as_url) self.assertRaises(UrlBuildingError, lambda: r.persons(person_id=1).news.as_url)
def test_match_empty_pattern(self): '''Test if match() works proper with empty patterns''' r = Response() app = web.prefix('/') | web.match('', 'index') | (lambda e, d: r) self.assertEqual(web.ask(app, '/'), r)
def test_prefix_leaf(self): '''Simple prefix''' def handler(env, data): self.assertEqual(env._route_state.path, '/item') return Response() app = web.cases( web.match('/', 'index'), web.prefix('/docs') | web.cases( web.match('/', 'docs') | handler, web.match('/item', 'doc') | handler, web.prefix('/tags') | web.cases( web.match('/', 'tags') | handler, web.match('/tag', 'tag') | handler))) self.assertEqual(web.ask(app, '/docs/item').status_int, 200)
def test_match_empty_pattern(self): '''Test if match() works proper with empty patterns''' r = Response() app = web.prefix('/') | web.match('', 'index') | (lambda e,d: r) self.assertEqual(web.ask(app, '/'), r)
def test_prefix_with_zeros_in_int(self): '''Simple prefix''' from iktomi.web.url_converters import Converter, ConvertError def handler(env, data): return Response() class ZeroInt(Converter): def to_python(self, value, env=None): try: value = int(value) except ValueError: raise ConvertError(self.name, value) else: return value def to_url(self, value): return str(value) app = web.cases( web.prefix('/section/<int:section_id>', convs={'int': ZeroInt}) | web.match('/item', 'doc') | handler) #self.assertEqual(web.ask(app, '/section/1').status_int, 200) self.assertEqual(web.ask(app, '/section/1/item').status_int, 200) self.assertEqual(web.ask(app, '/section/001/item').status_int, 200)
def test_unicode(self): 'Reverse with unicode' # various combinations of url parts containing unicode chain = web.subdomain(u'п') | web.cases( web.prefix(u'/з') | web.match('/', 'unicode1'), web.prefix(u'/з') | web.match('/<string:slug>', 'unicode2'), web.match(u'/д/<string:slug>', 'unicode3'), #regression web.match(u'/<string:slug1>/<string:slug2>', 'unicode4'), #regression ) r = web.Reverse.from_handler(chain) self.assertEqual(r.unicode1.as_url, 'http://xn--o1a/%D0%B7/') self.assertEqual(str(r.unicode1), 'http://xn--o1a/%D0%B7/') self.assertEqual(r.unicode2(slug=u'ю').as_url, 'http://xn--o1a/%D0%B7/%D1%8E') self.assertEqual(r.unicode3(slug=u'ю').as_url, 'http://xn--o1a/%D0%B4/%D1%8E') self.assertEqual(r.unicode4(slug1=u'д', slug2=u'ю').as_url, 'http://xn--o1a/%D0%B4/%D1%8E')
def test_unicode(self): "Reverse with unicode" # various combinations of url parts containing unicode chain = web.subdomain(u"п") | web.cases( web.prefix(u"/з") | web.match("/", "unicode1"), web.prefix(u"/з") | web.match("/<string:slug>", "unicode2"), web.match(u"/д/<string:slug>", "unicode3"), # regression web.match(u"/<string:slug1>/<string:slug2>", "unicode4"), # regression ) r = web.Reverse.from_handler(chain) self.assertEqual(r.unicode1.as_url, "http://xn--o1a/%D0%B7/") self.assertEqual(str(r.unicode1), "http://xn--o1a/%D0%B7/") self.assertEqual(r.unicode2(slug=u"ю").as_url, "http://xn--o1a/%D0%B7/%D1%8E") self.assertEqual(r.unicode3(slug=u"ю").as_url, "http://xn--o1a/%D0%B4/%D1%8E") self.assertEqual(r.unicode4(slug1=u"д", slug2=u"ю").as_url, "http://xn--o1a/%D0%B4/%D1%8E")
def test_prefix_and_cases(self): "Locations of web.cases with prefix" chain = web.prefix("/news") | web.cases(web.match("/", "index"), web.match("/docs", "docs")) for k in ("index", "docs"): self.assert_(web.locations(chain).keys(), [k]) self.assert_(web.locations(chain)[k][0].builders) self.assertEqual(len(web.locations(chain)[k][0].builders), 2)
def prefix_handler(self): @web.request_filter def set_models(env, data, nxt): #assert data.version in self.versions_dict.keys() env.models = getattr(env.models, data.version) env.models = getattr(env.models, data.lang) env.version = data.version env.lang = data.lang return nxt(env, data) version_prefix = web.prefix('/<any("%s"):version>' % \ ('","'.join(self.versions_dict.keys()))) lang_prefix = web.prefix('/<any("%s"):lang>' % \ ('","'.join(self.langs_dict.keys()))) #return version_prefix | set_models | \ return super(PublishStreamNoState, self).prefix_handler |\ version_prefix | lang_prefix | set_models
def app(self): prefix = web.prefix('/<noneint:item>/'+self.action+'/<field_name>', name=self.action, convs={'noneint': NoneIntConv}) prepare = PrepareItemHandler(self) return prefix | web.cases( web.match() | prepare | self, )
def test_function(self): 'Reverse working with chained functions' app = web.cases( web.match('/', 'index') | (lambda e, d: None), web.prefix('/xx') | (lambda e, d: None), (lambda e, d: None), ) self.assertEqual(location_keys(app), ['index'])
def test_nested_cases_with_prefixes(self): 'Reverse with nested web.cases with web.prefixes' chain = web.cases( web.match('/', 'index'), web.prefix('/docs') | web.cases( web.match('/<int:id>', 'doc'), web.match('/list', 'docs')), web.prefix('/news') | web.cases( web.match('/<int:id>', 'news'), web.match('/list', 'newslist'))) r = web.Reverse.from_handler(chain) self.assertEqual(r.index.as_url, '/') self.assertEqual(r.docs.as_url, '/docs/list') self.assertEqual(r.newslist.as_url, '/news/list') self.assertEqual(r.doc(id=1).as_url, '/docs/1') self.assertEqual(r.news(id=1).as_url, '/news/1')
def test_multiple_params_with_params_in_endpoints(self): app = web.prefix('/persons/<int:person_id>') | web.namespace('persons') |\ web.cases( web.match('/index/<page>', ''), web.prefix('/news') | web.namespace('news') | web.cases( web.match('/index/<news_page>', ''), web.match('/<int:news_id>', 'item') ) ) r = web.Reverse.from_handler(app) self.assertEqual(r.persons(person_id=1, page=2).as_url, '/persons/1/index/2') self.assertEqual(r.build_url('persons', person_id=1, page=2), '/persons/1/index/2') self.assertRaises(UrlBuildingError, lambda: r.persons(person_id=1).as_url) self.assertRaises(UrlBuildingError, lambda: r.persons(person_id=1).news.as_url)
def test_prefix_state(self): '''Prefix state correctness''' def handler(env, data): return Response() app = web.cases( web.match('/', 'index'), web.prefix('/docs') | web.namespace('doc') | web.cases( web.match('/item', '') | handler, web.prefix('/list') | web.cases(web.match('/item', 'list') | handler), web.match('/other-thing', 'something') | handler), web.match('/something', 'something') | handler) self.assertEqual(web.ask(app, '/docs/something'), None) self.assertEqual(web.ask(app, '/docs/list/something'), None) self.assertEqual(web.ask(app, '/docs/list/other-thing'), None)
def app(self): prefix = web.prefix('/<noneint:item>/' + self.action + '/<field_name>', name=self.action, convs={'noneint': NoneIntConv}) prepare = PrepareItemHandler(self) return prefix | web.cases( web.match() | prepare | self, web.match('/crop', 'crop') | prepare | self.crop, )
def test_prefix_and_cases(self): 'Locations of web.cases with prefix' chain = web.prefix('/news') | web.cases( web.match('/', 'index'), web.match('/docs', 'docs')) for k in ('index', 'docs'): self.assert_(location_keys(chain), [k]) self.assert_(locations(chain)[k][0].builders) self.assertEqual(len(locations(chain)[k][0].builders), 2)
def test_prefix_leaf(self): """Simple prefix""" def handler(env, data): self.assertEqual(env._route_state.path, "/item") return Response() app = web.cases( web.match("/", "index"), web.prefix("/docs") | web.cases( web.match("/", "docs") | handler, web.match("/item", "doc") | handler, web.prefix("/tags") | web.cases(web.match("/", "tags") | handler, web.match("/tag", "tag") | handler), ), ) self.assertEqual(web.ask(app, "/docs/item").status_int, 200)
def test_double_call(self): app = web.prefix('/news', name='news') | web.cases( web.match('/<sort>'), web.match('/<sort>/page/<int:page>', name='page'), web.match('/feed', name='feed'), ) r = web.Reverse.from_handler(app) self.assertRaises(UrlBuildingError, lambda: r.news(sort='desc')())
def test_subreverse(self): chain = web.cases( web.prefix('/docs', name='docs') | web.cases( web.match('/<int:id>', 'doc'), web.match('/list', 'docs'))) r = web.Reverse.from_handler(chain) self.assertEqual(r.build_subreverse('docs.doc', id=1).as_url, '/docs/1') self.assertEqual(r.build_subreverse('docs').doc(id=1).as_url, '/docs/1')
def prefix_handler(self): """ Handler match stream path, setup stream namespace and env""" @web.request_filter def set_stream_handler(env, data, nxt): env.stream = self return nxt(env, data) part = self.module_name.rsplit('.', 1)[-1] return web.prefix('/' + part, name=part) | \ set_stream_handler
def prefix_handler(self): @web.request_filter def set_models(env, data, nxt): env.models = getattr(env.models, data.lang) env.lang = data.lang return nxt(env, data) lang_prefix = web.prefix('/<any("%s"):lang>' % \ ('","'.join(self.langs_dict.keys()))) return Stream.prefix_handler.fget(self) | lang_prefix | set_models
def h_section(self, section=None): parent_id = section and section.id or None subsections = self.get_sections(parent_id=parent_id) handlers = [] for subsection in subsections: resource = self.resources.get_resource(subsection.type) handler = resource.handler(self, subsection) handler = prefix('/' + (subsection.slug or ''), name=subsection.slug) | handler handlers.append(handler) return cases(*handlers)
def test_repr(self): # for coverage '%r' % web.WebHandler() '%r' % web.cases() '%r' % web.request_filter(lambda e, d, n: None) '%r' % web.match('/', 'index') '%r' % web.method('GET') '%r' % web.static_files('/prefix') '%r' % web.prefix('/prefix') '%r' % web.subdomain('name') '%r' % web.namespace('name')
def test_prefix_root(self): '''Prefix root''' def handler(env, data): self.assertEqual(env._route_state.path, '/') return Response() app = web.cases( web.match('/', 'index') | handler, web.prefix('/docs') | web.cases( web.match('/', 'docs') | handler, web.match('/item', 'doc') | handler, web.prefix('/tags') | web.cases( web.match('/', 'tags') | handler, web.match('/tag', 'tag') | handler))) self.assertEqual(web.ask(app, '/docs'), None) self.assertEqual(web.ask(app, '/docs/').status_int, 200) self.assertEqual(web.ask(app, '/docs/tags'), None) self.assertEqual(web.ask(app, '/docs/tags/').status_int, 200) self.assertEqual(web.ask(app, '/docs/tags/asdasd'), None)
def create_handler(app): h_caching = Caching(app.cache, duration=app.cfg.CACHE_TIME) return cases( static_files(app.cfg.STATIC_DIR, app.cfg.STATIC_URL), static_files(app.cfg.FRONT_MEDIA_DIR, app.cfg.MEDIA_URL), h_caching | cache(enable=app.cfg.CACHE_ENABLED) | cases( prefix('/en') | app.i18n.handler('en') | h_index, app.i18n.handler('ru') | h_index, ), HTTPNotFound, )
def test_current_location(self): def test_ns(env, data): return env.current_location app = web.cases( web.match('/', 'm1'), web.prefix('/ns', name="ns1.ns2") | web.cases( web.match(''), web.match('/m2', 'm2'), )) | test_ns self.assertEqual(web.ask(app, '/'), 'm1') self.assertEqual(web.ask(app, '/ns'), 'ns1.ns2') self.assertEqual(web.ask(app, '/ns/m2'), 'ns1.ns2.m2')
def _create_subapp(self, ns=''): prefix = ns and (ns + '.') or '' handlers_by_namespace = self._handlers_by_namespace() children = filter( lambda x: x and x.startswith(prefix) and not '.' in x[len( prefix):], handlers_by_namespace) child_apps = [web.prefix('/' + x.rsplit('.', 1)[-1]) | \ web.namespace(x.rsplit('.', 1)[-1]) | self._create_subapp(x) for x in children] return web.cases(*(child_apps + handlers_by_namespace[ns]))
def test_sane_exceptions(self): # XXX what is this? 0_o 'Not yet completed test of sane exceptions' @web.request_filter def get_items(env, data, nxt): return nxt(env, data) def raise_exc(env, data): raise Exception('somewhere deep inside') app = web.prefix('/prefix') | web.match('/', '') | get_items | raise_exc self.assertRaises(Exception, lambda: web.ask(app, '/prefix/'))
def test_unicode(self): '''Routing rules with unicode''' # XXX move to urltemplate and reverse tests? app = web.cases( web.prefix(u'/հայերեն') | web.cases( web.match(u'/%', 'percent') | (lambda e, d: Response()))) encoded = '/%D5%B0%D5%A1%D5%B5%D5%A5%D6%80%D5%A5%D5%B6/%25' self.assertEqual(web.Reverse.from_handler(app).percent.as_url, encoded) self.assertEqual( web.Reverse.from_handler(app).percent.as_url.get_readable(), u'/հայերեն/%25') self.assertNotEqual(web.ask(app, encoded), None) # ??? # rctx have prefixes, so we need new one self.assertEqual(web.ask(app, encoded).status_int, 200)
def create_handler(app): h_caching = Caching(app.cache, duration=app.cfg.CACHE_TIME) h_sections_ru = app.sections['ru'].handler() h_sections_en = app.sections['en'].handler() return cases( static_files(app.cfg.STATIC_DIR, app.cfg.STATIC_URL), static_files(app.cfg.FRONT_MEDIA_DIR, app.cfg.MEDIA_URL), h_caching | cache(enable=app.cfg.CACHE_ENABLED) | cases( prefix('/en') | app.i18n.handler('en') | cases( match('/', name='index') | h_index, h_sections_en, ), app.i18n.handler('ru') | cases( match('/', name='index') | h_index, h_sections_ru, ), ), HTTPNotFound, )
def app_prefix(self): return web.prefix('/<idconv:item>', name='item', convs={'idconv': self.stream.id_none_converter})
def h_app(prefix, name, app): return web.prefix(prefix, name=name) | H_App(app)