Ejemplo n.º 1
0
    def test_not_distributed(self):
        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name
        self._trace_app_not_distributed(self.tracer)

        # make a request
        headers = {'x-datadog-trace-id': '123',
                   'x-datadog-parent-id': '456'}
        resp = self.app.get('/hi/dougie', headers=headers)
        eq_(resp.status_int, 200)
        eq_(compat.to_unicode(resp.body), u'hi dougie')

        # validate it's traced
        spans = self.tracer.writer.pop()
        eq_(len(spans), 1)
        s = spans[0]
        eq_(s.name, 'bottle.request')
        eq_(s.service, 'bottle-app')
        eq_(s.resource, 'GET /hi/<name>')
        eq_(s.get_tag('http.status_code'), '200')
        eq_(s.get_tag('http.method'), 'GET')
        # check distributed headers
        assert_not_equal(123, s.trace_id)
        assert_not_equal(456, s.parent_id)
Ejemplo n.º 2
0
 def test_to_unicode_bytearray_double_decode(self):
     #  Calling `compat.to_unicode` with an already decoded `bytearray`
     # This represents the double-decode issue, which can cause a `UnicodeEncodeError`
     #   `bytearray('\xc3\xbf').decode('utf-8').decode('utf-8')`
     res = to_unicode(bytearray('\xc3\xbf').decode('utf-8'))
     eq_(type(res), unicode)
     eq_(res, u'ÿ')
Ejemplo n.º 3
0
    def test_analytics_global_off_integration_default(self):
        """
        When making a request
            When an integration trace search is not set and sample rate is set and globally trace search is disabled
                We expect the root span to not include tag
        """
        # setup our test app
        @self.app.route("/hi/<name>")
        def hi(name):
            return "hi %s" % name

        self._trace_app(self.tracer)

        with self.override_global_config(dict(analytics_enabled=False)):
            resp = self.app.get("/hi/dougie")
            assert resp.status_int == 200
            assert compat.to_unicode(resp.body) == u"hi dougie"

        root = self.get_root_span()
        self.assertIsNone(root.get_metric(ANALYTICS_SAMPLE_RATE_KEY))

        for span in self.spans:
            if span == root:
                continue
            self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))
Ejemplo n.º 4
0
    def test_analytics_global_off_integration_on(self):
        """
        When making a request
            When an integration trace search is enabled and sample rate is set and globally trace search is disabled
                We expect the root span to have the appropriate tag
        """
        # setup our test app
        @self.app.route("/hi/<name>")
        def hi(name):
            return "hi %s" % name

        self._trace_app(self.tracer)

        with self.override_global_config(dict(analytics_enabled=False)):
            with self.override_config(
                    "bottle",
                    dict(analytics_enabled=True, analytics_sample_rate=0.5)):
                resp = self.app.get("/hi/dougie")
                assert resp.status_int == 200
                assert compat.to_unicode(resp.body) == u"hi dougie"

        root = self.get_root_span()
        root.assert_matches(
            name="bottle.request",
            metrics={
                ANALYTICS_SAMPLE_RATE_KEY: 0.5,
            },
        )

        for span in self.spans:
            if span == root:
                continue
            self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))
Ejemplo n.º 5
0
    def test_analytics_global_on_integration_default(self):
        """
        When making a request
            When an integration trace search is not event sample rate is not set and globally trace search is enabled
                We expect the root span to have the appropriate tag
        """
        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name

        self._trace_app(self.tracer)

        with self.override_global_config(dict(analytics_enabled=True)):
            resp = self.app.get('/hi/dougie')
            assert resp.status_int == 200
            assert compat.to_unicode(resp.body) == u'hi dougie'

        root = self.get_root_span()
        root.assert_matches(
            name='bottle.request',
            metrics={
                ANALYTICS_SAMPLE_RATE_KEY: 1.0,
            },
        )

        for span in self.spans:
            if span == root:
                continue
            self.assertIsNone(span.get_metric(ANALYTICS_SAMPLE_RATE_KEY))
Ejemplo n.º 6
0
    def test_200(self, query_string=''):
        if query_string:
            fqs = '?' + query_string
        else:
            fqs = ''

        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name

        self._trace_app(self.tracer)

        # make a request
        resp = self.app.get('/hi/dougie' + fqs)
        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u'hi dougie'
        # validate it's traced
        spans = self.tracer.writer.pop()
        assert len(spans) == 1
        s = spans[0]
        assert s.name == 'bottle.request'
        assert s.service == 'bottle-app'
        assert s.span_type == 'web'
        assert s.resource == 'GET /hi/<name>'
        assert s.get_tag('http.status_code') == '200'
        assert s.get_tag('http.method') == 'GET'
        assert s.get_tag(http.URL) == 'http://localhost:80/hi/dougie'

        services = self.tracer.writer.pop_services()
        assert services == {}
