Exemplo n.º 1
0
    def test_custom_filters(self):
        """Templates: jinja2 custom filters """
        from bottle import jinja2_template as template

        settings = dict(filters={"star": lambda var: touni("").join((touni("*"), var, touni("*")))})
        t = Jinja2Template("start {{var|star}} end", **settings)
        self.assertEqual("start *var* end", t.render(var="var"))
Exemplo n.º 2
0
 def test_non_string_header(self):
     response = BaseResponse()
     response['x-test'] = 5
     self.assertEqual('5', response['x-test'])
     response['x-test'] = None
     self.assertEqual('', response['x-test'])
     response['x-test'] = touni('瓶')
     self.assertEqual(tonat(touni('瓶')), response['x-test'])
Exemplo n.º 3
0
 def test_detect_pep263(self):
     ''' PEP263 strings in code-lines change the template encoding on the fly '''
     t = SimpleTemplate(touni('%#coding: iso8859_15\nöäü?@€').encode('utf8'))
     self.assertNotEqual(touni('öäü?@€'), t.render())
     self.assertEqual(t.encoding, 'iso8859_15')
     t = SimpleTemplate(touni('%#coding: iso8859_15\nöäü?@€').encode('iso8859_15'))
     self.assertEqual(touni('öäü?@€'), t.render())
     self.assertEqual(t.encoding, 'iso8859_15')
     self.assertEqual(2, len(t.code.splitlines()))
Exemplo n.º 4
0
 def test_view_decorator_issue_407(self):
     @view('stpl_no_vars')
     def test():
         pass
     self.assertEqual(touni('hihi'), test())
     @view('aaa {{x}}', x='bbb')
     def test2():
         pass
     self.assertEqual(touni('aaa bbb'), test2())
Exemplo n.º 5
0
def executebackend(ws, query):
    sqls = [x[:-1].strip() for x in re.findall(
        r"(?:[^';]|'(?:\\'|[^'])*')+[^;]*;",
        bottle.touni(query) + ';')]

    if len(sqls) > 1 and [1 for x in sqls if x[:6].upper() == 'SELECT']:
        ws.send(json.dumps(
            {'error': 'SELECT statements must be executed alone'}))
        return

    try:
        with _connect() as conn, closing(conn.cursor()) as cursor:
            for sql in sqls:
                cursor._executebackend(sql)

            if cursor.description:
                ws.send(json.dumps(
                    {'a': 'd', 'c': [x[0] for x in cursor.description]}))
                for row in cursor:
                    wrapped_row = [_wrap_value(x) for x in row]
                    ws.send(json.dumps({'a': 'p', 'r': wrapped_row}))
                ws.send(json.dumps({'a': 's'}))
                ws.send(json.dumps({'a': 't'}))
            else:
                ws.send(json.dumps({'error': None}))

    except (RuntimeError, psycopg2.Error) as e:
        ws.send(json.dumps({'error': unicode(e)}))
Exemplo n.º 6
0
 def test_multipart(self):
     """ Environ: POST (multipart files and multible values per key) """
     fields = [('field1','value1'), ('field2','value2'), ('field2','value3')]
     files = [('file1','filename1.txt','content1'), ('file2','filename2.py',touni('ä\nö\rü'))]
     e = tools.multipart_environ(fields=fields, files=files)
     request = BaseRequest(e)
     # File content
     self.assertTrue('file1' in request.POST)
     self.assertTrue('file1' in request.files)
     self.assertTrue('file1' not in request.forms)
     cmp = tob('content1') if sys.version_info >= (3,2,0) else 'content1'
     self.assertEqual(cmp, request.POST['file1'].file.read())
     # File name and meta data
     self.assertTrue('file2' in request.POST)
     self.assertTrue('file2' in request.files)
     self.assertTrue('file2' not in request.forms)
     self.assertEqual('filename2.py', request.POST['file2'].filename)
     # UTF-8 files
     x = request.POST['file2'].file.read()
     if (3,2,0) > sys.version_info >= (3,0,0):
         x = x.encode('ISO-8859-1')
     self.assertEqual(tob('ä\nö\rü'), x)
     # No file
     self.assertTrue('file3' not in request.POST)
     self.assertTrue('file3' not in request.files)
     self.assertTrue('file3' not in request.forms)
     # Field (single)
     self.assertEqual('value1', request.POST['field1'])
     self.assertTrue('field1' not in request.files)
     self.assertEqual('value1', request.forms['field1'])
     # Field (multi)
     self.assertEqual(2, len(request.POST.getall('field2')))
     self.assertEqual(['value2', 'value3'], request.POST.getall('field2'))
     self.assertEqual(['value2', 'value3'], request.forms.getall('field2'))
     self.assertTrue('field2' not in request.files)
