Ejemplo n.º 1
0
    def process_response(self, response):
        # If the body is HTML, then we add the toolbar to the response.
        request = self.request

        if isinstance(response, WSGIHTTPException):
            # the body of a WSGIHTTPException needs to be "prepared"
            response.prepare(request.environ)

        for panel in self.panels:
            panel.process_response(response)

        if response.content_type in self.html_types:
            static_path = request.static_url(STATIC_PATH)
            root_path = request.route_url(ROOT_ROUTE_NAME)
            button_style = get_setting(request.registry.settings,
                                       'button_style', '')
            vars = {
                'panels': self.panels,
                'static_path': static_path,
                'root_path': root_path,
                'button_style': button_style
            }
            toolbar_html = render(
                'pyramid_debugtoolbar:templates/toolbar.mako',
                vars,
                request=request)
            response_html = response.body
            toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
            body = replace_insensitive(response_html, bytes_('</body>'),
                                       toolbar_html + bytes_('</body>'))
            response.app_iter = [body]
Ejemplo n.º 2
0
    def process_response(self, response):
        # If the body is HTML, then we add the toolbar to the response.
        request = self.request

        if isinstance(response, WSGIHTTPException):
            # the body of a WSGIHTTPException needs to be "prepared"
            response.prepare(request.environ)

        for panel in self.panels:
            panel.process_response(response)

        if response.content_type in self.html_types:
            static_path = request.static_url(STATIC_PATH)
            root_path = request.route_url(ROOT_ROUTE_NAME)
            button_style = get_setting(request.registry.settings,
                    'button_style', '')
            vars = {'panels': self.panels, 'static_path': static_path,
                    'root_path': root_path, 'button_style': button_style}
            toolbar_html = render(
                    'pyramid_debugtoolbar:templates/toolbar.dbtmako',
                    vars, request=request)
            response_html = response.body
            toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
            body = replace_insensitive(
                response_html, bytes_('</body>'),
                toolbar_html + bytes_('</body>')
                )
            response.app_iter = [body]
            response.content_length = len(body)
Ejemplo n.º 3
0
 def test_execute(self):
     request = self._makeRequest()
     request.params['cmd'] = 'doit'
     view = self._makeOne(request)
     response = view.execute()
     self.assertEqual(response.body, bytes_('evaled'))
     self.assertEqual(response.content_type, 'text/html')
    def sql_select(self):
        stmt = self.request.params['sql']
        params = self.request.params['params']
        engine_id = self.request.params['engine_id']

        # Validate hash
        hash = hashlib.sha1(
            bytes_(self.request.exc_history.token + stmt +
                   params)).hexdigest()
        if hash != self.request.params['hash']:
            raise HTTPBadRequest('Bad token in request')

        # Make sure it is a select statement
        if not stmt.lower().strip().startswith('select'):
            raise HTTPBadRequest('Not a SELECT SQL statement')

        if not engine_id:
            raise HTTPBadRequest('No valid database engine')

        engine = getattr(self.request.registry, 'pdtb_sqla_engines')\
                      [int(engine_id)]()
        params = json.loads(params)
        result = engine.execute(stmt, params)

        return {
            'result': result.fetchall(),
            'headers': result.keys(),
            'sql': format_sql(stmt),
            'duration': float(self.request.params['duration']),
        }
Ejemplo n.º 5
0
    def process_response(self, response):
        data = []
        for index, query in enumerate(self.queries):
            stmt = query['statement']

            is_select = stmt.strip().lower().startswith('select')
            params = ''
            try:
                params = url_quote(json.dumps(query['parameters']))
            except TypeError:
                pass  # object not JSON serializable
            except UnicodeDecodeError:
                pass  # parameters contain non-utf8 (probably binary) data

            need = self.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(stmt),
                'raw_sql': stmt,
                'hash': hash,
                'parameters': query['parameters'],
                'params': params,
                'is_select': is_select,
                'context': query['context'],
                'query_index': index,
            })

        self.data = {
            'queries': data,
            'text': text,
        }