Ejemplo n.º 7
0
    def test_200(self):
        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name

        self._trace_app(self.tracer)

        # make a request
        resp = self.app.get('/hi/dougie')
        eq_(resp.status_int, 200)
        eq_(compat.to_unicode(resp.body), u'hi dougie')
        # validate it's traced
        spans = self.tracer.writer.pop()
        eq_(len(spans), 1)
        s = spans[0]
        eq_(s.name, 'bottle.request')
        eq_(s.service, 'bottle-app')
        eq_(s.span_type, 'web')
        eq_(s.resource, 'GET /hi/<name>')
        eq_(s.get_tag('http.status_code'), '200')
        eq_(s.get_tag('http.method'), 'GET')

        services = self.tracer.writer.pop_services()
        eq_(len(services), 1)
        ok_(SERVICE in services)
        s = services[SERVICE]
        eq_(s['app_type'], 'web')
        eq_(s['app'], 'bottle')
Ejemplo n.º 8
0
    def test_not_distributed(self):
        # setup our test app
        @self.app.route("/hi/<name>")
        def hi(name):
            return "hi %s" % name

        self._trace_app_not_distributed(self.tracer)

        # make a request
        headers = {"x-datadog-trace-id": "123", "x-datadog-parent-id": "456"}
        resp = self.app.get("/hi/dougie", headers=headers)
        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u"hi dougie"

        # validate it's traced
        spans = self.tracer.writer.pop()
        assert len(spans) == 1
        s = spans[0]
        assert s.name == "bottle.request"
        assert s.service == "bottle-app"
        assert s.resource == "GET /hi/<name>"
        assert_span_http_status_code(s, 200)
        assert s.get_tag("http.method") == "GET"
        # check distributed headers
        assert 123 != s.trace_id
        assert 456 != s.parent_id
Ejemplo n.º 9
0
    def test_200(self):
        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name
        self._trace_app(self.tracer)

        # make a request
        resp = self.app.get('/hi/dougie')
        eq_(resp.status_int, 200)
        eq_(compat.to_unicode(resp.body), u'hi dougie')
        # validate it's traced
        spans = self.tracer.writer.pop()
        eq_(len(spans), 1)
        s = spans[0]
        eq_(s.name, 'bottle.request')
        eq_(s.service, 'bottle-app')
        eq_(s.resource, 'GET /hi/<name>')
        eq_(s.get_tag('http.status_code'), '200')
        eq_(s.get_tag('http.method'), 'GET')

        services = self.tracer.writer.pop_services()
        eq_(len(services), 1)
        ok_(SERVICE in services)
        s = services[SERVICE]
        eq_(s['app_type'], 'web')
        eq_(s['app'], 'bottle')
Ejemplo n.º 10
0
 def test_to_unicode_bytearray_double_decode(self):
     #  Calling `compat.to_unicode` with an already decoded `bytearray`
     # This represents the double-decode issue, which can cause a `UnicodeEncodeError`
     #   `bytearray('\xc3\xbf').decode('utf-8').decode('utf-8')`
     res = to_unicode(bytearray(b'\xc3\xbf').decode('utf-8'))
     assert type(res) == unicode
     assert res == u'ÿ'
Ejemplo n.º 11
0
 def test_to_unicode_unicode_double_decode(self):
     # Calling `compat.to_unicode` on a unicode decoded string
     # This represents the double-decode issue, which can cause a `UnicodeEncodeError`
     #   `'\xc3\xbf'.decode('utf-8').decode('utf-8')`
     res = to_unicode(b'\xc3\xbf'.decode('utf-8'))
     assert type(res) == unicode
     assert res == u'ÿ'
Ejemplo n.º 12
0
 def test_to_unicode_unicode_double_decode(self):
     # Calling `compat.to_unicode` on a unicode decoded string
     # This represents the double-decode issue, which can cause a `UnicodeEncodeError`
     #   `'\xc3\xbf'.decode('utf-8').decode('utf-8')`
     res = to_unicode('\xc3\xbf'.decode('utf-8'))
     eq_(type(res), unicode)
     eq_(res, u'ÿ')
