'Test route finding'

def test_route_finding(self):

    from calibre.srv.routes import Router, endpoint, HTTPNotFound
    router = Router()
    def find(path):
        path = filter(None, path.split(u'/'))
        (ep, args) = router.find_route(path)
        args = list(args)
        return (ep, args)
    @endpoint(u'/')
    def root(ctx, data):
        pass
    @endpoint(u'/defval/{a=1}')
    def defval(ctx, data, a):
        pass
    @endpoint(u'/varpath/{a}/{b}')
    def varpath(ctx, data, a, b):
        pass
    @endpoint(u'/soak/{+rest}')
    def soak(ctx, dest, rest):
        pass
    @endpoint(u'/soak_opt/{+rest="xxx"}')
    def soak_opt(ctx, dest, rest):
        pass
    @endpoint(u'/needs    quoting/{x}')
    def quoting(ctx, dest, x):
        pass
    @endpoint(u'/get/{a}/{b=None}')
    def get(ctx, dest, a, b):
        pass
    for x in locals().itervalues():
        if getattr(x, u'is_endpoint', False):
            router.add(x)
    router.finalize()
    (ep, args) = find(u'/')
    (self.ae(ep, root), self.assertFalse(args))
    (ep, args) = find(u'/defval')
    (self.ae(ep, defval), self.ae(args, [1]))
    (ep, args) = find(u'/defval/2')
    (self.ae(ep, defval), self.ae(args, [2]))
    self.assertRaises(HTTPNotFound, find, u'/defval/a')
    self.assertRaises(HTTPNotFound, find, u'/varpath')
    self.assertRaises(HTTPNotFound, find, u'/varpath/x')
    self.assertRaises(HTTPNotFound, find, u'/varpath/x/y/z')
    self.assertRaises(HTTPNotFound, find, u'/soak')
    (ep, args) = find(u'/varpath/x/y')
    (self.ae(ep, varpath), self.ae(args, [u'x', u'y']))
    (ep, args) = find(u'/soak/x')
    (self.ae(ep, soak), self.ae(args, [u'x']))
    self.ae(router.routes[u'/soak'].soak_up_extra, u'rest')
    (ep, args) = find(u'/soak/x/y/z')
    (self.ae(ep, soak), self.ae(args, [u'x/y/z']))
    (ep, args) = find(u'/soak_opt')
    (self.ae(ep, soak_opt), self.ae(args, [u'xxx']))
    (ep, args) = find(u'/soak_opt/a/b')
    (self.ae(ep, soak_opt), self.ae(args, [u'a/b']))
    self.ae(router.url_for(u'/needs    quoting', x=u'a/b    c'), u'/needs    quoting/a%2Fb%20c')
    self.ae(router.url_for(None), u'/')
    self.ae(router.url_for(u'/get', a=u'1', b=u'xxx'), u'/get/1/xxx')