Ejemplo n.º 6
0
    def sql_select(self):
        stmt = self.request.params["sql"]
        params = self.request.params["params"]
        engine_id = self.request.params["engine_id"]

        # Validate hash
        hash = hashlib.sha1(bytes_(self.request.exc_history.token + stmt + params)).hexdigest()
        if hash != self.request.params["hash"]:
            raise HTTPBadRequest("Bad token in request")

        # Make sure it is a select statement
        if not stmt.lower().strip().startswith("select"):
            raise HTTPBadRequest("Not a SELECT SQL statement")

        if not engine_id:
            raise HTTPBadRequest("No valid database engine")

        engine = getattr(self.request.registry, "pdtb_sqla_engines")[int(engine_id)]()
        params = json.loads(params)
        result = engine.execute(stmt, params)

        return {
            "result": result.fetchall(),
            "headers": result.keys(),
            "sql": format_sql(stmt),
            "duration": float(self.request.params["duration"]),
        }
Ejemplo n.º 7
0
    def process_response(self, response):
        data = []
        for query in self.queries:
            stmt = query['statement']

            is_select = stmt.strip().lower().startswith('select')
            params = ''
            try:
                params = url_quote(json.dumps(query['parameters']))
            except TypeError:
                pass # object not JSON serializable
            except UnicodeDecodeError:
                pass # parameters contain non-utf8 (probably binary) data

            need = self.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(stmt),
                'raw_sql': stmt,
                'hash': hash,
                'parameters': query['parameters'],
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        self.data = {
            'queries':data,
            'text':text,
            }
Ejemplo n.º 8
0
 def test_execute(self):
     request = self._makeRequest()
     request.params['cmd'] = 'doit'
     view = self._makeOne(request)
     response = view.execute()
     self.assertEqual(response.body, bytes_('evaled'))
     self.assertEqual(response.content_type, 'text/html')
 def test_source(self):
     request = self._makeRequest()
     request.params['frm'] = '0'
     view = self._makeOne(request)
     response = view.source()
     self.assertEqual(response.body, bytes_('source'))
     self.assertEqual(response.content_type, 'text/html')
Ejemplo n.º 10
0
    def sql_select(self):
        stmt = self.request.params['sql']
        params = self.request.params['params']
        engine_id = self.request.params['engine_id']

        # Validate hash
        hash = hashlib.sha1(
            bytes_(self.request.exc_history.token + stmt + params)).hexdigest()
        if hash != self.request.params['hash']:
            raise HTTPBadRequest('Bad token in request')
 
        # Make sure it is a select statement
        if not stmt.lower().strip().startswith('select'):
            raise HTTPBadRequest('Not a SELECT SQL statement')

        if not engine_id:
            raise HTTPBadRequest('No valid database engine')

        engine = getattr(self.request.registry, 'pdtb_sqla_engines')\
                      [int(engine_id)]()
        params = json.loads(params)
        result = engine.execute(stmt, params)

        return {
            'result': result.fetchall(),
            'headers': result.keys(),
            'sql': format_sql(stmt),
            'duration': float(self.request.params['duration']),
        }
Ejemplo n.º 11
0
 def test_source(self):
     request = self._makeRequest()
     request.params["frm"] = "0"
     view = self._makeOne(request)
     response = view.source()
     self.assertEqual(response.body, bytes_("source"))
     self.assertEqual(response.content_type, "text/html")
Ejemplo n.º 12
0
 def test_source(self):
     request = self._makeRequest()
     request.params['frm'] = '0'
     view = self._makeOne(request)
     response = view.source()
     self.assertEqual(response.body, bytes_('source'))
     self.assertEqual(response.content_type, 'text/html')
Ejemplo n.º 13
0
 def test_execute(self):
     request = self._makeRequest()
     request.params["frm"] = "0"
     request.params["cmd"] = "doit"
     view = self._makeOne(request)
     response = view.execute()
     self.assertEqual(response.body, bytes_("evaled"))
     self.assertEqual(response.content_type, "text/html")
Ejemplo n.º 14
0
 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings, 'button_style',
                                '')
     css_path = request.static_url(STATIC_PATH + 'css/toolbar_button.css')
     toolbar_html = toolbar_html_template % {
         'button_style': button_style,
         'css_path': css_path,
         'toolbar_url': toolbar_url
     }
     toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
     response.body = replace_insensitive(response_html, bytes_('</body>'),
                                         toolbar_html + bytes_('</body>'))