Ejemplo n.º 13
0
    def test_not_distributed(self):
        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name

        self._trace_app_not_distributed(self.tracer)

        # make a request
        headers = {'x-datadog-trace-id': '123', 'x-datadog-parent-id': '456'}
        resp = self.app.get('/hi/dougie', headers=headers)
        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u'hi dougie'

        # validate it's traced
        spans = self.tracer.writer.pop()
        assert len(spans) == 1
        s = spans[0]
        assert s.name == 'bottle.request'
        assert s.service == 'bottle-app'
        assert s.resource == 'GET /hi/<name>'
        assert s.get_metric('http.status_code') == 200
        assert s.get_tag('http.method') == 'GET'
        # check distributed headers
        assert 123 != s.trace_id
        assert 456 != s.parent_id
Ejemplo n.º 14
0
def test_redis_legacy():
    # ensure the old interface isn't broken, but doesn't trace
    tracer = get_dummy_tracer()
    TracedRedisCache = get_traced_redis(tracer, "foo")
    r = TracedRedisCache(port=REDIS_CONFIG['port'])
    r.set("a", "b")
    got = r.get("a")
    eq_(compat.to_unicode(got), "b")
    assert not tracer.writer.pop()
Ejemplo n.º 15
0
def test_redis_legacy():
    # ensure the old interface isn't broken, but doesn't trace
    tracer = get_dummy_tracer()
    TracedRedisCache = get_traced_redis(tracer, 'foo')
    r = TracedRedisCache(port=REDIS_CONFIG['port'])
    r.set('a', 'b')
    got = r.get('a')
    assert compat.to_unicode(got) == 'b'
    assert not tracer.writer.pop()
Ejemplo n.º 16
0
def test_redis_legacy():
    # ensure the old interface isn't broken, but doesn't trace
    tracer = get_dummy_tracer()
    TracedRedisCache = get_traced_redis(tracer, "foo")
    r = TracedRedisCache(port=REDIS_CONFIG['port'])
    r.set("a", "b")
    got = r.get("a")
    eq_(compat.to_unicode(got), "b")
    assert not tracer.writer.pop()
Ejemplo n.º 17
0
    def func(response):
        try:
            # pull out response code from gRPC response to use both for `grpc.status.code`
            # tag and the error type tag if the response is an exception
            response_code = response.code()
            # cast code to unicode for tags
            status_code = to_unicode(response_code)
            span._set_str_tag(constants.GRPC_STATUS_CODE_KEY, status_code)

            if response_code != grpc.StatusCode.OK:
                _handle_error(span, response, status_code)
        finally:
            span.finish()
Ejemplo n.º 18
0
    def test_render(self):
        # render
        t = Template("Hello ${name}!")
        self.assertEqual(t.render(name="mako"), "Hello mako!")

        spans = self.pop_spans()
        self.assertEqual(len(spans), 1)

        assert_is_measured(spans[0])
        self.assertEqual(spans[0].service, "mako")
        self.assertEqual(spans[0].span_type, "template")
        self.assertEqual(spans[0].get_tag("mako.template_name"),
                         DEFAULT_TEMPLATE_NAME)
        self.assertEqual(spans[0].name, "mako.template.render")
        self.assertEqual(spans[0].resource, DEFAULT_TEMPLATE_NAME)

        # render_unicode
        t = Template("Hello ${name}!")
        self.assertEqual(t.render_unicode(name="mako"),
                         to_unicode("Hello mako!"))
        spans = self.pop_spans()
        self.assertEqual(len(spans), 1)
        assert_is_measured(spans[0])
        self.assertEqual(spans[0].service, "mako")
        self.assertEqual(spans[0].span_type, "template")
        self.assertEqual(spans[0].get_tag("mako.template_name"),
                         DEFAULT_TEMPLATE_NAME)
        self.assertEqual(spans[0].name, "mako.template.render_unicode")
        self.assertEqual(spans[0].resource, DEFAULT_TEMPLATE_NAME)

        # render_context
        t = Template("Hello ${name}!")
        buf = StringIO()
        c = Context(buf, name="mako")
        t.render_context(c)
        self.assertEqual(buf.getvalue(), "Hello mako!")
        spans = self.pop_spans()
        self.assertEqual(len(spans), 1)
        assert_is_measured(spans[0])
        self.assertEqual(spans[0].service, "mako")
        self.assertEqual(spans[0].span_type, "template")
        self.assertEqual(spans[0].get_tag("mako.template_name"),
                         DEFAULT_TEMPLATE_NAME)
        self.assertEqual(spans[0].name, "mako.template.render_context")
        self.assertEqual(spans[0].resource, DEFAULT_TEMPLATE_NAME)
