aissue 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.
- aissue/__init__.py +5 -0
- aissue/apps.py +6 -0
- aissue/exceptions.py +13 -0
- aissue/middleware.py +143 -0
- aissue-1.0.0.dist-info/METADATA +180 -0
- aissue-1.0.0.dist-info/RECORD +11 -0
- aissue-1.0.0.dist-info/WHEEL +5 -0
- aissue-1.0.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +1 -0
- tests/test_middleware.py +278 -0
- tests/urls.py +15 -0
aissue/__init__.py
ADDED
aissue/apps.py
ADDED
aissue/exceptions.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
class AIssueError(Exception):
|
|
2
|
+
"""Base exception for AIssue middleware"""
|
|
3
|
+
pass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AIssueConfigurationError(AIssueError):
|
|
7
|
+
"""Raised when AIssue middleware is misconfigured"""
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AIssueAPIError(AIssueError):
|
|
12
|
+
"""Raised when there's an error communicating with AIssue API"""
|
|
13
|
+
pass
|
aissue/middleware.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import traceback
|
|
3
|
+
import requests
|
|
4
|
+
import logging
|
|
5
|
+
from django.conf import settings
|
|
6
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
7
|
+
from .exceptions import AIssueConfigurationError, AIssueAPIError
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AIssueMiddleware:
|
|
13
|
+
"""
|
|
14
|
+
Django middleware for logging errors to AIssue error monitoring service.
|
|
15
|
+
|
|
16
|
+
Configuration in settings.py:
|
|
17
|
+
AISSUE_API_KEY = 'your-api-key'
|
|
18
|
+
AISSUE_BASE_URL = 'https://your-aissue-instance.com' # optional
|
|
19
|
+
AISSUE_TIMEOUT = 5 # optional, default 5 seconds
|
|
20
|
+
AISSUE_ENABLED = True # optional, default True
|
|
21
|
+
AISSUE_LOG_IN_DEBUG = False # optional, allows logging in DEBUG mode
|
|
22
|
+
|
|
23
|
+
By default, errors are only logged when DEBUG = False.
|
|
24
|
+
Set AISSUE_LOG_IN_DEBUG = True to also log errors in DEBUG mode.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, get_response):
|
|
28
|
+
self.get_response = get_response
|
|
29
|
+
self._validate_config()
|
|
30
|
+
|
|
31
|
+
def _validate_config(self):
|
|
32
|
+
"""Validate AIssue configuration"""
|
|
33
|
+
self.api_key = getattr(settings, 'AISSUE_API_KEY', None)
|
|
34
|
+
if not self.api_key:
|
|
35
|
+
raise AIssueConfigurationError(
|
|
36
|
+
"AISSUE_API_KEY setting is required for AIssueMiddleware"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
self.base_url = getattr(settings, 'AISSUE_BASE_URL', 'https://app.aissue.com')
|
|
40
|
+
self.timeout = getattr(settings, 'AISSUE_TIMEOUT', 5)
|
|
41
|
+
self.enabled = getattr(settings, 'AISSUE_ENABLED', True)
|
|
42
|
+
self.log_in_debug = getattr(settings, 'AISSUE_LOG_IN_DEBUG', False)
|
|
43
|
+
|
|
44
|
+
# Check if we should log based on DEBUG setting
|
|
45
|
+
debug_mode = getattr(settings, 'DEBUG', False)
|
|
46
|
+
self.should_log = self.enabled and (not debug_mode or self.log_in_debug)
|
|
47
|
+
|
|
48
|
+
logger.info(f"AIssue middleware initialized: {self.base_url} (enabled: {self.should_log})")
|
|
49
|
+
|
|
50
|
+
def __call__(self, request):
|
|
51
|
+
"""Process the request and response"""
|
|
52
|
+
try:
|
|
53
|
+
response = self.get_response(request)
|
|
54
|
+
return response
|
|
55
|
+
except Exception as e:
|
|
56
|
+
if self.should_log:
|
|
57
|
+
try:
|
|
58
|
+
self._log_error(request, e)
|
|
59
|
+
except Exception as log_error:
|
|
60
|
+
# Never let error logging break the application
|
|
61
|
+
logger.warning(f"Failed to log error to AIssue: {log_error}")
|
|
62
|
+
raise # Re-raise the original exception
|
|
63
|
+
|
|
64
|
+
def process_exception(self, request, exception):
|
|
65
|
+
"""
|
|
66
|
+
Called when a view raises an exception.
|
|
67
|
+
This is the proper Django hook for exception handling.
|
|
68
|
+
Returns None to allow normal Django error handling to continue.
|
|
69
|
+
"""
|
|
70
|
+
if self.should_log:
|
|
71
|
+
try:
|
|
72
|
+
self._log_error(request, exception)
|
|
73
|
+
except Exception as e:
|
|
74
|
+
# Never let error logging break the application
|
|
75
|
+
logger.warning(f"Failed to log error to AIssue: {e}")
|
|
76
|
+
|
|
77
|
+
# Return None to let Django handle the exception normally
|
|
78
|
+
# This prevents duplicate processing and maintains Django's error flow
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
def _log_error(self, request, exception):
|
|
82
|
+
"""Send error data to AIssue"""
|
|
83
|
+
try:
|
|
84
|
+
error_data = self._extract_error_data(request, exception)
|
|
85
|
+
self._send_to_aissue(error_data)
|
|
86
|
+
logger.debug("Error successfully logged to AIssue")
|
|
87
|
+
except Exception as e:
|
|
88
|
+
raise AIssueAPIError(f"Failed to log error to AIssue: {e}")
|
|
89
|
+
|
|
90
|
+
def _extract_error_data(self, request, exception):
|
|
91
|
+
"""Extract relevant error information from request and exception"""
|
|
92
|
+
# Get request body
|
|
93
|
+
body = self._get_request_body(request)
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
'error_code': getattr(exception, 'status_code', 500),
|
|
97
|
+
'path': request.path,
|
|
98
|
+
'method': request.method,
|
|
99
|
+
'user_email': self._get_user_email(request),
|
|
100
|
+
'user_id': self._get_user_id(request),
|
|
101
|
+
'traceback': traceback.format_exc(),
|
|
102
|
+
'request_data': {
|
|
103
|
+
'GET': dict(request.GET),
|
|
104
|
+
'POST': dict(request.POST),
|
|
105
|
+
'body': body
|
|
106
|
+
},
|
|
107
|
+
'headers': dict(request.headers)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
def _get_request_body(self, request):
|
|
111
|
+
"""Safely extract request body"""
|
|
112
|
+
try:
|
|
113
|
+
body = request.body.decode('utf-8') if request.body else None
|
|
114
|
+
if body and 'application/json' in request.content_type.lower():
|
|
115
|
+
return json.loads(body)
|
|
116
|
+
return body
|
|
117
|
+
except (UnicodeDecodeError, json.JSONDecodeError, AttributeError):
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
def _get_user_email(self, request):
|
|
121
|
+
"""Safely get user email"""
|
|
122
|
+
if hasattr(request, 'user') and hasattr(request.user, 'email'):
|
|
123
|
+
return request.user.email
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
def _get_user_id(self, request):
|
|
127
|
+
"""Safely get user ID"""
|
|
128
|
+
if hasattr(request, 'user') and request.user.is_authenticated:
|
|
129
|
+
return str(request.user.id)
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
def _send_to_aissue(self, error_data):
|
|
133
|
+
"""Send error data to AIssue API"""
|
|
134
|
+
try:
|
|
135
|
+
response = requests.post(
|
|
136
|
+
f"{self.base_url.rstrip('/')}/api/errors/",
|
|
137
|
+
json=error_data,
|
|
138
|
+
headers={'X-API-Key': self.api_key},
|
|
139
|
+
timeout=self.timeout
|
|
140
|
+
)
|
|
141
|
+
response.raise_for_status()
|
|
142
|
+
except requests.RequestException as e:
|
|
143
|
+
raise Exception(f"AIssue API error: {e}")
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: aissue
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Django middleware for AIssue error monitoring
|
|
5
|
+
Home-page: https://github.com/aissue/aissue-django
|
|
6
|
+
Author: AIssue Team
|
|
7
|
+
Author-email: support@aissue.com
|
|
8
|
+
Project-URL: Bug Reports, https://github.com/aissue/aissue-django/issues
|
|
9
|
+
Project-URL: Source, https://github.com/aissue/aissue-django
|
|
10
|
+
Project-URL: Documentation, https://docs.aissue.com/django
|
|
11
|
+
Keywords: django middleware error monitoring aissue
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Framework :: Django
|
|
22
|
+
Classifier: Framework :: Django :: 3.2
|
|
23
|
+
Classifier: Framework :: Django :: 4.0
|
|
24
|
+
Classifier: Framework :: Django :: 4.1
|
|
25
|
+
Classifier: Framework :: Django :: 4.2
|
|
26
|
+
Requires-Python: >=3.8
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
Requires-Dist: Django>=3.2
|
|
29
|
+
Requires-Dist: requests>=2.25.0
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: pytest>=6.0; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest-django>=4.0; extra == "dev"
|
|
33
|
+
Requires-Dist: black>=21.0; extra == "dev"
|
|
34
|
+
Requires-Dist: flake8>=3.8; extra == "dev"
|
|
35
|
+
Dynamic: author
|
|
36
|
+
Dynamic: author-email
|
|
37
|
+
Dynamic: classifier
|
|
38
|
+
Dynamic: description
|
|
39
|
+
Dynamic: description-content-type
|
|
40
|
+
Dynamic: home-page
|
|
41
|
+
Dynamic: keywords
|
|
42
|
+
Dynamic: project-url
|
|
43
|
+
Dynamic: provides-extra
|
|
44
|
+
Dynamic: requires-dist
|
|
45
|
+
Dynamic: requires-python
|
|
46
|
+
Dynamic: summary
|
|
47
|
+
|
|
48
|
+
# AIssue Django Middleware
|
|
49
|
+
|
|
50
|
+
Easy Django error monitoring with AIssue. Automatically capture and send all unhandled exceptions to your AIssue dashboard for AI-powered analysis and resolution suggestions.
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install aissue-django
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Quick Setup
|
|
59
|
+
|
|
60
|
+
1. **Add to your Django settings:**
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
# settings.py
|
|
64
|
+
MIDDLEWARE = [
|
|
65
|
+
# ... your existing middleware
|
|
66
|
+
'aissue_django.middleware.AIssueMiddleware',
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
# Required: Your AIssue API key
|
|
70
|
+
AISSUE_API_KEY = 'your-api-key-here'
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
2. **Get your API key from your AIssue dashboard**
|
|
74
|
+
|
|
75
|
+
That's it! The middleware will now automatically capture all unhandled exceptions and send them to AIssue.
|
|
76
|
+
|
|
77
|
+
## Configuration Options
|
|
78
|
+
|
|
79
|
+
All configuration is optional except for `AISSUE_API_KEY`:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
# Required
|
|
83
|
+
AISSUE_API_KEY = 'your-api-key-here'
|
|
84
|
+
|
|
85
|
+
# Optional settings with defaults
|
|
86
|
+
AISSUE_BASE_URL = 'https://app.aissue.com' # Your AIssue instance URL
|
|
87
|
+
AISSUE_TIMEOUT = 5 # API request timeout in seconds
|
|
88
|
+
AISSUE_ENABLED = True # Enable/disable error logging
|
|
89
|
+
AISSUE_LOG_IN_DEBUG = False # Log errors even when DEBUG = True
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Debug Mode Behavior
|
|
93
|
+
|
|
94
|
+
By default, the middleware **only logs errors when `DEBUG = False`** (production mode). This prevents development errors from cluttering your production error logs.
|
|
95
|
+
|
|
96
|
+
To also log errors in development (when `DEBUG = True`), set:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
AISSUE_LOG_IN_DEBUG = True
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Features
|
|
103
|
+
|
|
104
|
+
- **Automatic Error Capture**: Catches all unhandled Django exceptions
|
|
105
|
+
- **Rich Context**: Captures request data, user info, headers, and full traceback
|
|
106
|
+
- **Non-Intrusive**: Won't break your app if AIssue is unreachable
|
|
107
|
+
- **Debug-Aware**: Respects Django's DEBUG setting
|
|
108
|
+
- **Configurable**: Easy to enable/disable and customize
|
|
109
|
+
- **User Context**: Automatically includes authenticated user information
|
|
110
|
+
|
|
111
|
+
## What Gets Captured
|
|
112
|
+
|
|
113
|
+
For each error, the middleware sends:
|
|
114
|
+
|
|
115
|
+
- **Error Details**: Exception type, message, and full traceback
|
|
116
|
+
- **Request Info**: URL path, HTTP method, GET/POST data, request body
|
|
117
|
+
- **User Context**: Email and ID (if user is authenticated)
|
|
118
|
+
- **Headers**: All HTTP headers
|
|
119
|
+
- **Timestamp**: When the error occurred
|
|
120
|
+
|
|
121
|
+
## Example Error Data
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"error_code": 500,
|
|
126
|
+
"path": "/api/users/123/",
|
|
127
|
+
"method": "POST",
|
|
128
|
+
"user_email": "user@example.com",
|
|
129
|
+
"user_id": "456",
|
|
130
|
+
"traceback": "Traceback (most recent call last)...",
|
|
131
|
+
"request_data": {
|
|
132
|
+
"GET": {},
|
|
133
|
+
"POST": {"name": "John"},
|
|
134
|
+
"body": "{\"age\": 30}"
|
|
135
|
+
},
|
|
136
|
+
"headers": {
|
|
137
|
+
"User-Agent": "Mozilla/5.0...",
|
|
138
|
+
"Content-Type": "application/json"
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Security
|
|
144
|
+
|
|
145
|
+
- **API Key**: Transmitted securely via X-API-Key header
|
|
146
|
+
- **Sensitive Data**: Be mindful of sensitive data in request bodies/headers
|
|
147
|
+
- **User Privacy**: User emails/IDs are only sent if users are authenticated
|
|
148
|
+
|
|
149
|
+
## Troubleshooting
|
|
150
|
+
|
|
151
|
+
### "AISSUE_API_KEY setting is required"
|
|
152
|
+
|
|
153
|
+
Make sure you've added your API key to Django settings:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
AISSUE_API_KEY = 'your-actual-api-key'
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Not seeing errors in AIssue?
|
|
160
|
+
|
|
161
|
+
1. Check that `DEBUG = False` or set `AISSUE_LOG_IN_DEBUG = True`
|
|
162
|
+
2. Verify your API key is correct
|
|
163
|
+
3. Check Django logs for AIssue connection errors
|
|
164
|
+
4. Ensure the middleware is added to `MIDDLEWARE` setting
|
|
165
|
+
|
|
166
|
+
### Temporarily disable logging
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
AISSUE_ENABLED = False
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
## Support
|
|
173
|
+
|
|
174
|
+
- **Documentation**: [https://docs.aissue.com/django](https://docs.aissue.com/django)
|
|
175
|
+
- **Issues**: [GitHub Issues](https://github.com/aissue/aissue-django/issues)
|
|
176
|
+
- **Email**: support@aissue.com
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
MIT License - see LICENSE file for details.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
aissue/__init__.py,sha256=66bXkgvI74_dHADga6xYa3vCpZhZB4WGYWF0Tsx3Rm4,164
|
|
2
|
+
aissue/apps.py,sha256=W8PCpChIhqLoMXg48tENpcUwy9a2wLIOOo7PH4t1_Es,189
|
|
3
|
+
aissue/exceptions.py,sha256=INg4QsXMfwfeS1_XBEmSh_DNqw8bssPLJj-R_vMIx04,314
|
|
4
|
+
aissue/middleware.py,sha256=vSqIIOncDWAuJ1FB31DPbCwKgRp3SY6FB9WsMgaAL2o,5544
|
|
5
|
+
tests/__init__.py,sha256=Tjs5UBRNWY52xQaWUYlyDkEccyAIaIYHL92in1XTgEY,37
|
|
6
|
+
tests/test_middleware.py,sha256=3EazwuykBf17KG3S9tNvAqkfTBtE2a9rcWM6Tjj_fE8,9703
|
|
7
|
+
tests/urls.py,sha256=o3TvyvvsebpMqVaWmhl81M9oqJ549htiiOqxBpRV0nc,395
|
|
8
|
+
aissue-1.0.0.dist-info/METADATA,sha256=5aogJKN8XzOZmQTpdZoDBjyK8pGhVw-lNYHkwGuvvLE,5193
|
|
9
|
+
aissue-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
10
|
+
aissue-1.0.0.dist-info/top_level.txt,sha256=6nCHaASdkDAV9BxuvN_FeK9IOLCrwFmfE5YCZl8M6ro,13
|
|
11
|
+
aissue-1.0.0.dist-info/RECORD,,
|
tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Tests for aissue-django middleware
|
tests/test_middleware.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from unittest.mock import patch, MagicMock, call
|
|
3
|
+
from django.test import TestCase, RequestFactory, override_settings, Client
|
|
4
|
+
from django.contrib.auth import get_user_model
|
|
5
|
+
from django.http import HttpResponse
|
|
6
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
from aissue.middleware import AIssueMiddleware
|
|
10
|
+
from aissue.exceptions import AIssueConfigurationError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@patch('aissue.middleware.requests.post')
|
|
14
|
+
class TestAIssueMiddleware(TestCase):
|
|
15
|
+
def setUp(self):
|
|
16
|
+
self.factory = RequestFactory()
|
|
17
|
+
User = get_user_model()
|
|
18
|
+
self.user = User.objects.create_user(
|
|
19
|
+
username='testuser',
|
|
20
|
+
email='test@example.com',
|
|
21
|
+
password='testpass123'
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Create a mock get_response function
|
|
25
|
+
self.get_response = MagicMock()
|
|
26
|
+
|
|
27
|
+
@override_settings(
|
|
28
|
+
AISSUE_API_KEY='test-key',
|
|
29
|
+
AISSUE_BASE_URL='http://test.com',
|
|
30
|
+
DEBUG=False
|
|
31
|
+
)
|
|
32
|
+
def test_successful_request_no_error(self, mock_post):
|
|
33
|
+
"""Test that middleware passes through successful requests without logging"""
|
|
34
|
+
request = self.factory.get('/test-path')
|
|
35
|
+
self.get_response.return_value = HttpResponse('OK')
|
|
36
|
+
|
|
37
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
38
|
+
response = middleware(request)
|
|
39
|
+
|
|
40
|
+
self.assertEqual(response.status_code, 200)
|
|
41
|
+
mock_post.assert_not_called()
|
|
42
|
+
|
|
43
|
+
@override_settings(
|
|
44
|
+
AISSUE_API_KEY='test-key',
|
|
45
|
+
AISSUE_BASE_URL='http://test.com',
|
|
46
|
+
DEBUG=False
|
|
47
|
+
)
|
|
48
|
+
def test_process_exception_logs_error(self, mock_post):
|
|
49
|
+
"""Test that process_exception logs errors when DEBUG=False"""
|
|
50
|
+
request = self.factory.get('/test-path')
|
|
51
|
+
request.user = self.user
|
|
52
|
+
|
|
53
|
+
# Set up mock response
|
|
54
|
+
mock_response = MagicMock()
|
|
55
|
+
mock_response.status_code = 201
|
|
56
|
+
mock_post.return_value = mock_response
|
|
57
|
+
|
|
58
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
59
|
+
exception = ValueError('Test error')
|
|
60
|
+
|
|
61
|
+
# Call process_exception directly
|
|
62
|
+
result = middleware.process_exception(request, exception)
|
|
63
|
+
|
|
64
|
+
# Should return None to continue Django's error handling
|
|
65
|
+
self.assertIsNone(result)
|
|
66
|
+
|
|
67
|
+
# Verify the error was logged
|
|
68
|
+
self.assertTrue(mock_post.called)
|
|
69
|
+
|
|
70
|
+
# Get the call arguments
|
|
71
|
+
args, kwargs = mock_post.call_args
|
|
72
|
+
|
|
73
|
+
# Check the URL
|
|
74
|
+
self.assertEqual(args[0], 'http://test.com/api/errors/')
|
|
75
|
+
|
|
76
|
+
# Check the headers
|
|
77
|
+
self.assertEqual(kwargs['headers'], {'X-API-Key': 'test-key'})
|
|
78
|
+
|
|
79
|
+
# Check the error data
|
|
80
|
+
error_data = kwargs['json']
|
|
81
|
+
self.assertEqual(error_data['error_code'], 500)
|
|
82
|
+
self.assertEqual(error_data['path'], '/test-path')
|
|
83
|
+
self.assertEqual(error_data['method'], 'GET')
|
|
84
|
+
self.assertEqual(error_data['user_email'], 'test@example.com')
|
|
85
|
+
self.assertEqual(error_data['user_id'], str(self.user.id))
|
|
86
|
+
|
|
87
|
+
@override_settings(
|
|
88
|
+
AISSUE_API_KEY='test-key',
|
|
89
|
+
AISSUE_BASE_URL='http://test.com',
|
|
90
|
+
DEBUG=True,
|
|
91
|
+
AISSUE_LOG_IN_DEBUG=False
|
|
92
|
+
)
|
|
93
|
+
def test_debug_mode_no_logging(self, mock_post):
|
|
94
|
+
"""Test that middleware doesn't log in DEBUG mode by default"""
|
|
95
|
+
request = self.factory.get('/test-path')
|
|
96
|
+
|
|
97
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
98
|
+
exception = ValueError('Test error')
|
|
99
|
+
|
|
100
|
+
# Call process_exception
|
|
101
|
+
middleware.process_exception(request, exception)
|
|
102
|
+
|
|
103
|
+
# Should not log in debug mode
|
|
104
|
+
mock_post.assert_not_called()
|
|
105
|
+
|
|
106
|
+
@override_settings(
|
|
107
|
+
AISSUE_API_KEY='test-key',
|
|
108
|
+
AISSUE_BASE_URL='http://test.com',
|
|
109
|
+
DEBUG=True,
|
|
110
|
+
AISSUE_LOG_IN_DEBUG=True
|
|
111
|
+
)
|
|
112
|
+
def test_debug_mode_with_log_in_debug(self, mock_post):
|
|
113
|
+
"""Test that middleware logs in DEBUG mode when AISSUE_LOG_IN_DEBUG=True"""
|
|
114
|
+
request = self.factory.get('/test-path')
|
|
115
|
+
request.user = self.user
|
|
116
|
+
|
|
117
|
+
# Set up mock response
|
|
118
|
+
mock_response = MagicMock()
|
|
119
|
+
mock_response.status_code = 201
|
|
120
|
+
mock_post.return_value = mock_response
|
|
121
|
+
|
|
122
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
123
|
+
exception = ValueError('Test error')
|
|
124
|
+
|
|
125
|
+
# Call process_exception
|
|
126
|
+
middleware.process_exception(request, exception)
|
|
127
|
+
|
|
128
|
+
# Should log even in debug mode
|
|
129
|
+
self.assertTrue(mock_post.called)
|
|
130
|
+
|
|
131
|
+
@override_settings(AISSUE_API_KEY='') # Override to empty string
|
|
132
|
+
def test_missing_api_key_raises_error(self, mock_post):
|
|
133
|
+
"""Test that missing API key raises configuration error"""
|
|
134
|
+
with self.assertRaises(AIssueConfigurationError):
|
|
135
|
+
AIssueMiddleware(self.get_response)
|
|
136
|
+
|
|
137
|
+
@override_settings(
|
|
138
|
+
AISSUE_API_KEY='test-key',
|
|
139
|
+
AISSUE_ENABLED=False,
|
|
140
|
+
DEBUG=False
|
|
141
|
+
)
|
|
142
|
+
def test_disabled_middleware(self, mock_post):
|
|
143
|
+
"""Test that disabled middleware doesn't log errors"""
|
|
144
|
+
request = self.factory.get('/test-path')
|
|
145
|
+
|
|
146
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
147
|
+
exception = ValueError('Test error')
|
|
148
|
+
|
|
149
|
+
# Call process_exception
|
|
150
|
+
middleware.process_exception(request, exception)
|
|
151
|
+
|
|
152
|
+
# Should not log when disabled
|
|
153
|
+
mock_post.assert_not_called()
|
|
154
|
+
|
|
155
|
+
@override_settings(
|
|
156
|
+
AISSUE_API_KEY='test-key',
|
|
157
|
+
AISSUE_BASE_URL='http://test.com',
|
|
158
|
+
DEBUG=False
|
|
159
|
+
)
|
|
160
|
+
def test_api_error_handling(self, mock_post):
|
|
161
|
+
"""Test that API errors are handled gracefully"""
|
|
162
|
+
request = self.factory.get('/test-path')
|
|
163
|
+
request.user = self.user
|
|
164
|
+
|
|
165
|
+
# Simulate API error
|
|
166
|
+
mock_post.side_effect = requests.RequestException('API error')
|
|
167
|
+
|
|
168
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
169
|
+
exception = ValueError('Test error')
|
|
170
|
+
|
|
171
|
+
# Should not raise an exception
|
|
172
|
+
result = middleware.process_exception(request, exception)
|
|
173
|
+
self.assertIsNone(result)
|
|
174
|
+
|
|
175
|
+
@override_settings(
|
|
176
|
+
AISSUE_API_KEY='test-key',
|
|
177
|
+
AISSUE_BASE_URL='http://test.com',
|
|
178
|
+
DEBUG=False
|
|
179
|
+
)
|
|
180
|
+
def test_anonymous_user_handling(self, mock_post):
|
|
181
|
+
"""Test that anonymous users are handled correctly"""
|
|
182
|
+
request = self.factory.get('/test-path')
|
|
183
|
+
request.user = MagicMock(is_authenticated=False, email=None)
|
|
184
|
+
|
|
185
|
+
# Set up mock response
|
|
186
|
+
mock_response = MagicMock()
|
|
187
|
+
mock_response.status_code = 201
|
|
188
|
+
mock_post.return_value = mock_response
|
|
189
|
+
|
|
190
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
191
|
+
exception = ValueError('Test error')
|
|
192
|
+
|
|
193
|
+
middleware.process_exception(request, exception)
|
|
194
|
+
|
|
195
|
+
self.assertTrue(mock_post.called)
|
|
196
|
+
args, kwargs = mock_post.call_args
|
|
197
|
+
error_data = kwargs['json']
|
|
198
|
+
self.assertIsNone(error_data['user_email'])
|
|
199
|
+
self.assertIsNone(error_data['user_id'])
|
|
200
|
+
|
|
201
|
+
@override_settings(
|
|
202
|
+
AISSUE_API_KEY='test-key',
|
|
203
|
+
AISSUE_BASE_URL='http://test.com',
|
|
204
|
+
DEBUG=False
|
|
205
|
+
)
|
|
206
|
+
def test_post_data_capture(self, mock_post):
|
|
207
|
+
"""Test that POST data is correctly captured"""
|
|
208
|
+
request = self.factory.post('/test-path', data={'test': 'value'})
|
|
209
|
+
request.user = self.user
|
|
210
|
+
|
|
211
|
+
# Set up mock response
|
|
212
|
+
mock_response = MagicMock()
|
|
213
|
+
mock_response.status_code = 201
|
|
214
|
+
mock_post.return_value = mock_response
|
|
215
|
+
|
|
216
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
217
|
+
exception = ValueError('Test error')
|
|
218
|
+
|
|
219
|
+
middleware.process_exception(request, exception)
|
|
220
|
+
|
|
221
|
+
self.assertTrue(mock_post.called)
|
|
222
|
+
args, kwargs = mock_post.call_args
|
|
223
|
+
error_data = kwargs['json']
|
|
224
|
+
self.assertEqual(error_data['request_data']['POST'], {'test': ['value']})
|
|
225
|
+
|
|
226
|
+
@override_settings(
|
|
227
|
+
AISSUE_API_KEY='test-key',
|
|
228
|
+
AISSUE_BASE_URL='http://test.com',
|
|
229
|
+
DEBUG=False
|
|
230
|
+
)
|
|
231
|
+
def test_json_body_capture(self, mock_post):
|
|
232
|
+
"""Test that JSON request body is correctly captured"""
|
|
233
|
+
json_data = {'test': 'value'}
|
|
234
|
+
request = self.factory.post(
|
|
235
|
+
'/test-path',
|
|
236
|
+
data=json.dumps(json_data),
|
|
237
|
+
content_type='application/json'
|
|
238
|
+
)
|
|
239
|
+
request.user = self.user
|
|
240
|
+
|
|
241
|
+
# Set up mock response
|
|
242
|
+
mock_response = MagicMock()
|
|
243
|
+
mock_response.status_code = 201
|
|
244
|
+
mock_post.return_value = mock_response
|
|
245
|
+
|
|
246
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
247
|
+
exception = ValueError('Test error')
|
|
248
|
+
|
|
249
|
+
middleware.process_exception(request, exception)
|
|
250
|
+
|
|
251
|
+
self.assertTrue(mock_post.called)
|
|
252
|
+
args, kwargs = mock_post.call_args
|
|
253
|
+
error_data = kwargs['json']
|
|
254
|
+
self.assertEqual(error_data['request_data']['body'], json_data)
|
|
255
|
+
|
|
256
|
+
@override_settings(
|
|
257
|
+
AISSUE_API_KEY='test-key',
|
|
258
|
+
AISSUE_BASE_URL='http://test.com',
|
|
259
|
+
AISSUE_TIMEOUT=10,
|
|
260
|
+
DEBUG=False
|
|
261
|
+
)
|
|
262
|
+
def test_custom_timeout(self, mock_post):
|
|
263
|
+
"""Test that custom timeout is used"""
|
|
264
|
+
request = self.factory.get('/test-path')
|
|
265
|
+
|
|
266
|
+
# Set up mock response
|
|
267
|
+
mock_response = MagicMock()
|
|
268
|
+
mock_response.status_code = 201
|
|
269
|
+
mock_post.return_value = mock_response
|
|
270
|
+
|
|
271
|
+
middleware = AIssueMiddleware(self.get_response)
|
|
272
|
+
exception = ValueError('Test error')
|
|
273
|
+
|
|
274
|
+
middleware.process_exception(request, exception)
|
|
275
|
+
|
|
276
|
+
# Check that timeout was passed correctly
|
|
277
|
+
args, kwargs = mock_post.call_args
|
|
278
|
+
self.assertEqual(kwargs['timeout'], 10)
|
tests/urls.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from django.urls import path
|
|
2
|
+
from django.http import HttpResponse
|
|
3
|
+
|
|
4
|
+
def test_view(request):
|
|
5
|
+
"""Simple test view"""
|
|
6
|
+
return HttpResponse("Test view")
|
|
7
|
+
|
|
8
|
+
def error_view(request):
|
|
9
|
+
"""View that raises an error for testing"""
|
|
10
|
+
raise ValueError("Test error for middleware testing")
|
|
11
|
+
|
|
12
|
+
urlpatterns = [
|
|
13
|
+
path('test/', test_view, name='test'),
|
|
14
|
+
path('error/', error_view, name='error'),
|
|
15
|
+
]
|