django-server-errors 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
errors/middleware.py ADDED
@@ -0,0 +1,30 @@
1
+ from .recorder import record_request
2
+
3
+ EXCEPTION_ATTRIBUTE = '_error_exception'
4
+
5
+
6
+ def remember_exception(request, exception, replace=True):
7
+ if replace or getattr(request, EXCEPTION_ATTRIBUTE, None) is None:
8
+ setattr(request, EXCEPTION_ATTRIBUTE, exception)
9
+
10
+
11
+ class ErrorCaptureMiddleware:
12
+ """
13
+ Records responses with 5xx status into errors.Error. Comes first, so that it also sees the 500 Django makes of an
14
+ exception in another middleware. The exception of a view is taken in process_exception, the one of a middleware
15
+ in the got_request_exception receiver, see signals.
16
+ """
17
+ def __init__(self, get_response):
18
+ self.get_response = get_response
19
+
20
+ def __call__(self, request):
21
+ response = self.get_response(request)
22
+ # popped in any case, the exception's frames refer to the request
23
+ exception = request.__dict__.pop(EXCEPTION_ATTRIBUTE, None)
24
+ if response.status_code >= 500:
25
+ record_request(request, response, exception)
26
+ return response
27
+
28
+ def process_exception(self, request, exception):
29
+ remember_exception(request, exception)
30
+ return None
@@ -0,0 +1,54 @@
1
+ # Generated by Django 6.1.1 on 2026-11-09 09:22
2
+
3
+ import django.db.models.deletion
4
+ import django.utils.timezone
5
+ from django.db import migrations, models
6
+
7
+
8
+ class Migration(migrations.Migration):
9
+
10
+ initial = True
11
+
12
+ dependencies = [
13
+ ]
14
+
15
+ operations = [
16
+ migrations.CreateModel(
17
+ name='Error',
18
+ fields=[
19
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
20
+ ('fingerprint', models.CharField(editable=False, max_length=64, unique=True, verbose_name='fingerprint')),
21
+ ('kind', models.CharField(choices=[('request', 'Request'), ('task', 'Celery task')], max_length=16, verbose_name='kind')),
22
+ ('name', models.CharField(help_text='Exception class or response status', max_length=255, verbose_name='error')),
23
+ ('message', models.TextField(blank=True, help_text='The latest one', verbose_name='message')),
24
+ ('source', models.CharField(help_text='API route, Django view or Celery task', max_length=255, verbose_name='source')),
25
+ ('location', models.CharField(blank=True, max_length=255, verbose_name='location in code')),
26
+ ('first_seen', models.DateTimeField(default=django.utils.timezone.now, verbose_name='first seen')),
27
+ ('last_seen', models.DateTimeField(db_index=True, default=django.utils.timezone.now, verbose_name='last seen')),
28
+ ('count', models.PositiveIntegerField(default=1, verbose_name='count')),
29
+ ('severity', models.PositiveSmallIntegerField(choices=[(10, 'Low'), (20, 'Medium'), (30, 'High'), (40, 'Critical')], default=20, verbose_name='severity')),
30
+ ],
31
+ options={
32
+ 'verbose_name': 'error',
33
+ 'verbose_name_plural': 'errors',
34
+ 'ordering': ['-last_seen'],
35
+ },
36
+ ),
37
+ migrations.CreateModel(
38
+ name='ErrorTrace',
39
+ fields=[
40
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
41
+ ('created', models.DateTimeField(default=django.utils.timezone.now, verbose_name='time')),
42
+ ('message', models.TextField(blank=True, verbose_name='message')),
43
+ ('traceback', models.TextField(blank=True, verbose_name='traceback')),
44
+ ('frames', models.JSONField(blank=True, default=list, verbose_name='stack')),
45
+ ('context', models.JSONField(blank=True, default=dict, verbose_name='context')),
46
+ ('error', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='traces', to='errors.error', verbose_name='error')),
47
+ ],
48
+ options={
49
+ 'verbose_name': 'occurrence',
50
+ 'verbose_name_plural': 'occurrences',
51
+ 'ordering': ['-created'],
52
+ },
53
+ ),
54
+ ]
File without changes
errors/models.py ADDED
@@ -0,0 +1,65 @@
1
+ from datetime import timedelta
2
+
3
+ from django.db import models
4
+ from django.utils import timezone
5
+ from django.utils.translation import gettext, gettext_lazy as _
6
+
7
+
8
+ class Error(models.Model):
9
+ """
10
+ Server errors of one kind: the same exception raised at the same place of the code for the same view or task.
11
+ Messages, parameters and the rest of the stack may differ, see recorder.
12
+ """
13
+ class Kind(models.TextChoices):
14
+ REQUEST = 'request', _('Request')
15
+ TASK = 'task', _('Celery task')
16
+
17
+ class Severity(models.IntegerChoices):
18
+ LOW = 10, _('Low')
19
+ MEDIUM = 20, _('Medium')
20
+ HIGH = 30, _('High')
21
+ CRITICAL = 40, _('Critical')
22
+
23
+ fingerprint = models.CharField(_('fingerprint'), max_length=64, unique=True, editable=False)
24
+ kind = models.CharField(_('kind'), max_length=16, choices=Kind)
25
+ name = models.CharField(_('error'), max_length=255, help_text=_('Exception class or response status'))
26
+ message = models.TextField(_('message'), blank=True, help_text=_('The latest one'))
27
+ source = models.CharField(_('source'), max_length=255, help_text=_('API route, Django view or Celery task'))
28
+ location = models.CharField(_('location in code'), max_length=255, blank=True)
29
+ first_seen = models.DateTimeField(_('first seen'), default=timezone.now)
30
+ last_seen = models.DateTimeField(_('last seen'), default=timezone.now, db_index=True)
31
+ count = models.PositiveIntegerField(_('count'), default=1)
32
+ severity = models.PositiveSmallIntegerField(_('severity'), choices=Severity, default=Severity.MEDIUM)
33
+
34
+ class Meta:
35
+ verbose_name = _('error')
36
+ verbose_name_plural = _('errors')
37
+ ordering = ['-last_seen']
38
+
39
+ def __str__(self):
40
+ return gettext('%(name)s in %(source)s') % {'name': self.name, 'source': self.source}
41
+
42
+ @property
43
+ def frequency(self):
44
+ """ Occurrences per day since the first one, counting at least a day """
45
+ days = max((timezone.now() - self.first_seen) / timedelta(days=1), 1)
46
+ return self.count / days
47
+
48
+
49
+ class ErrorTrace(models.Model):
50
+ """ One occurrence of an error, only the latest ones are kept """
51
+ error = models.ForeignKey(Error, on_delete=models.CASCADE, related_name='traces', verbose_name=_('error'))
52
+ created = models.DateTimeField(_('time'), default=timezone.now)
53
+ message = models.TextField(_('message'), blank=True)
54
+ traceback = models.TextField(_('traceback'), blank=True)
55
+ # [{file, function, lineno, in_app, lines: [[number, text]], vars: [[name, repr]], cause, cause_explicit}]
56
+ frames = models.JSONField(_('stack'), default=list, blank=True)
57
+ context = models.JSONField(_('context'), default=dict, blank=True)
58
+
59
+ class Meta:
60
+ verbose_name = _('occurrence')
61
+ verbose_name_plural = _('occurrences')
62
+ ordering = ['-created']
63
+
64
+ def __str__(self):
65
+ return timezone.localtime(self.created).strftime('%Y-%m-%d %H:%M:%S')
errors/recorder.py ADDED
@@ -0,0 +1,236 @@
1
+ """
2
+ Records server errors into Error groups with their latest ErrorTrace.
3
+
4
+ An error is grouped by its kind, exception class, source (view or task) and location: the innermost frame of the
5
+ project code, without the line number. Messages, parameters and the rest of the stack may differ within a group.
6
+ Project code is any code outside the standard library and installed packages.
7
+
8
+ Recording never raises: a failure is logged, the response or the task goes on as it would without it.
9
+ """
10
+ import hashlib
11
+ import logging
12
+ import os
13
+ import sys
14
+ import sysconfig
15
+ import traceback
16
+
17
+ from django.conf import settings
18
+ from django.db import transaction
19
+ from django.db.models import F, QuerySet
20
+ from django.http import HttpRequest
21
+ from django.template.defaultfilters import pprint
22
+ from django.urls import resolve
23
+ from django.utils import timezone
24
+ from django.utils.functional import LazyObject, empty
25
+ from django.views.debug import ExceptionReporter, get_exception_reporter_filter
26
+
27
+ from .models import Error, ErrorTrace
28
+
29
+ try:
30
+ from rest_framework.request import Request
31
+ REQUEST_CLASSES = (HttpRequest, Request)
32
+ except ImportError: # Django REST framework is optional
33
+ REQUEST_CLASSES = (HttpRequest,)
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ MAX_TRACES = 10 # per error by default, see ERRORS_MAX_TRACES; with the locals a trace takes tens of kilobytes
38
+ MAX_MESSAGE_LENGTH = 10000
39
+ MAX_VALUE_LENGTH = 4096 # of a variable, as on the debug page
40
+ LIBRARY_DIRS = tuple(f'{os.sep}{name}{os.sep}' for name in ('site-packages', 'dist-packages'))
41
+ STDLIB_DIRS = tuple({os.path.join(sysconfig.get_path(name), '') for name in ('stdlib', 'platstdlib')})
42
+
43
+
44
+ def record_request(request, response, exception=None):
45
+ """ Records a response with 5xx status, and the exception it was made of if there was one """
46
+ try:
47
+ if exception is not None:
48
+ details = describe_exception(exception, exception.__traceback__, request)
49
+ else:
50
+ # such as an APIException, which DRF turns into a response itself
51
+ data = getattr(response, 'data', None)
52
+ message = str(data['detail']) if isinstance(data, dict) and 'detail' in data else response.reason_phrase
53
+ details = {'name': f'HTTP {response.status_code}', 'message': message}
54
+ record(Error.Kind.REQUEST, request_source(request), context=request_context(request, response), **details)
55
+ except Exception:
56
+ logger.exception('Could not record the error of %s %s', request.method, request.path)
57
+
58
+
59
+ def record_task(task, task_id, exception, tb):
60
+ """ Records a Celery task that failed. Its arguments are in the locals of its frame. """
61
+ try:
62
+ request = getattr(task, 'request', None)
63
+ context = {
64
+ 'task_id': task_id,
65
+ 'retries': getattr(request, 'retries', None),
66
+ 'hostname': getattr(request, 'hostname', None),
67
+ }
68
+ record(Error.Kind.TASK, task.name, context=context, **describe_exception(exception, tb))
69
+ except Exception:
70
+ logger.exception('Could not record the failure of task %s', task_id)
71
+
72
+
73
+ def record(kind, source, name, message='', location='', traceback_text='', frames=(), context=None):
74
+ message = message[:MAX_MESSAGE_LENGTH]
75
+ name, source, location = name[:255], source[:255], location[:255]
76
+ fingerprint = hashlib.sha256('\n'.join((kind, name, source, location)).encode()).hexdigest()
77
+ now = timezone.now()
78
+ with transaction.atomic():
79
+ error, created = Error.objects.get_or_create(fingerprint=fingerprint, defaults={
80
+ 'kind': kind, 'name': name, 'message': without_nul(message), 'source': source, 'location': location,
81
+ 'first_seen': now, 'last_seen': now,
82
+ })
83
+ if not created:
84
+ Error.objects.filter(pk=error.pk).update(count=F('count') + 1, last_seen=now, message=without_nul(message))
85
+ ErrorTrace.objects.create(
86
+ error=error, created=now, message=without_nul(message), traceback=without_nul(traceback_text),
87
+ frames=without_nul(list(frames)), context=without_nul(context or {}),
88
+ )
89
+ limit = getattr(settings, 'ERRORS_MAX_TRACES', MAX_TRACES)
90
+ stale = error.traces.order_by('-created', '-pk').values_list('pk', flat=True)[limit:]
91
+ ErrorTrace.objects.filter(pk__in=list(stale)).delete()
92
+ return error
93
+
94
+
95
+ def describe_exception(exception, tb, request=None):
96
+ try:
97
+ message = str(exception)
98
+ except Exception:
99
+ message = '<message not available>'
100
+ return {
101
+ 'name': exception_name(exception),
102
+ 'message': message,
103
+ 'location': find_location(tb),
104
+ 'traceback_text': ''.join(traceback.format_exception(type(exception), exception, tb)),
105
+ 'frames': collect_frames(exception, tb, request),
106
+ }
107
+
108
+
109
+ def exception_name(exception):
110
+ cls = type(exception)
111
+ return cls.__qualname__ if cls.__module__ == 'builtins' else f'{cls.__module__}.{cls.__qualname__}'
112
+
113
+
114
+ def find_location(tb):
115
+ """ The innermost frame of the project code, or the innermost one if the project has none """
116
+ frames = [frame for frame, _ in traceback.walk_tb(tb)]
117
+ if not frames:
118
+ return ''
119
+ frame = ([frame for frame in frames if is_project_file(frame.f_code.co_filename)] or frames)[-1]
120
+ return f'{short_path(frame.f_code.co_filename)} in {frame.f_code.co_qualname}'
121
+
122
+
123
+ def is_project_file(filename):
124
+ """ Not of the standard library or an installed package. A virtualenv may lie inside the project. """
125
+ return (
126
+ not filename.startswith('<') # such as <frozen importlib._bootstrap>
127
+ and not filename.startswith(STDLIB_DIRS)
128
+ and not any(name in filename for name in LIBRARY_DIRS)
129
+ )
130
+
131
+
132
+ def short_path(filename):
133
+ """ Relative to the sys.path entry it is imported from: shop/models.py, django/views/debug.py """
134
+ roots = [os.path.join(os.path.abspath(entry), '') for entry in sys.path if isinstance(entry, str)]
135
+ root = max((root for root in roots if filename.startswith(root)), key=len, default='')
136
+ return filename[len(root):]
137
+
138
+
139
+ def collect_frames(exception, tb, request=None):
140
+ """
141
+ The frames of the exception and its causes, as on Django's debug page. ExceptionReporter takes care of
142
+ @sensitive_variables and request.POST, names that look sensitive, such as password or token, are masked here.
143
+ """
144
+ reporter = ExceptionReporter(request, type(exception), exception, tb)
145
+ frames = []
146
+ for frame in reporter.get_traceback_frames():
147
+ if frame.get('tb') is None:
148
+ continue
149
+ first = frame['pre_context_lineno']
150
+ lines = frame['pre_context'] + [frame['context_line']] + frame['post_context']
151
+ cause = frame['exc_cause']
152
+ frames.append({
153
+ 'file': short_path(frame['filename']),
154
+ 'function': frame['function'],
155
+ 'lineno': frame['lineno'],
156
+ 'in_app': is_project_file(frame['filename']),
157
+ 'lines': [[first + index, line] for index, line in enumerate(lines)],
158
+ 'vars': [[name, format_value(reporter.filter, name, value)] for name, value in frame['vars']],
159
+ 'cause': f'{exception_name(cause)}: {cause}' if cause is not None else None,
160
+ 'cause_explicit': bool(frame['exc_cause_explicit']),
161
+ })
162
+ return frames
163
+
164
+
165
+ def format_value(reporter_filter, name, value):
166
+ try:
167
+ value = reporter_filter.cleanse_setting(name, value)
168
+ if isinstance(value, str) and value == reporter_filter.cleansed_substitute:
169
+ return value
170
+ if isinstance(value, QuerySet) and value._result_cache is None:
171
+ return f'<QuerySet of {value.model.__name__}, not evaluated>'
172
+ if isinstance(value, REQUEST_CLASSES):
173
+ # their repr has the query string, which may hold a token; the context has it masked
174
+ return f'<{type(value).__name__}: {value.method} {value.path!r}>'
175
+ text = pprint(value)
176
+ except Exception as e:
177
+ return f'Error in formatting: {e.__class__.__name__}: {e}'
178
+ if len(text) > MAX_VALUE_LENGTH:
179
+ text = '%s… <trimmed %d bytes string>' % (text[:MAX_VALUE_LENGTH], len(text))
180
+ return text
181
+
182
+
183
+ def request_source(request):
184
+ """ The method and the URL name, Django falls back to the view's dotted path for unnamed ones """
185
+ match = resolver_match(request)
186
+ return f'{request.method} {match.view_name if match is not None else request.path}'
187
+
188
+
189
+ def resolver_match(request):
190
+ match = getattr(request, 'resolver_match', None)
191
+ if match is None: # the error came before the URL was resolved
192
+ try:
193
+ match = resolve(request.path_info, getattr(request, 'urlconf', None))
194
+ except Exception:
195
+ match = None
196
+ return match
197
+
198
+
199
+ def request_context(request, response):
200
+ match = resolver_match(request)
201
+ reporter_filter = get_exception_reporter_filter(request)
202
+ return {
203
+ 'method': request.method,
204
+ 'path': request.path,
205
+ 'query': {
206
+ key: reporter_filter.cleanse_setting(key, values[0] if len(values) == 1 else values)
207
+ for key, values in request.GET.lists()
208
+ },
209
+ 'status': response.status_code,
210
+ 'view': match._func_path if match is not None else None,
211
+ 'route': match.route if match is not None else None,
212
+ 'site': getattr(getattr(request, 'site', None), 'domain', None),
213
+ 'user': user_id(request),
214
+ 'ip': request.META.get('REMOTE_ADDR'),
215
+ }
216
+
217
+
218
+ def user_id(request):
219
+ """ Only a user known by now, so that recording does not load the session """
220
+ user = getattr(request, 'user', None)
221
+ if isinstance(user, LazyObject):
222
+ if user._wrapped is empty:
223
+ return None
224
+ user = user._wrapped
225
+ return user.pk if getattr(user, 'is_authenticated', False) else None
226
+
227
+
228
+ def without_nul(value):
229
+ """ PostgreSQL rejects NUL in text and JSON, and it comes in query strings of bots """
230
+ if isinstance(value, str):
231
+ return value.replace('\x00', '\\x00')
232
+ if isinstance(value, dict):
233
+ return {without_nul(key): without_nul(item) for key, item in value.items()}
234
+ if isinstance(value, (list, tuple)):
235
+ return [without_nul(item) for item in value]
236
+ return value
errors/signals.py ADDED
@@ -0,0 +1,35 @@
1
+ import sys
2
+
3
+ from django.core.signals import got_request_exception
4
+ from django.dispatch import receiver
5
+
6
+ from .middleware import remember_exception
7
+ from .recorder import record_task
8
+
9
+ try:
10
+ from celery.signals import task_failure
11
+ except ImportError: # Celery is optional
12
+ task_failure = None
13
+
14
+
15
+ @receiver(got_request_exception)
16
+ def exception_raised(sender, request=None, **kwargs):
17
+ """
18
+ Django sends it for every exception it turns into a 500, inside the except block. process_exception of
19
+ ErrorCaptureMiddleware sees only the exceptions of views, this one also those of middlewares.
20
+ """
21
+ if request is not None:
22
+ remember_exception(request, sys.exc_info()[1], replace=False)
23
+
24
+
25
+ def task_failed(sender=None, task_id=None, exception=None, traceback=None, **kwargs):
26
+ """
27
+ Sent when a task fails for good, not when it is retried. Celery clears the traceback right after it, so the
28
+ frames are read here.
29
+ """
30
+ if sender is not None and exception is not None:
31
+ record_task(sender, task_id, exception, traceback)
32
+
33
+
34
+ if task_failure is not None:
35
+ task_failure.connect(task_failed, weak=False, dispatch_uid='errors.task_failed')
@@ -0,0 +1,28 @@
1
+ {% load i18n %}{# Frames of ErrorTrace.frames, as on Django's debug page: the project ones are open, those of libraries closed #}
2
+ {% for frame in frames %}
3
+ {% ifchanged frame.cause %}{% if frame.cause %}
4
+ <p style="margin: 12px 0 8px; font-weight: bold">
5
+ {% if frame.cause_explicit %}
6
+ {% blocktranslate trimmed with cause=frame.cause %}The above exception ({{ cause }}) was the direct cause of the following exception:{% endblocktranslate %}
7
+ {% else %}
8
+ {% blocktranslate trimmed with cause=frame.cause %}During handling of the above exception ({{ cause }}), another exception occurred:{% endblocktranslate %}
9
+ {% endif %}
10
+ </p>
11
+ {% endif %}{% endifchanged %}
12
+ <details{% if frame.in_app %} open{% endif %} style="margin: 0 0 6px">
13
+ <summary>{% blocktranslate trimmed with file=frame.file line=frame.lineno function=frame.function %}<code>{{ file }}</code>, line {{ line }}, in <code>{{ function }}</code>{% endblocktranslate %}</summary>
14
+ <pre style="margin: 4px 0; padding: 4px 0; background: var(--darkened-bg); overflow-x: auto">{% for number, line in frame.lines %}<span style="display: block{% if number == frame.lineno %}; background: var(--message-warning-bg); font-weight: bold{% endif %}">{{ number|stringformat:"5d" }} {{ line }}</span>{% endfor %}</pre>
15
+ {% if frame.vars %}
16
+ <table style="width: 100%; margin-bottom: 8px">
17
+ <thead><tr><th style="width: 15%">{% translate "Variable" %}</th><th>{% translate "Value" %}</th></tr></thead>
18
+ <tbody>
19
+ {% for name, value in frame.vars %}
20
+ <tr><td><code>{{ name }}</code></td><td><pre style="margin: 0; white-space: pre-wrap; word-break: break-all">{{ value }}</pre></td></tr>
21
+ {% endfor %}
22
+ </tbody>
23
+ </table>
24
+ {% endif %}
25
+ </details>
26
+ {% empty %}
27
+ <p>{% translate "None: the response came without an exception" %}</p>
28
+ {% endfor %}
@@ -0,0 +1,9 @@
1
+ """
2
+ Tests of the errors app. In a project that has it installed:
3
+
4
+ python manage.py test errors
5
+
6
+ Without a project, on SQLite, in the repository's root:
7
+
8
+ python -m django test errors --settings=errors.tests.settings
9
+ """
errors/tests/mixins.py ADDED
@@ -0,0 +1,22 @@
1
+ import os
2
+ from unittest import mock
3
+
4
+ from errors import recorder
5
+
6
+ TESTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '')
7
+
8
+
9
+ def is_project_or_test_file(filename, is_project_file=recorder.is_project_file):
10
+ return is_project_file(filename) or filename.startswith(TESTS_DIR)
11
+
12
+
13
+ class TestsAreProjectCode:
14
+ """
15
+ The views and tasks of the tests stand for project code. When the package
16
+ is installed they are in site-packages, which the recorder skips.
17
+ """
18
+ def setUp(self):
19
+ patcher = mock.patch.object(recorder, 'is_project_file', is_project_or_test_file)
20
+ patcher.start()
21
+ self.addCleanup(patcher.stop)
22
+ super().setUp()
@@ -0,0 +1,45 @@
1
+ """
2
+ Settings to run the tests without a project, see __init__.py
3
+ """
4
+ SECRET_KEY = 'tests'
5
+ USE_TZ = True
6
+
7
+ DATABASES = {
8
+ 'default': {
9
+ 'ENGINE': 'django.db.backends.sqlite3',
10
+ 'NAME': ':memory:',
11
+ },
12
+ }
13
+
14
+ INSTALLED_APPS = [
15
+ 'django.contrib.admin',
16
+ 'django.contrib.auth',
17
+ 'django.contrib.contenttypes',
18
+ 'django.contrib.sessions',
19
+ 'django.contrib.messages',
20
+ 'errors',
21
+ ]
22
+
23
+ MIDDLEWARE = [
24
+ 'errors.middleware.ErrorCaptureMiddleware',
25
+ 'django.contrib.sessions.middleware.SessionMiddleware',
26
+ 'django.middleware.common.CommonMiddleware',
27
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
28
+ 'django.contrib.messages.middleware.MessageMiddleware',
29
+ ]
30
+
31
+ ROOT_URLCONF = 'errors.tests.urls'
32
+
33
+ TEMPLATES = [
34
+ {
35
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
36
+ 'APP_DIRS': True,
37
+ 'OPTIONS': {
38
+ 'context_processors': [
39
+ 'django.template.context_processors.request',
40
+ 'django.contrib.auth.context_processors.auth',
41
+ 'django.contrib.messages.context_processors.messages',
42
+ ],
43
+ },
44
+ },
45
+ ]
@@ -0,0 +1,42 @@
1
+ from django.contrib.admin import AdminSite
2
+ from django.contrib.auth import get_user_model
3
+ from django.test import Client, RequestFactory, TestCase, override_settings
4
+ from django.utils import translation
5
+
6
+ from errors.admin import ErrorAdmin
7
+ from errors.models import Error
8
+ from errors.tests.mixins import TestsAreProjectCode
9
+
10
+ MASK = '********************'
11
+
12
+
13
+ @override_settings(ROOT_URLCONF='errors.tests.urls')
14
+ class AdminTests(TestsAreProjectCode, TestCase):
15
+ def setUp(self):
16
+ super().setUp()
17
+ Client(raise_request_exception=False).get('/boom/?password=hunter2')
18
+ self.error = Error.objects.get()
19
+ self.model_admin = ErrorAdmin(Error, AdminSite())
20
+
21
+ def get(self, view, *args):
22
+ request = RequestFactory().get('/admin/errors/error/')
23
+ request.user = get_user_model()(is_active=True, is_staff=True, is_superuser=True)
24
+ return view(request, *args).render()
25
+
26
+ def test_pages(self):
27
+ self.assertContains(self.get(self.model_admin.changelist_view), 'errors/tests/urls.py in boom')
28
+ page = self.get(self.model_admin.change_view, str(self.error.pk))
29
+ self.assertContains(page, '<details open')
30
+ self.assertContains(page, 'raise ValueError')
31
+ self.assertContains(page, MASK)
32
+ self.assertNotContains(page, 'hunter2')
33
+
34
+ def test_translations(self):
35
+ for language, texts in (
36
+ ('en', ['Kind', 'Frequency, per day', 'Variable', 'line', 'ValueError in GET boom']),
37
+ ('ru', ['Вид', 'Частота, в день', 'Переменная', 'строка', 'ValueError в GET boom']),
38
+ ):
39
+ with translation.override(language):
40
+ page = self.get(self.model_admin.change_view, str(self.error.pk))
41
+ for text in texts:
42
+ self.assertContains(page, text, msg_prefix=language)