Ejemplo n.º 19
0
    def test_render(self):
        # render
        t = Template('Hello ${name}!')
        self.assertEqual(t.render(name='mako'), 'Hello mako!')

        spans = self.tracer.writer.pop()
        self.assertEqual(len(spans), 1)

        assert_is_measured(spans[0])
        self.assertEqual(spans[0].service, 'mako')
        self.assertEqual(spans[0].span_type, 'template')
        self.assertEqual(spans[0].get_tag('mako.template_name'), '<memory>')
        self.assertEqual(spans[0].name, 'mako.template.render')
        self.assertEqual(spans[0].resource, '<memory>')

        # render_unicode
        t = Template('Hello ${name}!')
        self.assertEqual(t.render_unicode(name='mako'),
                         to_unicode('Hello mako!'))
        spans = self.tracer.writer.pop()
        self.assertEqual(len(spans), 1)
        assert_is_measured(spans[0])
        self.assertEqual(spans[0].service, 'mako')
        self.assertEqual(spans[0].span_type, 'template')
        self.assertEqual(spans[0].get_tag('mako.template_name'), '<memory>')
        self.assertEqual(spans[0].name, 'mako.template.render_unicode')
        self.assertEqual(spans[0].resource, '<memory>')

        # render_context
        t = Template('Hello ${name}!')
        buf = StringIO()
        c = Context(buf, name='mako')
        t.render_context(c)
        self.assertEqual(buf.getvalue(), 'Hello mako!')
        spans = self.tracer.writer.pop()
        self.assertEqual(len(spans), 1)
        assert_is_measured(spans[0])
        self.assertEqual(spans[0].service, 'mako')
        self.assertEqual(spans[0].span_type, 'template')
        self.assertEqual(spans[0].get_tag('mako.template_name'), '<memory>')
        self.assertEqual(spans[0].name, 'mako.template.render_context')
        self.assertEqual(spans[0].resource, '<memory>')
Ejemplo n.º 20
0
    def test_200(self):
        # setup our test app
        @self.app.route("/hi/<name>")
        def hi(name):
            return "hi %s" % name

        self._trace_app(self.tracer)

        # make a request
        resp = self.app.get("/hi/dougie")
        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u"hi dougie"
        # validate it's traced
        spans = self.pop_spans()
        assert len(spans) == 1
        s = spans[0]
        assert s.name == "bottle.request"
        assert s.service == "bottle-app"
        assert s.resource == "GET /hi/<name>"
        assert_span_http_status_code(s, 200)
        assert s.get_tag("http.method") == "GET"
Ejemplo n.º 21
0
def test_json():
    app, tracer = _get_test_app(service='foobar')
    res = app.get('/json', status=200)
    parsed = json.loads(compat.to_unicode(res.body))
    eq_(parsed, {'a':1})

    writer = tracer.writer
    spans = writer.pop()
    eq_(len(spans), 2)
    spans_by_name = {s.name:s for s in spans}
    s = spans_by_name['pyramid.request']
    eq_(s.service, 'foobar')
    eq_(s.resource, 'json')
    eq_(s.error, 0)
    eq_(s.span_type, 'http')
    eq_(s.meta.get('http.status_code'), '200')
    eq_(s.meta.get('http.url'), '/json')

    s = spans_by_name['pyramid.render']
    eq_(s.service, 'foobar')
    eq_(s.error, 0)
    eq_(s.span_type, 'template')
Ejemplo n.º 22
0
    def test_200_ot(self):
        ot_tracer = init_tracer('my_svc', self.tracer)

        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name

        self._trace_app(self.tracer)

        # make a request
        with ot_tracer.start_active_span('ot_span'):
            resp = self.app.get('/hi/dougie')

        eq_(resp.status_int, 200)
        eq_(compat.to_unicode(resp.body), u'hi dougie')
        # validate it's traced
        spans = self.tracer.writer.pop()
        eq_(len(spans), 2)
        ot_span, dd_span = spans

        # confirm the parenting
        eq_(ot_span.parent_id, None)
        eq_(dd_span.parent_id, ot_span.span_id)

        eq_(ot_span.resource, 'ot_span')

        eq_(dd_span.name, 'bottle.request')
        eq_(dd_span.service, 'bottle-app')
        eq_(dd_span.resource, 'GET /hi/<name>')
        eq_(dd_span.get_tag('http.status_code'), '200')
        eq_(dd_span.get_tag('http.method'), 'GET')

        services = self.tracer.writer.pop_services()
        eq_(len(services), 1)
        ok_(SERVICE in services)
        s = services[SERVICE]
        eq_(s['app_type'], 'web')
        eq_(s['app'], 'bottle')