Ejemplo n.º 15
0
 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings,
             'button_style', '')
     css_path = request.static_url(STATIC_PATH + 'css/toolbar_button.css')
     toolbar_html = toolbar_html_template % {
         'button_style': button_style,
         'css_path': css_path,
         'toolbar_url': toolbar_url}
     toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
     response.body = replace_insensitive(
         response_html, bytes_('</body>'),
         toolbar_html + bytes_('</body>')
         )
Ejemplo n.º 16
0
    def validate(self):
        stmt = self.request.params['sql']
        params = self.request.params['params']

        # Validate hash
        need = self.request.exc_history.token + stmt + url_quote(params)

        hash = hashlib.sha1(bytes_(need)).hexdigest()
        if hash != self.request.params['hash']:
            raise HTTPBadRequest('Bad token in request')
        return stmt, params
Ejemplo n.º 17
0
    def validate(self):
        stmt = self.request.params['sql']
        params = self.request.params['params']

        # Validate hash
        need = self.token + stmt + url_quote(params)

        hash = hashlib.sha1(bytes_(need)).hexdigest()
        if hash != self.request.params['hash']:
            raise HTTPBadRequest('Bad token in request')
        return stmt, params
Ejemplo n.º 18
0
    def validate(self):
        stmt = self.request.params["sql"]
        params = self.request.params["params"]

        # Validate hash
        need = self.request.exc_history.token + stmt + url_quote(params)

        hash = hashlib.sha1(bytes_(need)).hexdigest()
        if hash != self.request.params["hash"]:
            raise HTTPBadRequest("Bad token in request")
        return stmt, params
Ejemplo n.º 19
0
 def test_inject_html(self):
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static', STATIC_PATH)
     self.config.add_route('debugtoolbar', '/_debugtoolbar/*subpath')
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.pdtb_id = 'abc'
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel], [DummyPanel], [])
     toolbar.inject(request, response)
     self.assertTrue(bytes_('div id="pDebug"') in response.app_iter[0])
     self.assertEqual(response.content_length, len(response.app_iter[0]))
Ejemplo n.º 20
0
 def test_process_response_html(self):
     from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static', STATIC_PATH)
     self.config.add_route(ROOT_ROUTE_NAME, '/_debugtoolbar')
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel])
     toolbar.process_response(response)
     self.assertTrue(response.processed)
     self.assertTrue(bytes_('div id="pDebug"') in response.app_iter[0])
 def test_inject_html(self):
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static', STATIC_PATH)
     self.config.add_route('debugtoolbar', '/_debugtoolbar/*subpath')
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.pdtb_id = 'abc'
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel], [DummyPanel], [])
     toolbar.inject(request, response)
     self.assertTrue(bytes_('div id="pDebug"') in response.app_iter[0])
     self.assertEqual(response.content_length, len(response.app_iter[0]))
Ejemplo n.º 22
0
 def test_process_response_html(self):
     from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static',
                                 STATIC_PATH)
     self.config.add_route(ROOT_ROUTE_NAME, '/_debugtoolbar')
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel])
     toolbar.process_response(response)
     self.assertTrue(response.processed)
     self.assertTrue(bytes_('div id="pDebug"') in response.app_iter[0])
Ejemplo n.º 23
0
 def test_passing_of_button_style(self):
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static', STATIC_PATH)
     self.config.add_route('debugtoolbar', '/_debugtoolbar/*subpath')
     self.config.registry.settings['debugtoolbar.button_style'] = \
         'top:120px;zoom:50%'
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.pdtb_id = 'abc'
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel], [DummyPanel], [])
     toolbar.inject(request, response)
     self.assertTrue(bytes_('top:120px;zoom:50%') in response.app_iter[0])
 def test_passing_of_button_style(self):
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static', STATIC_PATH)
     self.config.add_route('debugtoolbar', '/_debugtoolbar/*subpath')
     self.config.registry.settings['debugtoolbar.button_style'] = \
         'top:120px;zoom:50%'
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.pdtb_id = 'abc'
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel], [DummyPanel], [])
     toolbar.inject(request, response)
     self.assertTrue(bytes_('top:120px;zoom:50%') in response.app_iter[0])