Exemplo n.º 7
0
    def test_iterator_with_close(self):
        class MyIter(object):
            def __init__(self, data):
                self.data = data
                self.closed = False
            def close(self):    self.closed = True
            def __iter__(self): return iter(self.data)

        byte_iter = MyIter([tob('abc'), tob('def')])
        unicode_iter = MyIter([touni('abc'), touni('def')])

        for test_iter in (byte_iter, unicode_iter):
            @self.app.route('/')
            def test(): return test_iter
            self.assertInBody('abcdef')
            self.assertTrue(byte_iter.closed)
Exemplo n.º 8
0
def execute(ws, query):
    sqls = [x[:-1].strip() for x in re.findall(
        r"(?:[^';]|'(?:\\'|[^'])*')+[^;]*;",
        bottle.touni(query) + ';')]

    if len(sqls) > 1 and [1 for x in sqls if x[:6].upper() == 'SELECT']:
        ws.send(json.dumps(
            {'error': 'SELECT statements must be executed alone'}))
        return

    try:
        with _connect() as conn, closing(conn.cursor()) as cursor:
            def ws_send(action, row):
                if action == 'shift' or action == 'terminate':
                    ws.send(json.dumps({'a': action[0]}))
                else:  # populate, add, remove
                    wrapped_row = [_wrap_value(x) for x in row]
                    ws.send(json.dumps({'a': action[0], 'r': wrapped_row}))

            for sql in sqls:
                cursor.execute(sql, callback=ws_send)

            if cursor.description:
                session_id = _get_session()['_id']
                _cursors[session_id] = cursor
                ws.send(json.dumps(
                    {'a': 'd', 'c': [x[0] for x in cursor.description]}))
                cursor.fetchone()
                del _cursors[session_id]
            else:
                ws.send(json.dumps({'error': None}))

    # pylint: disable=W0703
    except (RuntimeError, deco.Error, psycopg2.Error, Exception) as e:
        ws.send(json.dumps({'error': unicode(e)}))
Exemplo n.º 9
0
 def test_custom_tests(self):
     """Templates: jinja2 custom tests """
     from bottle import jinja2_template as template
     TEMPL = touni("{% if var is even %}gerade{% else %}ungerade{% endif %}")
     settings = dict(tests={"even": lambda x: False if x % 2 else True})
     t = Jinja2Template(TEMPL, **settings)
     self.assertEqual("gerade", t.render(var=2))
     self.assertEqual("ungerade", t.render(var=1))
Exemplo n.º 10
0
 def assertRenders(self, source, result, syntax=None, *args, **vars):
     source = self.fix_ident(source)
     result = self.fix_ident(result)
     tpl = SimpleTemplate(source, syntax=syntax)
     try:
         tpl.co
         self.assertEqual(touni(result), tpl.render(*args, **vars))
     except SyntaxError:
         self.fail('Syntax error in template:\n%s\n\nTemplate code:\n##########\n%s\n##########' %
                  (traceback.format_exc(), tpl.code))
 def test_auth(self):
     user, pwd = 'marc', 'secret'
     basic = touni(base64.b64encode(tob('%s:%s' % (user, pwd))))
     r = BaseRequest({})
     self.assertEqual(r.auth, None)
     r.environ['HTTP_AUTHORIZATION'] = 'basic %s' % basic
     self.assertEqual(r.auth, (user, pwd))
     r.environ['REMOTE_USER'] = user
     self.assertEqual(r.auth, (user, pwd))
     del r.environ['HTTP_AUTHORIZATION']
     self.assertEqual(r.auth, (user, None))