Ejemplo n.º 23
0
    def test_200(self):
        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name
        self._trace_app(self.tracer)

        # make a request
        resp = self.app.get('/hi/dougie')
        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u'hi dougie'
        # validate it's traced
        spans = self.tracer.writer.pop()
        assert len(spans) == 1
        s = spans[0]
        assert s.name == 'bottle.request'
        assert s.service == 'bottle-app'
        assert s.resource == 'GET /hi/<name>'
        assert s.get_tag('http.status_code') == '200'
        assert s.get_tag('http.method') == 'GET'

        services = self.tracer.writer.pop_services()
        assert services == {}
Ejemplo n.º 24
0
    def test_json(self):
        res = self.app.get("/json", status=200)
        parsed = json.loads(compat.to_unicode(res.body))
        assert parsed == {"a": 1}

        spans = self.pop_spans()
        assert len(spans) == 2
        spans_by_name = {s.name: s for s in spans}
        s = spans_by_name["pyramid.request"]
        assert_is_measured(s)
        assert s.service == "foobar"
        assert s.resource == "GET json"
        assert s.error == 0
        assert s.span_type == "web"
        assert s.meta.get("http.method") == "GET"
        assert_span_http_status_code(s, 200)
        assert s.meta.get(http.URL) == "http://localhost/json"
        assert s.meta.get("pyramid.route.name") == "json"

        s = spans_by_name["pyramid.render"]
        assert s.service == "foobar"
        assert s.error == 0
        assert s.span_type == "template"
Ejemplo n.º 25
0
def test_200():
    # setup our test app
    app = bottle.Bottle()

    @app.route('/hi/<name>')
    def hi(name):
        return 'hi %s' % name

    tracer, app = _trace_app(app)

    # make a request
    resp = app.get("/hi/dougie")
    eq_(resp.status_int, 200)
    eq_(compat.to_unicode(resp.body), u'hi dougie')
    # validate it's traced
    spans = tracer.writer.pop()
    eq_(len(spans), 1)
    s = spans[0]
    eq_(s.name, "bottle.request")
    eq_(s.service, "foobar")
    eq_(s.resource, "GET /hi/<name>")
    eq_(s.get_tag('http.status_code'), '200')
    eq_(s.get_tag('http.method'), 'GET')
Ejemplo n.º 26
0
    def test_json(self):
        res = self.app.get('/json', status=200)
        parsed = json.loads(compat.to_unicode(res.body))
        assert parsed == {'a': 1}

        writer = self.tracer.writer
        spans = writer.pop()
        assert len(spans) == 2
        spans_by_name = {s.name: s for s in spans}
        s = spans_by_name['pyramid.request']
        assert s.service == 'foobar'
        assert s.resource == 'GET json'
        assert s.error == 0
        assert s.span_type == 'web'
        assert s.meta.get('http.method') == 'GET'
        assert_span_http_status_code(s, 200)
        assert s.meta.get(http.URL) == 'http://localhost/json'
        assert s.meta.get('pyramid.route.name') == 'json'

        s = spans_by_name['pyramid.render']
        assert s.service == 'foobar'
        assert s.error == 0
        assert s.span_type == 'template'
Ejemplo n.º 27
0
    def test_json(self):
        res = self.app.get('/json', status=200)
        parsed = json.loads(compat.to_unicode(res.body))
        eq_(parsed, {'a': 1})

        writer = self.tracer.writer
        spans = writer.pop()
        eq_(len(spans), 2)
        spans_by_name = {s.name: s for s in spans}
        s = spans_by_name['pyramid.request']
        eq_(s.service, 'foobar')
        eq_(s.resource, 'GET json')
        eq_(s.error, 0)
        eq_(s.span_type, 'http')
        eq_(s.meta.get('http.method'), 'GET')
        eq_(s.meta.get('http.status_code'), '200')
        eq_(s.meta.get('http.url'), '/json')
        eq_(s.meta.get('pyramid.route.name'), 'json')

        s = spans_by_name['pyramid.render']
        eq_(s.service, 'foobar')
        eq_(s.error, 0)
        eq_(s.span_type, 'template')