Ejemplo n.º 25
0
 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings, "button_style", "")
     css_path = request.static_url(STATIC_PATH + "css/toolbar.css")
     toolbar_html = toolbar_html_template % {
         "button_style": button_style,
         "css_path": css_path,
         "toolbar_url": toolbar_url,
     }
     toolbar_html = toolbar_html.encode(response.charset or "utf-8")
     response.body = replace_insensitive(response_html, bytes_("</body>"), toolbar_html + bytes_("</body>"))
 def test_passing_of_button_style(self):
     from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.include('pyramid_jinja2')
     self.config.add_static_view('_debugtoolbar/static',
                                 STATIC_PATH)
     self.config.add_route(ROOT_ROUTE_NAME, '/_debugtoolbar')
     self.config.registry.settings['debugtoolbar.button_style'] = \
         'top:120px;zoom:50%'
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel])
     toolbar.process_response(response)
     self.assertTrue(response.processed)
     self.failUnless(bytes_('top:120px;zoom:50%') in response.app_iter[0])
Ejemplo n.º 27
0
    def content(self):
        if not self.queries:
            return 'No queries in executed in request.'

        data = []
        for query in self.queries:
            stmt = query['statement']

            is_select = stmt.strip().lower().startswith('select')
            params = ''
            try:
                params = url_quote(json.dumps(query['parameters']))
            except TypeError:
                pass  # object not JSON serializable
            except UnicodeDecodeError:
                pass  # parameters contain non-utf8 (probably binary) data

            need = self.request.exc_history.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(stmt),
                'raw_sql': stmt,
                'hash': hash,
                'parameters': query['parameters'],
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        vars = {
            'static_path': self.request.static_url(STATIC_PATH),
            'root_path': self.request.route_url(ROOT_ROUTE_NAME),
            'queries': data,
            'text': text,
        }

        delattr(self.request, 'pdtb_sqla_queries')

        return self.render(
            'pyramid_debugtoolbar.panels:templates/sqlalchemy.dbtmako', vars,
            self.request)
Ejemplo n.º 28
0
    def content(self):
        if not self.queries:
            return 'No queries in executed in request.'

        data = []
        for query in self.queries:
            stmt = query['statement']

            is_select = stmt.strip().lower().startswith('select')
            params = ''
            try:
                params = url_quote(json.dumps(query['parameters']))
            except TypeError:
                pass # object not JSON serializable
            except UnicodeDecodeError:
                pass # parameters contain non-utf8 (probably binary) data

            need = self.request.exc_history.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(stmt),
                'raw_sql': stmt,
                'hash': hash,
                'parameters': query['parameters'],
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        vars = {
            'static_path': self.request.static_url(STATIC_PATH),
            'root_path': self.request.route_url(ROOT_ROUTE_NAME),
            'queries':data,
            'text':text,
            }

        delattr(self.request, 'pdtb_sqla_queries')

        return self.render(
            'pyramid_debugtoolbar.panels:templates/sqlalchemy.dbtmako',
            vars, self.request)
Ejemplo n.º 29
0
    def content(self):
        if not self.queries:
            return "No queries in executed in request."

        data = []
        for query in self.queries:
            stmt = query["statement"]

            is_select = stmt.strip().lower().startswith("select")
            params = ""
            try:
                params = url_quote(json.dumps(query["parameters"]))
            except TypeError:
                pass  # object not JSON serializable
            except UnicodeDecodeError:
                pass  # parameters contain non-utf8 (probably binary) data

            need = self.request.exc_history.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append(
                {
                    "engine_id": query["engine_id"],
                    "duration": query["duration"],
                    "sql": format_sql(stmt),
                    "raw_sql": stmt,
                    "hash": hash,
                    "parameters": query["parameters"],
                    "params": params,
                    "is_select": is_select,
                    "context": query["context"],
                }
            )

        vars = {
            "static_path": self.request.static_url(STATIC_PATH),
            "root_path": self.request.route_url(ROOT_ROUTE_NAME),
            "queries": data,
            "text": text,
        }

        delattr(self.request, "pdtb_sqla_queries")

        return self.render("pyramid_debugtoolbar.panels:templates/sqlalchemy.dbtmako", vars, self.request)