Exemplo n.º 12
0
 def test_auth(self):
     user, pwd = "marc", "secret"
     basic = touni(base64.b64encode(tob("%s:%s" % (user, pwd))))
     r = BaseRequest({})
     self.assertEqual(r.auth, None)
     r.environ["HTTP_AUTHORIZATION"] = "basic %s" % basic
     self.assertEqual(r.auth, (user, pwd))
     r.environ["REMOTE_USER"] = user
     self.assertEqual(r.auth, (user, pwd))
     del r.environ["HTTP_AUTHORIZATION"]
     self.assertEqual(r.auth, (user, None))
 def test_get(self):
     """ Environ: GET data """
     qs = tonat(tob('a=a&a=1&b=b&c=c&cn=%e7%93%b6'), 'latin1')
     request = BaseRequest({'QUERY_STRING':qs})
     self.assertTrue('a' in request.query)
     self.assertTrue('b' in request.query)
     self.assertEqual(['a','1'], request.query.getall('a'))
     self.assertEqual(['b'], request.query.getall('b'))
     self.assertEqual('1', request.query['a'])
     self.assertEqual('b', request.query['b'])
     self.assertEqual(tonat(tob('瓶'), 'latin1'), request.query['cn'])
     self.assertEqual(touni('瓶'), request.query.cn)
Exemplo n.º 14
0
 def test_filename(self):
     self.assertFilename('with space', 'with-space')
     self.assertFilename('with more  \t\n\r space', 'with-more-space')
     self.assertFilename('with/path', 'path')
     self.assertFilename('../path', 'path')
     self.assertFilename('..\\path', 'path')
     self.assertFilename('..', 'empty')
     self.assertFilename('.name.', 'name')
     self.assertFilename('.name.cfg', 'name.cfg')
     self.assertFilename(' . na me . ', 'na-me')
     self.assertFilename('path/', 'empty')
     self.assertFilename(bottle.tob('ümläüts$'), 'umlauts')
     self.assertFilename(bottle.touni('ümläüts$'), 'umlauts')
     self.assertFilename('', 'empty')
     self.assertFilename('a'+'b'*1337+'c', 'a'+'b'*254)
Exemplo n.º 15
0
    def test_wsgi_header_values(self):
        def cmp(app, wire):
            rs = BaseResponse()
            rs.set_header('x-test', app)
            result = [v for (h, v) in rs.headerlist if h.lower()=='x-test'][0]
            self.assertEqual(wire, result)

        if bottle.py3k:
            cmp(1, tonat('1', 'latin1'))
            cmp('öäü', 'öäü'.encode('utf8').decode('latin1'))
            # Dropped byte header support in Python 3:
            #cmp(tob('äöü'), 'äöü'.encode('utf8').decode('latin1'))
        else:
            cmp(1, '1')
            cmp('öäü', 'öäü')
            cmp(touni('äöü'), 'äöü')
Exemplo n.º 16
0
def explain():
    sqls = [x[:-1].strip() for x in re.findall(
        r"(?:[^';]|'(?:\\'|[^'])*')+[^;]*;",
        bottle.touni(bottle.request.forms.get('query')) + ';')]

    if len(sqls) > 1:
        return {'error': 'only one SELECT statement can be explained'}
    elif len(sqls) == 0:
        return {'error': None, 'plan': None}

    try:
        with _connect() as conn, closing(conn.cursor()) as cursor:
            plan = cursor._explain(sqls[0], True)
        error = None
    except (RuntimeError, deco.Error, psycopg2.Error) as e:
        error = unicode(e)
        plan = None

    return {'error': error, 'plan': plan}
Exemplo n.º 17
0
    def test_unicode(self):
        self.app.route('/')(lambda: touni('äöüß'))
        self.assertBody(touni('äöüß').encode('utf8'))

        self.app.route('/')(lambda: [touni('äö'), touni('üß')])
        self.assertBody(touni('äöüß').encode('utf8'))

        @self.app.route('/')
        def test5():
            bottle.response.content_type='text/html; charset=iso-8859-15'
            return touni('äöüß')
        self.assertBody(touni('äöüß').encode('iso-8859-15'))

        @self.app.route('/')
        def test5():
            bottle.response.content_type='text/html'
            return touni('äöüß')
        self.assertBody(touni('äöüß').encode('utf8'))
 def test_post(self):
     """ Environ: POST data """
     sq = tob('a=a&a=1&b=b&c=&d&cn=%e7%93%b6')
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(sq)
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(sq))
     e['REQUEST_METHOD'] = "POST"
     request = BaseRequest(e)
     self.assertTrue('a' in request.POST)
     self.assertTrue('b' in request.POST)
     self.assertEqual(['a','1'], request.POST.getall('a'))
     self.assertEqual(['b'], request.POST.getall('b'))
     self.assertEqual('1', request.POST['a'])
     self.assertEqual('b', request.POST['b'])
     self.assertEqual('', request.POST['c'])
     self.assertEqual('', request.POST['d'])
     self.assertEqual(tonat(tob('瓶'), 'latin1'), request.POST['cn'])
     self.assertEqual(touni('瓶'), request.POST.cn)