Ejemplo n.º 28
0
    def test_200_ot(self):
        ot_tracer = init_tracer('my_svc', self.tracer)

        # setup our test app
        @self.app.route('/hi/<name>')
        def hi(name):
            return 'hi %s' % name

        self._trace_app(self.tracer)

        # make a request
        with ot_tracer.start_active_span('ot_span'):
            resp = self.app.get('/hi/dougie')

        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u'hi dougie'
        # validate it's traced
        spans = self.tracer.writer.pop()
        assert len(spans) == 2
        ot_span, dd_span = spans

        # confirm the parenting
        assert ot_span.parent_id is None
        assert dd_span.parent_id == ot_span.span_id

        assert ot_span.resource == 'ot_span'

        assert_is_measured(dd_span)
        assert dd_span.name == 'bottle.request'
        assert dd_span.service == 'bottle-app'
        assert dd_span.resource == 'GET /hi/<name>'
        assert_span_http_status_code(dd_span, 200)
        assert dd_span.get_tag('http.method') == 'GET'
        assert dd_span.get_tag(http.URL) == 'http://localhost:80/hi/dougie'

        services = self.tracer.writer.pop_services()
        assert services == {}
Ejemplo n.º 29
0
    def test_200_ot(self):
        ot_tracer = init_tracer("my_svc", self.tracer)

        # setup our test app
        @self.app.route("/hi/<name>")
        def hi(name):
            return "hi %s" % name

        self._trace_app(self.tracer)

        # make a request
        with ot_tracer.start_active_span("ot_span"):
            resp = self.app.get("/hi/dougie")

        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u"hi dougie"
        # validate it's traced
        spans = self.tracer.writer.pop()
        assert len(spans) == 2
        ot_span, dd_span = spans

        # confirm the parenting
        assert ot_span.parent_id is None
        assert dd_span.parent_id == ot_span.span_id

        assert ot_span.resource == "ot_span"

        assert_is_measured(dd_span)
        assert dd_span.name == "bottle.request"
        assert dd_span.service == "bottle-app"
        assert dd_span.resource == "GET /hi/<name>"
        assert_span_http_status_code(dd_span, 200)
        assert dd_span.get_tag("http.method") == "GET"
        assert dd_span.get_tag(http.URL) == "http://localhost:80/hi/dougie"

        services = self.tracer.writer.pop_services()
        assert services == {}
Ejemplo n.º 30
0
    def test_200(self, query_string=""):
        if query_string:
            fqs = "?" + query_string
        else:
            fqs = ""

        # setup our test app
        @self.app.route("/hi/<name>")
        def hi(name):
            return "hi %s" % name

        self._trace_app(self.tracer)

        # make a request
        resp = self.app.get("/hi/dougie" + fqs)
        assert resp.status_int == 200
        assert compat.to_unicode(resp.body) == u"hi dougie"
        # validate it's traced
        spans = self.tracer.writer.pop()
        assert len(spans) == 1
        s = spans[0]

        assert_is_measured(s)
        assert s.name == "bottle.request"
        assert s.service == "bottle-app"
        assert s.span_type == "web"
        assert s.resource == "GET /hi/<name>"
        assert_span_http_status_code(s, 200)
        assert s.get_tag("http.method") == "GET"
        assert s.get_tag(http.URL) == "http://localhost:80/hi/dougie"
        if ddtrace.config.bottle.trace_query_string:
            assert s.get_tag(http.QUERY_STRING) == query_string
        else:
            assert http.QUERY_STRING not in s.meta

        services = self.tracer.writer.pop_services()
        assert services == {}
Ejemplo n.º 31
0
 def test_to_unicode_bytearray(self):
     # Calling `compat.to_unicode` with a `bytearray` containing unicode
     res = to_unicode(bytearray('\xc3\xbf'))
     eq_(type(res), unicode)
     eq_(res, u'ÿ')