Ejemplo n.º 30
0
    def content(self):
        if not self.queries:
            return 'No queries in executed in request.'

        data = []
        for query in self.queries:
            is_select = query['statement'].strip().lower().startswith('select')
            params = ''
            try:
                params = json.dumps(query['parameters'])
            except TypeError:
                pass # object not JSON serializable

            hash = hashlib.sha1(
                bytes_(self.request.exc_history.token +
                       query['statement'] + params)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(query['statement']),
                'raw_sql': query['statement'],
                'hash': hash,
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        vars = {
            'static_path': self.request.static_url(STATIC_PATH),
            'root_path': self.request.route_url(ROOT_ROUTE_NAME),
            'queries':data,
            }

        delattr(self.request, 'pdtb_sqla_queries')

        return self.render(
            'pyramid_debugtoolbar.panels:templates/sqlalchemy.jinja2',
            vars, self.request)
    def content(self):
        if not self.queries:
            return 'No queries in executed in request.'

        data = []
        for query in self.queries:
            is_select = query['statement'].strip().lower().startswith('select')
            params = ''
            try:
                params = json.dumps(query['parameters'])
            except TypeError:
                pass  # object not JSON serializable

            hash = hashlib.sha1(
                bytes_(self.request.exc_history.token + query['statement'] +
                       params)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(query['statement']),
                'raw_sql': query['statement'],
                'hash': hash,
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        vars = {
            'static_path': self.request.static_url(STATIC_PATH),
            'root_path': self.request.route_url(ROOT_ROUTE_NAME),
            'queries': data,
        }

        delattr(self.request, 'pdtb_sqla_queries')

        return self.render(
            'pyramid_debugtoolbar.panels:templates/sqlalchemy.jinja2', vars,
            self.request)
Ejemplo n.º 32
0
    def test_debug_repr(self):
        assert debug_repr([]) == "[]"
        assert debug_repr([1, 2]) == '[<span class="number">1</span>, <span class="number">2</span>]'
        assert debug_repr([1, "test"]) == '[<span class="number">1</span>, <span class="string">\'test\'</span>]'
        assert debug_repr([None]) == '[<span class="object">None</span>]'
        assert debug_repr(list(range(20))) == (
            '[<span class="number">0</span>, <span class="number">1</span>, '
            '<span class="number">2</span>, <span class="number">3</span>, '
            '<span class="number">4</span>, <span class="number">5</span>, '
            '<span class="number">6</span>, <span class="number">7</span>, '
            '<span class="number">8</span>, <span class="number">9</span>, '
            '<span class="number">10</span>, <span class="number">11</span>, '
            '<span class="number">12</span>, <span class="number">13</span>, '
            '<span class="number">14</span>, <span class="number">15</span>, '
            '<span class="number">16</span>, <span class="number">17</span>, '
            '<span class="number">18</span>, <span class="number">19</span>]'
        )
        assert debug_repr({}) == "{}"
        assert (
            debug_repr({"foo": 42}) == '{<span class="pair"><span class="key"><span class="string">\'foo\''
            '</span></span>: <span class="value"><span class="number">42'
            "</span></span></span>}"
        )
        result = debug_repr((1, bytes_("zwei"), text_("drei")))
        if PY3:  # pragma: no cover
            expected = (
                '(<span class="number">1</span>, <span class="string">b\''
                "zwei'</span>, <span class=\"string\">'drei'</span>)"
            )
        else:
            expected = (
                '(<span class="number">1</span>, <span class="string">\''
                "zwei'</span>, <span class=\"string\">u'drei'</span>)"
            )
        assert result == expected

        class Foo(object):
            def __repr__(self):
                return "<Foo 42>"

        assert debug_repr(Foo()) == '<span class="object">&lt;Foo 42&gt;</span>'

        class MyList(list):
            pass

        tmp = debug_repr(MyList([1, 2]))
        assert (
            tmp == '<span class="module">pyramid_debugtoolbar.tests.test_debug.</span>MyList(['
            '<span class="number">1</span>, <span class="number">2</span>])'
        )

        result = debug_repr(re.compile(r"foo\d"))
        assert result == "re.compile(<span class=\"string regex\">r'foo\\d'</span>)"
        result = debug_repr(re.compile(text_(r"foo\d")))
        if PY3:  # pragma: no cover
            assert result == "re.compile(<span class=\"string regex\">r'foo\\d'</span>)"
        else:
            assert result == "re.compile(<span class=\"string regex\">ur'foo\\d'</span>)"

        assert debug_repr(frozenset("x")) == "frozenset([<span class=\"string\">'x'</span>])"
        assert debug_repr(set("x")) == "set([<span class=\"string\">'x'</span>])"

        a = [1]
        a.append(a)
        assert debug_repr(a) == '[<span class="number">1</span>, [...]]'

        class Foo(object):
            def __repr__(self):
                1 / 0

        result = debug_repr(Foo())

        assert "division" in result
Ejemplo n.º 33
0
 def test_it(self):
     result = self._callFUT("SELECT * FROM TBL")
     self.assertTrue(result.startswith(bytes_("<div")))
Ejemplo n.º 34
0
    def test_debug_repr(self):
        assert debug_repr([]) == '[]'
        assert (debug_repr([
            1, 2
        ]) == '[<span class="number">1</span>, <span class="number">2</span>]')
        assert debug_repr([1, 'test'
                           ]) == ('[<span class="number">1</span>, '
                                  '<span class="string">\'test\'</span>]')
        assert debug_repr([None]) == '[<span class="object">None</span>]'
        assert debug_repr(list(range(20))) == (
            '[<span class="number">0</span>, <span class="number">1</span>, '
            '<span class="number">2</span>, <span class="number">3</span>, '
            '<span class="number">4</span>, <span class="number">5</span>, '
            '<span class="number">6</span>, <span class="number">7</span>, '
            '<span class="number">8</span>, <span class="number">9</span>, '
            '<span class="number">10</span>, <span class="number">11</span>, '
            '<span class="number">12</span>, <span class="number">13</span>, '
            '<span class="number">14</span>, <span class="number">15</span>, '
            '<span class="number">16</span>, <span class="number">17</span>, '
            '<span class="number">18</span>, <span class="number">19</span>]')
        assert debug_repr({}) == '{}'
        assert debug_repr({'foo': 42}) == (
            '{<span class="pair"><span class="key"><span class="string">\'foo\''
            '</span></span>: <span class="value"><span class="number">42'
            '</span></span></span>}')
        result = debug_repr((1, bytes_('zwei'), text_('drei')))
        if PY3:  # pragma: no cover
            expected = (
                '(<span class="number">1</span>, <span class="string">b\''
                'zwei\'</span>, <span class="string">\'drei\'</span>)')
        else:
            expected = (
                '(<span class="number">1</span>, <span class="string">\''
                'zwei\'</span>, <span class="string">u\'drei\'</span>)')
        assert result == expected

        class Foo(object):
            def __repr__(self):
                return '<Foo 42>'

        assert (debug_repr(
            Foo()) == '<span class="object">&lt;Foo 42&gt;</span>')

        class MyList(list):
            pass

        tmp = debug_repr(MyList([1, 2]))
        assert (
            tmp == '<span class="module">tests.test_debug.</span>MyList(['
            '<span class="number">1</span>, <span class="number">2</span>])')

        result = debug_repr(re.compile(r'foo\d'))
        assert (result ==
                're.compile(<span class="string regex">r\'foo\\d\'</span>)')
        result = debug_repr(re.compile(text_(r'foo\d')))
        if PY3:  # pragma: no cover
            assert (
                result ==
                're.compile(<span class="string regex">r\'foo\\d\'</span>)')
        else:
            assert (
                result ==
                're.compile(<span class="string regex">ur\'foo\\d\'</span>)')

        assert (debug_repr(
            frozenset('x')) == 'frozenset([<span class="string">\'x\'</span>])'
                )
        assert (debug_repr(
            set('x')) == 'set([<span class="string">\'x\'</span>])')

        a = [1]
        a.append(a)
        assert debug_repr(a) == '[<span class="number">1</span>, [...]]'

        class Foo(object):
            def __repr__(self):
                1 / 0

        result = debug_repr(Foo())

        assert 'division' in result
Ejemplo n.º 35
0
def hexlify(value):
    """Hexlify int, str then returns native str type."""
    # If integer
    str_ = str(value)
    hexified = text_(binascii.hexlify(bytes_(str_)))
    return hexified
Ejemplo n.º 36
0
def hexlify(value):
    """Hexlify int, str then returns native str type."""
    # If integer
    str_ = str(value)
    hexified = text_(binascii.hexlify(bytes_(str_)))
    return hexified
    def test_debug_repr(self):
        assert debug_repr([]) == '[]'
        assert debug_repr([1, 2]) == \
            '[<span class="number">1</span>, <span class="number">2</span>]'
        assert debug_repr([1, 'test']) == \
            '[<span class="number">1</span>, <span class="string">\'test\'</span>]'
        assert debug_repr([None]) == \
            '[<span class="object">None</span>]'
        assert debug_repr(list(range(20))) == (
            '[<span class="number">0</span>, <span class="number">1</span>, '
            '<span class="number">2</span>, <span class="number">3</span>, '
            '<span class="number">4</span>, <span class="number">5</span>, '
            '<span class="number">6</span>, <span class="number">7</span>, '
            '<span class="number">8</span>, <span class="number">9</span>, '
            '<span class="number">10</span>, <span class="number">11</span>, '
            '<span class="number">12</span>, <span class="number">13</span>, '
            '<span class="number">14</span>, <span class="number">15</span>, '
            '<span class="number">16</span>, <span class="number">17</span>, '
            '<span class="number">18</span>, <span class="number">19</span>]'
        )
        assert debug_repr({}) == '{}'
        assert debug_repr({'foo': 42}) == \
            '{<span class="pair"><span class="key"><span class="string">\'foo\''\
            '</span></span>: <span class="value"><span class="number">42' \
            '</span></span></span>}'
        result = debug_repr((1, bytes_('zwei'), text_('drei')))
        if PY3: # pragma: no cover
            expected = (
                '(<span class="number">1</span>, <span class="string">b\''
                'zwei\'</span>, <span class="string">\'drei\'</span>)')
        else:
            expected = (
                '(<span class="number">1</span>, <span class="string">\''
                'zwei\'</span>, <span class="string">u\'drei\'</span>)')
        assert result == expected

        class Foo(object):
            def __repr__(self):
                return '<Foo 42>'
        assert debug_repr(Foo()) == '<span class="object">&lt;Foo 42&gt;</span>'

        class MyList(list):
            pass
        tmp = debug_repr(MyList([1, 2]))
        assert tmp == \
            '<span class="module">pyramid_debugtoolbar.tests.test_debug.</span>MyList([' \
            '<span class="number">1</span>, <span class="number">2</span>])'

        result = debug_repr(re.compile(r'foo\d'))
        assert result == \
            're.compile(<span class="string regex">r\'foo\\d\'</span>)'
        result = debug_repr(re.compile(text_(r'foo\d')))
        if PY3: # pragma: no cover
            assert result == \
                   're.compile(<span class="string regex">r\'foo\\d\'</span>)'
        else:
            assert result == \
                   're.compile(<span class="string regex">ur\'foo\\d\'</span>)'


        assert debug_repr(frozenset('x')) == \
            'frozenset([<span class="string">\'x\'</span>])'
        assert debug_repr(set('x')) == \
            'set([<span class="string">\'x\'</span>])'

        a = [1]
        a.append(a)
        assert debug_repr(a) == '[<span class="number">1</span>, [...]]'

        class Foo(object):
            def __repr__(self):
                1/0

        result = debug_repr(Foo())

        assert 'division' in result
Ejemplo n.º 38
0
 def test_it(self):
     result = self._callFUT('SELECT * FROM TBL')
     self.assertTrue(result.startswith(bytes_('<div')))