Esempio n. 1
0
    def test_insert_overflow(self):

        lru = LRUCache(4)

        for x in range(6):
            lru.set(x)

        self.assertNotIn(1, lru)
        for x in range(2, 6):
            self.assertIn(x, lru)
Esempio n. 2
0
    def test_insert_overflow(self):

        lru = LRUCache(4)

        for x in range(6):
            lru.set(x)

        self.assertFalse(lru.has_key(1))
        for x in range(2, 6):
            self.assertTrue(lru.has_key(x))
Esempio n. 3
0
def test_stacktrace_filtered_for_opbeat():
    client = TestClient()
    opbeat = get_client()
    instrumentation.control.instrument(opbeat)

    # Clear the LRU frame cache
    Transaction._lrucache = LRUCache(maxsize=5000)

    with mock.patch(
            "opbeat.traces.RequestsStore.should_collect") as should_collect:
        should_collect.return_value = False
        with override_settings(MIDDLEWARE_CLASSES=[
            'opbeat.contrib.django.middleware.OpbeatAPMMiddleware']):
            resp = client.get(reverse("render-heavy-template"))
    assert resp.status_code == 200

    transactions, traces = opbeat.instrumentation_store.get_all()

    expected_signatures = ['transaction', 'list_users.html',
                           'something_expensive']

    # Reorder according to the kinds list so we can just test them
    sig_dict = dict([(t['signature'], t) for t in traces])
    traces = [sig_dict[k] for k in expected_signatures]

    assert traces[1]['signature'] == 'list_users.html'
    frames = traces[1]['extra']['_frames']

    # Top frame should be inside django rendering
    assert frames[0]['module'].startswith('django.template')
Esempio n. 4
0
def test_stacktraces_have_templates():
    client = TestClient()
    opbeat = get_client()
    instrumentation.control.instrument()

    # Clear the LRU frame cache
    Transaction._lrucache = LRUCache(maxsize=5000)

    # only Django 1.9+ have the necessary information stored on Node/Template
    # instances when TEMPLATE_DEBUG = False

    TEMPLATE_DEBUG = django.VERSION < (1, 9)

    with mock.patch(
            "opbeat.traces.RequestsStore.should_collect") as should_collect:
        should_collect.return_value = False
        TEMPLATES_copy = deepcopy(settings.TEMPLATES)
        TEMPLATES_copy[0]['OPTIONS']['debug'] = TEMPLATE_DEBUG
        with override_settings(MIDDLEWARE_CLASSES=[
                'opbeat.contrib.django.middleware.OpbeatAPMMiddleware'
        ],
                               TEMPLATE_DEBUG=TEMPLATE_DEBUG,
                               TEMPLATES=TEMPLATES_copy):
            resp = client.get(reverse("render-heavy-template"))
    assert resp.status_code == 200

    transactions, traces = opbeat.instrumentation_store.get_all()
    assert len(transactions) == 1
    assert len(traces) == 3, [t["signature"] for t in traces]

    expected_signatures = [
        'transaction', 'list_users.html', 'something_expensive'
    ]

    assert set([t['signature'] for t in traces]) == set(expected_signatures)

    # Reorder according to the kinds list so we can just test them
    sig_dict = dict([(t['signature'], t) for t in traces])
    traces = [sig_dict[k] for k in expected_signatures]

    assert traces[2]['signature'] == 'something_expensive'

    # Find the template
    for frame in traces[2]['extra']['_frames']:
        if frame['lineno'] == 4 and frame['filename'].endswith(
                'django/testapp/templates/list_users.html'):
            break
    else:
        assert False is True, "Template was not found"
Esempio n. 5
0
    def test_insert_overflow(self):

        lru = LRUCache(4)

        for x in range(6):
            lru.set(x)

        self.assertFalse(lru.has_key(1))
        for x in range(2, 6):
            self.assertTrue(lru.has_key(x))
Esempio n. 6
0
class Transaction(object):
    _lrucache = LRUCache(maxsize=5000)

    def __init__(self, get_frames, kind="custom"):
        self.id = uuid.uuid4()
        self.timestamp = datetime.datetime.utcnow()
        self.start_time = _time_func()
        self.name = None
        self.duration = None
        self.result = None
        self.kind = kind
        self.get_frames = get_frames

        self.traces = []
        self.trace_stack = []
        self.ignore_subtree = False
        self.extra = {}

        self._trace_counter = 0

        # The transaction is a trace as well
        self.begin_trace("transaction", "transaction")

    def end_transaction(self, skip_frames=8):
        # End the "transaction" trace started above
        self.duration = _time_func() - self.start_time
        return self.end_trace(skip_frames)

    def begin_trace(self, name, trace_type, context=None, leaf=False):
        # If we were already called with `leaf=True`, we'll just push
        # a placeholder on the stack.
        if self.ignore_subtree:
            self.trace_stack.append(None)
            return None

        if leaf:
            self.ignore_subtree = True

        start = _time_func() - self.start_time
        trace = Trace(self._trace_counter, name, trace_type, start, context)
        self._trace_counter += 1
        self.trace_stack.append(trace)
        return trace

    def end_trace(self, skip_frames):
        trace = self.trace_stack.pop()
        if trace is None:
            return None

        self.ignore_subtree = False

        trace.duration = _time_func() - trace.start_time - self.start_time

        if self.trace_stack:
            trace.parent = self.trace_stack[-1].idx

        trace.frames = self.get_frames()[skip_frames:]
        self.traces.append(trace)

        return trace

    def to_dict(self):
        return {
            'id': str(self.id),
            'name': self.name,
            'type': self.kind,
            'duration': self.duration * 1000,  # milliseconds
            'result': str(self.result),
            'timestamp': self.timestamp.strftime(defaults.TIMESTAMP_FORMAT),
            'context': self.extra,
            'traces': [
                trace_obj.to_dict() for trace_obj in self.traces
            ]
        }
Esempio n. 7
0
class Transaction(object):
    _lrucache = LRUCache(maxsize=5000)

    def __init__(self, start_time, get_frames):
        self.start_time = start_time
        self.transaction_traces = []
        self.trace_stack = []
        self.get_frames = get_frames
        self.ignore_subtree = False

        # The transaction is a trace as well
        self.begin_trace("transaction", "transaction")

    def end_transaction(self, skip_frames=8):
        # End the "transaction" trace started above
        return self.end_trace(skip_frames)

    def begin_trace(self, signature, kind, extra=None, leaf=False):
        # If we were already called with `leaf=True`, we'll just push
        # a placeholder on the stack.
        if self.ignore_subtree:
            self.trace_stack.append(None)
            return None

        if leaf:
            self.ignore_subtree = True

        abs_start = time.time()
        trace = Trace(signature, kind, abs_start, extra)
        self.trace_stack.append(trace)
        return trace

    def end_trace(self, skip_frames):
        trace = self.trace_stack.pop()
        if trace is None:
            return None

        self.ignore_subtree = False

        duration = (time.time() - trace.abs_start_time) * 1000

        if self.trace_stack:
            parent_start_time = self.trace_stack[-1].abs_start_time
        else:
            parent_start_time = 0.0
        rel_start_time = (trace.abs_start_time - parent_start_time) * 1000

        parents = [s.signature for s in self.trace_stack]

        trace.parents = tuple(parents)
        trace.trace_duration = duration
        trace.rel_start_time = rel_start_time

        if not self._lrucache.has_key(trace.fingerprint):
            self._lrucache.set(trace.fingerprint)
            frames = self.get_frames()[skip_frames:]
            trace.frames = frames

        self.transaction_traces.append(trace)

        return trace