Ejemplo n.º 32
0
    def wrapper(wrapped, instance, args, kwargs):
        if len(args) > 1:
            self = args[0]
            clsname = self.__class__.__name__
        else:
            clsname = ""

        if include_tracer:
            tracer = Tracer()
        else:
            tracer = ddtrace.tracer

        module = inspect.getmodule(wrapped)

        # Use the fully qualified function name as a unique test token to
        # identify the snapshot.
        token = "{}{}{}.{}".format(module.__name__, "." if clsname else "",
                                   clsname, wrapped.__name__)

        # Use variant that applies to update test token. One must apply. If none
        # apply, the test should have been marked as skipped.
        if variants:
            applicable_variant_ids = [k for (k, v) in variants.items() if v]
            assert len(applicable_variant_ids) == 1
            variant_id = applicable_variant_ids[0]
            token = "{}_{}".format(token, variant_id) if variant_id else token

        parsed = parse.urlparse(tracer.writer.agent_url)
        conn = httplib.HTTPConnection(parsed.hostname, parsed.port)
        try:
            # clear queue in case traces have been generated before test case is
            # itself run
            try:
                tracer.writer.flush_queue()
            except Exception as e:
                pytest.fail("Could not flush the queue before test case: %s" %
                            str(e),
                            pytrace=True)

            if async_mode:
                # Patch the tracer writer to include the test token header for all requests.
                tracer.writer._headers["X-Datadog-Test-Token"] = token
            else:
                # Signal the start of this test case to the test agent.
                try:
                    conn.request("GET", "/test/start?token=%s" % token)
                except Exception as e:
                    pytest.fail("Could not connect to test agent: %s" % str(e),
                                pytrace=False)
                else:
                    r = conn.getresponse()
                    if r.status != 200:
                        # The test agent returns nice error messages we can forward to the user.
                        raise SnapshotFailed(r.read())

            # Run the test.
            try:
                if include_tracer:
                    kwargs["tracer"] = tracer
                ret = wrapped(*args, **kwargs)
                # Force a flush so all traces are submitted.
                tracer.writer.flush_queue()
            finally:
                if async_mode:
                    del tracer.writer._headers["X-Datadog-Test-Token"]

            # Query for the results of the test.
            conn = httplib.HTTPConnection(parsed.hostname, parsed.port)
            conn.request(
                "GET", "/test/snapshot?ignores=%s&token=%s" %
                (",".join(ignores), token))
            r = conn.getresponse()
            if r.status != 200:
                raise SnapshotFailed(r.read())
            return ret
        except SnapshotFailed as e:
            # Fail the test if a failure has occurred and print out the
            # message we got from the test agent.
            pytest.fail(to_unicode(e.args[0]), pytrace=False)
        except Exception as e:
            # Even though it's unlikely any traces have been sent, make the
            # final request to the test agent so that the test case is finished.
            conn = httplib.HTTPConnection(parsed.hostname, parsed.port)
            conn.request(
                "GET", "/test/snapshot?ignores=%s&token=%s" %
                (",".join(ignores), token))
            conn.getresponse()
            pytest.fail("Unexpected test failure during snapshot test: %s" %
                        str(e),
                        pytrace=True)
        finally:
            conn.close()
Ejemplo n.º 33
0
 def test_to_unicode_unicode_encoded(self):
     # Calling `compat.to_unicode` on a unicode encoded string
     res = to_unicode('\xff')
     eq_(type(res), str)
     eq_(res, 'ÿ')
