Skip to content

Commit

Permalink
Add test, fix lint for django user error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
c24t committed Apr 8, 2019
1 parent b1c3fec commit 0ce478a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ def _set_django_attributes(span, request):
try:
user_name = django_user.get_username()
except AttributeError:
# AnonymousUser in some older versions of Django doesn't implement get_username()
# AnonymousUser in some older versions of Django doesn't implement
# get_username
return

# User id is the django autofield for User model as the primary key
Expand Down
38 changes: 38 additions & 0 deletions contrib/opencensus-ext-django/tests/test_django_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,44 @@ def test_process_response(self):

self.assertEqual(span.attributes, expected_attributes)

def test_process_response_no_get_username(self):
from opencensus.ext.django import middleware

trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
span_id = '6e0c63257de34c92'
django_trace_id = '{}/{}'.format(trace_id, span_id)

django_request = RequestFactory().get('/', **{
google_cloud_format._TRACE_CONTEXT_HEADER_NAME: django_trace_id})

middleware_obj = middleware.OpencensusMiddleware()

middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()

exporter_mock = mock.Mock()
tracer.exporter = exporter_mock

django_response = mock.Mock()
django_response.status_code = 200

expected_attributes = {
'http.url': u'/',
'http.method': 'GET',
'http.status_code': '200',
}

mock_user = mock.Mock()
mock_user.pk = 123
mock_user.get_username.side_effect = AttributeError
django_request.user = mock_user

middleware_obj.process_response(django_request, django_response)

self.assertEqual(span.attributes, expected_attributes)


def test_process_response_unfinished_child_span(self):
from opencensus.ext.django import middleware

Expand Down

0 comments on commit 0ce478a

Please sign in to comment.