Exemplo n.º 19
0
 def test_unicode(self):
     self.env['HTTP_TEST_HEADER'] = touni('foobar')
     self.assertEqual(self.headers['Test-Header'], 'foobar')
Exemplo n.º 20
0
 def test_unicode(self):
     self.assertRenders('start {{var}} end', 'start äöü end', var=touni('äöü'))
     self.assertRenders('start {{var}} end', 'start äöü end', var=tob('äöü'))
Exemplo n.º 21
0
 def assertRenders(self, tpl, to, *args, **vars):
     if isinstance(tpl, str):
         tpl = SimpleTemplate(tpl)
     self.assertEqual(touni(to), tpl.render(*args, **vars))
Exemplo n.º 22
0
 def test_ignore_late_pep263(self):
     ''' PEP263 strings must appear within the first two lines '''
     t = SimpleTemplate(touni('\n\n%#coding: iso8859_15\nöäü?@€').encode('utf8'))
     self.assertEqual(touni('\n\nöäü?@€'), t.render())
     self.assertEqual(t.encoding, 'utf8')
Exemplo n.º 23
0
 def test_global_config(self):
     SimpleTemplate.global_config('meh', 1)
     t = SimpleTemplate('anything')
     self.assertEqual(touni('anything'), t.render())
Exemplo n.º 24
0
 def setUp(self):
     self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
     self.key = tob('secret')
Exemplo n.º 25
0
 def test_unicode_code(self):
     """ Templates: utf8 code in file"""
     with chdir(__file__):
         t = SimpleTemplate(name='./views/stpl_unicode.tpl', lookup=['.'])
         self.assertRenders(t, 'start ñç äöü end\n', var=touni('äöü'))
Exemplo n.º 26
0
 def test5():
     bottle.response.content_type = 'text/html; charset=iso-8859-15'
     return touni('äöüß')
Exemplo n.º 27
0
 def test_attr_access(self):
     """ FomsDict.attribute returs string values as unicode. """
     d = FormsDict(py2=tob('瓶'), py3=tob('瓶').decode('latin1'))
     self.assertEqual(touni('瓶'), d.py2)
     self.assertEqual(touni('瓶'), d.py3)
Exemplo n.º 28
0
 def test_view_decorator(self):
     @view('start {{var}} end')
     def test():
         return dict(var='middle')
     self.assertEqual(touni('start middle end'), test())
Exemplo n.º 29
0
 def test_global_config(self):
     SimpleTemplate.global_config('meh', 1)
     t = SimpleTemplate('anything')
     self.assertEqual(touni('anything'), t.render())
Exemplo n.º 30
0
 def test_template_shortcut(self):
     result = template('start {{var}} end', var='middle')
     self.assertEqual(touni('start middle end'), result)
Exemplo n.º 31
0
 def test_ignore_late_pep263(self):
     ''' PEP263 strings must appear within the first two lines '''
     self.assertRaises(UnicodeError, lambda: SimpleTemplate(touni('\n\n%#coding: iso8859_15\nöäü?@€').encode('iso8859_15')).co)
     t = SimpleTemplate(touni('\n\n%#coding: iso8859_15\nöäü?@€').encode('utf8'))
     self.assertEqual(touni('\n\nöäü?@€'), t.render())
     self.assertEqual(t.encoding, 'utf8')
Exemplo n.º 32
0
 def test_ignore_pep263_in_textline(self):
     ''' PEP263 strings in text-lines have no effect '''
     self.assertRaises(UnicodeError, lambda: SimpleTemplate(touni('#coding: iso8859_15\nöäü?@€').encode('iso8859_15')).co)
     t = SimpleTemplate(touni('#coding: iso8859_15\nöäü?@€').encode('utf8'))
     self.assertEqual(touni('#coding: iso8859_15\nöäü?@€'), t.render())
     self.assertEqual(t.encoding, 'utf8')