Ejemplo n.º 34
0
def traced_wsgi_app(pin, wrapped, instance, args, kwargs):
    """
    Wrapper for flask.app.Flask.wsgi_app

    This wrapper is the starting point for all requests.
    """
    # DEV: This is safe before this is the args for a WSGI handler
    #   https://www.python.org/dev/peps/pep-3333/
    environ, start_response = args

    # Create a werkzeug request from the `environ` to make interacting with it easier
    # DEV: This executes before a request context is created
    request = werkzeug.Request(environ)

    # Configure distributed tracing
    if config.flask.get('distributed_tracing_enabled', False):
        propagator = HTTPPropagator()
        context = propagator.extract(request.headers)
        # Only need to activate the new context if something was propagated
        if context.trace_id:
            pin.tracer.context_provider.activate(context)

    # Default resource is method and path:
    #   GET /
    #   POST /save
    # We will override this below in `traced_dispatch_request` when we have a `RequestContext` and possibly a url rule
    resource = u'{} {}'.format(request.method, request.path)
    with pin.tracer.trace('flask.request',
                          service=pin.service,
                          resource=resource,
                          span_type=http.TYPE) as s:
        # set analytics sample rate with global config enabled
        sample_rate = config.flask.get_analytics_sample_rate(
            use_global_config=True)
        if sample_rate is not None:
            s.set_tag(ANALYTICS_SAMPLE_RATE_KEY, sample_rate)

        s.set_tag(FLASK_VERSION, flask_version_str)

        # Wrap the `start_response` handler to extract response code
        # DEV: We tried using `Flask.finalize_request`, which seemed to work, but gave us hell during tests
        # DEV: The downside to using `start_response` is we do not have a `Flask.Response` object here,
        #   only `status_code`, and `headers` to work with
        #   On the bright side, this works in all versions of Flask (or any WSGI app actually)
        def _wrap_start_response(func):
            def traced_start_response(status_code, headers):
                code, _, _ = status_code.partition(' ')
                try:
                    code = int(code)
                except ValueError:
                    pass

                # Override root span resource name to be `<method> 404` for 404 requests
                # DEV: We do this because we want to make it easier to see all unknown requests together
                #      Also, we do this to reduce the cardinality on unknown urls
                # DEV: If we have an endpoint or url rule tag, then we don't need to do this,
                #      we still want `GET /product/<int:product_id>` grouped together,
                #      even if it is a 404
                if not s.get_tag(FLASK_ENDPOINT) and not s.get_tag(
                        FLASK_URL_RULE):
                    s.resource = u'{} {}'.format(request.method, code)

                s.set_tag(http.STATUS_CODE, code)
                if 500 <= code < 600:
                    s.error = 1
                elif code in config.flask.get('extra_error_codes', set()):
                    s.error = 1
                return func(status_code, headers)

            return traced_start_response

        start_response = _wrap_start_response(start_response)

        # DEV: We set response status code in `_wrap_start_response`
        # DEV: Use `request.base_url` and not `request.url` to keep from leaking any query string parameters
        s.set_tag(http.URL, request.base_url)
        s.set_tag(http.METHOD, request.method)
        if config.flask.trace_query_string:
            s.set_tag(http.QUERY_STRING,
                      compat.to_unicode(request.query_string))

        return wrapped(environ, start_response)
Ejemplo n.º 35
0
 def test_to_unicode_unicode_string(self):
     # Calling `compat.to_unicode` on a unicode string
     res = to_unicode('ÿ')
     eq_(type(res), str)
     eq_(res, 'ÿ')
Ejemplo n.º 36
0
 def test_to_unicode_non_string(self):
     #  Calling `compat.to_unicode` on non-string types
     assert to_unicode(1) == u"1"
     assert to_unicode(True) == u"True"
     assert to_unicode(None) == u"None"
     assert to_unicode(dict(key="value")) == u"{'key': 'value'}"
Ejemplo n.º 37
0
 def test_to_unicode_bytearray(self):
     # Calling `compat.to_unicode` with a `bytearray` containing unicode
     res = to_unicode(bytearray(b"\xc3\xbf"))
     assert type(res) == unicode
     assert res == u"ÿ"
Ejemplo n.º 38
0
 def test_to_unicode_unicode_string(self):
     # Calling `compat.to_unicode` on a unicode string
     res = to_unicode(u"ÿ")
     assert type(res) == unicode
     assert res == u"ÿ"
Ejemplo n.º 39
0
 def test_to_unicode_unicode_encoded(self):
     # Calling `compat.to_unicode` on a unicode encoded string
     res = to_unicode(b"\xc3\xbf")
     assert type(res) == unicode
     assert res == u"ÿ"
Ejemplo n.º 40
0
 def test_to_unicode_unicode_encoded(self):
     # Calling `compat.to_unicode` on a unicode encoded string
     res = to_unicode('\xc3\xbf')
     eq_(type(res), unicode)
     eq_(res, u'ÿ')
Ejemplo n.º 41
0
 def test_to_unicode_non_string(self):
     # Calling `compat.to_unicode` on non-string types
     eq_(to_unicode(1), '1')
     eq_(to_unicode(True), 'True')
     eq_(to_unicode(None), 'None')
     eq_(to_unicode(dict(key='value')), '{\'key\': \'value\'}')
Ejemplo n.º 42
0
 def test_to_unicode_bytearray(self):
     # Calling `compat.to_unicode` with a `bytearray` containing unicode """
     res = to_unicode(bytearray('\xff', 'utf-8'))
     eq_(type(res), str)
     eq_(res, 'ÿ')
Ejemplo n.º 43
0
 def test_to_unicode_string(self):
     # Calling `compat.to_unicode` on a non-unicode string
     res = to_unicode('test')
     eq_(type(res), unicode)
     eq_(res, 'test')