Skip to content
This repository was archived by the owner on Sep 17, 2025. It is now read-only.

Commit 5757306

Browse files
committed
WIP Django DB instrumentation tests
1 parent 65567c1 commit 5757306

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Copyright 2017, OpenCensus Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import unittest
16+
from collections import namedtuple
17+
18+
import django
19+
import mock
20+
import pytest
21+
from django.test.utils import teardown_test_environment
22+
23+
from opencensus.trace import execution_context
24+
from opencensus.trace.tracers.noop_tracer import NoopTracer
25+
26+
27+
class TestOpencensusDatabaseMiddleware(unittest.TestCase):
28+
def setUp(self):
29+
from django.conf import settings as django_settings
30+
from django.test.utils import setup_test_environment
31+
32+
33+
if not django_settings.configured:
34+
django_settings.configure()
35+
setup_test_environment()
36+
37+
def tearDown(self):
38+
execution_context.clear()
39+
teardown_test_environment()
40+
41+
def test_process_request(self):
42+
if django.VERSION < (2, 0):
43+
pytest.skip("Wrong version of Django")
44+
45+
from opencensus.trace.ext.django import middleware
46+
47+
tracer = middleware._get_current_tracer()
48+
span = tracer.current_span()
49+
50+
sql = "SELECT * FROM users"
51+
52+
MockConnection = namedtuple('Connection', ('vendor'))
53+
connection = MockConnection('mysql')
54+
55+
mock_execute = mock.Mock()
56+
mock_execute.return_value = "Mock result"
57+
58+
middleware_obj = middleware.OpencensusMiddleware()
59+
60+
result = middleware_obj._trace_db_call(
61+
mock_execute, sql, params=[], many=False,
62+
context={'connection': connection})
63+
64+
mock_sql, mock_params, mock_many, mock_context = mock_execute.call_args[0]
65+
66+
self.assertEqual(mock_sql, sql)
67+
self.assertEqual(mock_params, [])
68+
self.assertEqual(mock_many, False)
69+
self.assertEqual(mock_context, {'connection': connection})
70+
self.assertEqual(result, "Mock result")
71+
72+
result = middleware_obj._trace_db_call(
73+
mock_execute, sql, params=[], many=True,
74+
context={'connection': connection})
75+
76+
mock_sql, mock_params, mock_many, mock_context = mock_execute.call_args[0]
77+
self.assertEqual(mock_many, True)

0 commit comments

Comments
 (0)