Exemplo n.º 33
0
 def setUp(self):
     super(TestSignedCookiesWithPickle, self).setUp()
     self.data = dict(a=5,
                      b=touni('υηι¢σ∂є'),
                      c=[1, 2, 3, 4, tob('bytestring')])
Exemplo n.º 34
0
 def test():
     raise Exception(touni('Unicode äöüß message.'))
Exemplo n.º 35
0
 def setUp(self):
     self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
     self.secret = tob('secret')
     bottle.app.push()
     bottle.response.bind()
 def test_unicode(self):
     self.env['HTTP_TEST_HEADER'] = touni('foobar')
     self.assertEqual(self.headers['Test-Header'], 'foobar')
Exemplo n.º 37
0
 def test_attr_missing(self):
     """ FomsDict.attribute returs u'' on missing keys. """
     d = FormsDict()
     self.assertEqual(touni(''), d.missing)
Exemplo n.º 38
0
 def test_unicode(self):
     self.assertRenders('start {{var}} end', 'start äöü end', var=touni('äöü'))
     self.assertRenders('start {{var}} end', 'start äöü end', var=tob('äöü'))
Exemplo n.º 39
0
 def test_ignore_pep263_in_textline(self):
     ''' PEP263 strings in text-lines have no effect '''
     t = SimpleTemplate(touni('#coding: iso8859_15\nöäü?@€').encode('utf8'))
     self.assertEqual(touni('#coding: iso8859_15\nöäü?@€'), t.render())
     self.assertEqual(t.encoding, 'utf8')
Exemplo n.º 40
0
 def test_view_decorator(self):
     @mako_view('start ${var} end')
     def test():
         return dict(var='middle')
     self.assertEqual(touni('start middle end'), test())
Exemplo n.º 41
0
 def assertRenders(self, tpl, to, *args, **vars):
     if isinstance(tpl, str):
         tpl = SimpleTemplate(
             tpl, lookup=[os.path.join(os.path.dirname(__file__), 'views')])
     self.assertEqual(touni(to), tpl.render(*args, **vars))
Exemplo n.º 42
0
 def setUp(self):
     self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
     self.key = tob('secret')
Exemplo n.º 43
0
 def test(): raise Exception(touni('Unicode äöüß message.'))
 self.assertStatus(500, '/')
Exemplo n.º 44
0
 def test():
     yield touni('äöüß')
Exemplo n.º 45
0
 def test_unicode_code(self):
     """ Templates: utf8 code in file"""
     t = SimpleTemplate(name='./views/stpl_unicode.tpl')
     self.assertRenders(t, 'start ñç äöü end\n', var=touni('äöü'))
Exemplo n.º 46
0
    def test_unicode_generator_callback(self):
        @self.app.route('/')
        def test():
            yield touni('äöüß')

        self.assertBody(touni('äöüß').encode('utf8'))
Exemplo n.º 47
0
 def test_template_shortcut(self):
     result = mako_template('start ${var} end', var='middle')
     self.assertEqual(touni('start middle end'), result)
Exemplo n.º 48
0
 def test5():
     bottle.response.content_type = 'text/html'
     return touni('äöüß')
Exemplo n.º 49
0
 def assertRenders(self, tpl, to, *args, **vars):
     if isinstance(tpl, str):
         tpl = SimpleTemplate(tpl)
     self.assertEqual(touni(to), tpl.render(*args, **vars))
Exemplo n.º 50
0
 def setUp(self):
     self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
     self.secret = tob('secret')
     bottle.app.push()
     bottle.response.bind()
Exemplo n.º 51
0
 def test_attr_unicode_error(self):
     """ FomsDict.attribute returs u'' on UnicodeError. """
     d = FormsDict(latin=touni('öäüß').encode('latin1'))
     self.assertEqual(touni(''), d.latin)
     d.input_encoding = 'latin1'
     self.assertEqual(touni('öäüß'), d.latin)
Exemplo n.º 52
0
 def test_unicode_code(self):
     """ Templates: utf8 code in file"""
     t = SimpleTemplate(name='./views/stpl_unicode.tpl')
     self.assertRenders(t, 'start ñç äöü end\n', var=touni('äöü'))
Exemplo n.º 53
0
 def test(): raise Exception(touni('Unicode äöüß message.'))
 self.assertStatus(500, '/')
Exemplo n.º 54
0
 def setUp(self):
     self.data = touni('υηι¢σ∂є')
     self.secret = tob('secret')
     bottle.app.push()
     bottle.response.bind()