Spaces:
Sleeping
Sleeping
File size: 13,289 Bytes
2358888 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
"""
Sentry API simulator.
Provides realistic mock responses for Sentry API actions.
"""
from typing import Optional
from .base import BaseSimulator
from datetime import datetime
import time
import random
class SentrySimulator(BaseSimulator):
"""Simulator for Sentry API."""
def __init__(self):
super().__init__('sentry')
def load_mock_responses(self):
"""Load Sentry mock response templates."""
self.mock_responses = {
'get_issues': self._get_issues_template,
'update_issue': self._update_issue_template,
'get_events': self._get_events_template,
'get_issue_details': self._get_issue_details_template,
'resolve_issue': self._resolve_issue_template,
'get_projects': self._get_projects_template,
}
def get_required_permissions(self, action: str) -> set[str]:
"""Get required Sentry permissions for an action."""
permissions_map = {
'get_issues': {'project:read'},
'update_issue': {'project:write'},
'get_events': {'event:read'},
'get_issue_details': {'project:read'},
'resolve_issue': {'project:write'},
'get_projects': {'project:read'},
}
return permissions_map.get(action, set())
def validate_params(self, action: str, params: dict) -> tuple[bool, Optional[str]]:
"""Validate parameters for Sentry actions."""
if action == 'get_issues':
required = {'project_id'}
missing = required - set(params.keys())
if missing:
return False, f"Missing required parameters: {missing}"
elif action == 'update_issue':
required = {'issue_id'}
missing = required - set(params.keys())
if missing:
return False, f"Missing required parameters: {missing}"
elif action == 'get_events':
required = {'issue_id'}
missing = required - set(params.keys())
if missing:
return False, f"Missing required parameters: {missing}"
elif action == 'get_issue_details':
required = {'issue_id'}
missing = required - set(params.keys())
if missing:
return False, f"Missing required parameters: {missing}"
elif action == 'resolve_issue':
required = {'issue_id'}
missing = required - set(params.keys())
if missing:
return False, f"Missing required parameters: {missing}"
elif action == 'get_projects':
# No required params
pass
else:
return False, f"Unknown action: {action}"
return True, None
def generate_mock_response(self, action: str, params: dict) -> dict:
"""Generate realistic Sentry API response."""
if action not in self.mock_responses:
raise ValueError(f"Unknown action: {action}")
template_func = self.mock_responses[action]
return template_func(params)
def _get_issues_template(self, params: dict) -> list:
"""Mock response for getting project issues."""
issues = []
# Generate a few mock issues
error_types = [
("TypeError", "Cannot read property 'map' of undefined"),
("ReferenceError", "userId is not defined"),
("NetworkError", "Failed to fetch data from API"),
]
for i, (error_type, message) in enumerate(error_types):
issue_id = f"issue-{1000+i}"
issues.append({
"id": issue_id,
"shareId": None,
"shortId": f"PROJECT-{i+1}",
"title": f"{error_type}: {message}",
"culprit": f"app/components/UserList.tsx in <UserList>",
"permalink": f"https://sentry.io/organizations/myorg/issues/{issue_id}/",
"logger": None,
"level": "error",
"status": "unresolved" if i < 2 else "resolved",
"statusDetails": {},
"isPublic": False,
"platform": "javascript",
"project": {
"id": params['project_id'],
"name": "my-app",
"slug": "my-app",
"platform": "javascript"
},
"type": "error",
"metadata": {
"type": error_type,
"value": message,
"filename": "app/components/UserList.tsx",
"function": "<UserList>"
},
"numComments": 0,
"assignedTo": None,
"isBookmarked": False,
"isSubscribed": False,
"subscriptionDetails": None,
"hasSeen": True,
"annotations": [],
"isUnhandled": True,
"count": str(random.randint(5, 100)),
"userCount": random.randint(2, 20),
"firstSeen": f"2025-11-{20+i}T10:00:00.000000Z",
"lastSeen": datetime.utcnow().isoformat() + "Z",
"stats": {
"24h": [[int(time.time()) - 86400, random.randint(1, 10)] for _ in range(24)]
}
})
return issues
def _update_issue_template(self, params: dict) -> dict:
"""Mock response for updating an issue."""
issue_id = params['issue_id']
return {
"id": issue_id,
"status": params.get('status', 'resolved'),
"statusDetails": {},
"assignedTo": {
"id": params.get('assignedTo'),
"name": "Team Member",
"email": "member@company.com"
} if params.get('assignedTo') else None,
"hasSeen": True,
"isBookmarked": params.get('isBookmarked', False),
"isSubscribed": params.get('isSubscribed', True)
}
def _get_events_template(self, params: dict) -> list:
"""Mock response for getting events for an issue."""
events = []
# Generate a few mock events
for i in range(5):
event_id = f"event-{int(time.time())}-{i}"
events.append({
"id": event_id,
"groupID": params['issue_id'],
"eventID": event_id,
"projectID": "123456",
"size": 12345,
"platform": "javascript",
"message": "TypeError: Cannot read property 'map' of undefined",
"datetime": f"2025-11-30T{10+i}:00:00.000000Z",
"tags": [
{"key": "browser", "value": "Chrome 119.0.0"},
{"key": "environment", "value": "production"},
{"key": "level", "value": "error"},
{"key": "url", "value": "https://myapp.com/users"}
],
"context": {
"browser": {
"name": "Chrome",
"version": "119.0.0"
},
"os": {
"name": "Mac OS X",
"version": "10.15.7"
}
},
"user": {
"id": f"user-{i}",
"email": f"user{i}@example.com",
"ip_address": f"192.168.1.{i+1}"
},
"entries": [
{
"type": "exception",
"data": {
"values": [
{
"type": "TypeError",
"value": "Cannot read property 'map' of undefined",
"stacktrace": {
"frames": [
{
"filename": "app/components/UserList.tsx",
"function": "<UserList>",
"lineno": 42,
"colno": 15,
"context_line": " const userNames = users.map(u => u.name);",
"in_app": True
}
]
}
}
]
}
}
]
})
return events
def _get_issue_details_template(self, params: dict) -> dict:
"""Mock response for getting detailed issue information."""
issue_id = params['issue_id']
return {
"id": issue_id,
"shareId": None,
"shortId": "PROJECT-1",
"title": "TypeError: Cannot read property 'map' of undefined",
"culprit": "app/components/UserList.tsx in <UserList>",
"permalink": f"https://sentry.io/organizations/myorg/issues/{issue_id}/",
"logger": None,
"level": "error",
"status": "unresolved",
"statusDetails": {},
"isPublic": False,
"platform": "javascript",
"project": {
"id": "123456",
"name": "my-app",
"slug": "my-app",
"platform": "javascript"
},
"type": "error",
"metadata": {
"type": "TypeError",
"value": "Cannot read property 'map' of undefined",
"filename": "app/components/UserList.tsx",
"function": "<UserList>"
},
"numComments": 2,
"assignedTo": {
"id": "user-1",
"name": "Jane Developer",
"email": "jane@company.com"
},
"isBookmarked": False,
"isSubscribed": True,
"subscriptionDetails": {
"reason": "committed"
},
"hasSeen": True,
"annotations": [],
"isUnhandled": True,
"count": "47",
"userCount": 12,
"firstSeen": "2025-11-20T10:00:00.000000Z",
"lastSeen": datetime.utcnow().isoformat() + "Z",
"stats": {
"24h": [[int(time.time()) - 86400 + (i * 3600), random.randint(1, 5)] for i in range(24)]
},
"activity": [
{
"type": "note",
"user": {
"name": "John Developer",
"email": "john@company.com"
},
"dateCreated": "2025-11-29T14:00:00.000000Z",
"data": {
"text": "Looking into this issue now. Appears to be related to missing user data."
}
}
]
}
def _resolve_issue_template(self, params: dict) -> dict:
"""Mock response for resolving an issue."""
issue_id = params['issue_id']
return {
"id": issue_id,
"status": "resolved",
"statusDetails": {
"inNextRelease": params.get('inNextRelease', False),
"inRelease": params.get('inRelease')
},
"hasSeen": True
}
def _get_projects_template(self, params: dict) -> list:
"""Mock response for listing projects."""
return [
{
"id": "123456",
"slug": "my-app",
"name": "My App",
"platform": "javascript",
"dateCreated": "2025-01-15T00:00:00.000000Z",
"isBookmarked": False,
"isMember": True,
"teams": [
{
"id": "team-1",
"slug": "engineering",
"name": "Engineering"
}
],
"stats": {
"24h": {
"total": 125
}
}
},
{
"id": "123457",
"slug": "backend-api",
"name": "Backend API",
"platform": "python",
"dateCreated": "2025-02-01T00:00:00.000000Z",
"isBookmarked": True,
"isMember": True,
"teams": [
{
"id": "team-1",
"slug": "engineering",
"name": "Engineering"
}
],
"stats": {
"24h": {
"total": 43
}
}
}
]
|