-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
fixtures.py
464 lines (381 loc) · 15.3 KB
/
fixtures.py
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
"""
A number of generic default fixtures to use with tests.
All model-related fixtures defined here require the database, and should imply as much by
including ``db`` fixture in the function resolution scope.
"""
import difflib
import os
import re
import sys
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from typing import Optional
import pytest
import requests
import yaml
from django.core.cache import cache
import sentry
# These chars cannot be used in Windows paths so replace them:
# https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#naming-conventions
from sentry.types.activity import ActivityType
UNSAFE_PATH_CHARS = ("<", ">", ":", '"', " | ", "?", "*")
DIRECTORY_GROUPING_CHARS = ("::", "-", "[", "]", "\\")
DEFAULT_EVENT_DATA = {
"extra": {
"loadavg": [0.97607421875, 0.88330078125, 0.833984375],
"sys.argv": [
"/Users/dcramer/.virtualenvs/sentry/bin/raven",
"test",
"https://ebc35f33e151401f9deac549978bda11:[email protected]/1",
],
"user": "dcramer",
},
"modules": {"raven": "3.1.13"},
"request": {
"cookies": {},
"data": {},
"env": {},
"headers": {},
"method": "GET",
"query_string": "",
"url": "http://example.com",
},
"stacktrace": {
"frames": [
{
"abs_path": "www/src/sentry/models/foo.py",
"context_line": " string_max_length=self.string_max_length)",
"filename": "sentry/models/foo.py",
"function": "build_msg",
"in_app": True,
"lineno": 29,
"module": "raven.base",
"post_context": [
" },",
" })",
"",
" if 'stacktrace' in data:",
" if self.include_paths:",
],
"pre_context": [
"",
" data.update({",
" 'stacktrace': {",
" 'frames': get_stack_info(frames,",
" list_max_length=self.list_max_length,",
],
"vars": {
"culprit": "raven.scripts.runner",
"date": "datetime.datetime(2013, 2, 14, 20, 6, 33, 479471)",
"event_id": "598fb19363e745ec8be665e6ba88b1b2",
"event_type": "raven.events.Message",
"frames": "<generator object iter_stack_frames at 0x103fef050>",
"handler": "<raven.events.Message object at 0x103feb710>",
"k": "logentry",
"public_key": None,
"result": {
"logentry": "{'message': 'This is a test message generated using ``raven test``', 'params': []}"
},
"self": "<raven.base.Client object at 0x104397f10>",
"stack": True,
"tags": None,
"time_spent": None,
},
},
{
"abs_path": "/Users/dcramer/.virtualenvs/sentry/lib/python2.7/site-packages/raven/base.py",
"context_line": " string_max_length=self.string_max_length)",
"filename": "raven/base.py",
"function": "build_msg",
"in_app": False,
"lineno": 290,
"module": "raven.base",
"post_context": [
" },",
" })",
"",
" if 'stacktrace' in data:",
" if self.include_paths:",
],
"pre_context": [
"",
" data.update({",
" 'stacktrace': {",
" 'frames': get_stack_info(frames,",
" list_max_length=self.list_max_length,",
],
"vars": {
"culprit": "raven.scripts.runner",
"date": "datetime.datetime(2013, 2, 14, 20, 6, 33, 479471)",
"event_id": "598fb19363e745ec8be665e6ba88b1b2",
"event_type": "raven.events.Message",
"frames": "<generator object iter_stack_frames at 0x103fef050>",
"handler": "<raven.events.Message object at 0x103feb710>",
"k": "logentry",
"public_key": None,
"result": {
"logentry": "{'message': 'This is a test message generated using ``raven test``', 'params': []}"
},
"self": "<raven.base.Client object at 0x104397f10>",
"stack": True,
"tags": None,
"time_spent": None,
},
},
]
},
"tags": [],
"platform": "python",
}
@pytest.mark.django_db
@pytest.fixture
def factories():
# XXX(dcramer): hack to prevent recursive imports
from sentry.testutils.factories import Factories
return Factories
@pytest.fixture
def task_runner():
"""Context manager that ensures Celery tasks run directly inline where invoked.
While this context manager is active any Celery tasks created will run immediately at
the callsite rather than being sent to RabbitMQ and handled by a worker.
"""
from sentry.testutils.helpers.task_runner import TaskRunner
return TaskRunner
@pytest.fixture
def burst_task_runner():
"""Context manager that queues up Celery tasks until called.
The yielded value which can be assigned by the ``as`` clause is callable and will
execute all queued up tasks. It takes a ``max_jobs`` argument to limit the number of
jobs to process.
The queue itself can be inspected via the ``queue`` attribute of the yielded value.
"""
from sentry.testutils.helpers.task_runner import BurstTaskRunner
return BurstTaskRunner
@pytest.fixture(scope="function")
def session():
return factories.create_session()
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_user(factories):
"""A default (super)user with email ``admin@localhost`` and password ``admin``.
:returns: A :class:`sentry.models.user.User` instance.
"""
return factories.create_user(email="admin@localhost", is_superuser=True)
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_organization(factories, default_user):
"""A default organization (slug=``baz``) owned by the ``default_user`` fixture.
:returns: A :class:`sentry.models.organization.Organization` instance.
"""
# XXX(dcramer): ensure that your org slug doesnt match your team slug
# and the same for your project slug
return factories.create_organization(name="baz", slug="baz", owner=default_user)
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_team(factories, default_organization):
from sentry.models import OrganizationMember, OrganizationMemberTeam
team = factories.create_team(organization=default_organization, name="foo", slug="foo")
# XXX: handle legacy team fixture
queryset = OrganizationMember.objects.filter(organization=default_organization)
for om in queryset:
OrganizationMemberTeam.objects.create(team=team, organizationmember=om, is_active=True)
return team
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_project(factories, default_team):
return factories.create_project(name="Bar", slug="bar", teams=[default_team])
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_projectkey(factories, default_project):
return factories.create_project_key(project=default_project)
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_environment(factories, default_project):
return factories.create_environment(name="development", project=default_project)
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_group(factories, default_project):
# こんにちは konichiwa
return factories.create_group(project=default_project, message="\u3053\u3093\u306b\u3061\u306f")
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_event(factories, default_group):
return factories.store_event(
data={"event_id": "a" * 32, "message": "\u3053\u3093\u306b\u3061\u306f"},
project_id=default_project.id,
)
@pytest.mark.django_db
@pytest.fixture(scope="function")
def default_activity(default_group, default_project, default_user):
from sentry.models import Activity
return Activity.objects.create(
group=default_group,
project=default_project,
type=ActivityType.NOTE.value,
user_id=default_user.id,
data={},
)
@pytest.fixture()
def dyn_sampling_data():
# return a function that returns fresh config so we don't accidentally get tests interfering with each other
def inner(active=True):
return {
"mode": "total",
"rules": [
{
"sampleRate": 0.7,
"type": "trace",
"active": active,
"condition": {
"op": "and",
"inner": [
{"op": "eq", "ignoreCase": True, "name": "field1", "value": ["val"]},
{"op": "glob", "name": "field1", "value": ["val"]},
],
},
}
],
}
return inner
_snapshot_writeback: Optional[str] = os.environ.get("SENTRY_SNAPSHOTS_WRITEBACK") or "0"
if _snapshot_writeback in ("true", "1", "overwrite"):
_snapshot_writeback = "overwrite"
elif _snapshot_writeback != "new":
_snapshot_writeback = None
_test_base = os.path.realpath(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(sentry.__file__))))
)
_yaml_snap_re = re.compile(r"^---\r?\n(.*?)\r?\n---\r?\n(.*)$", re.DOTALL)
@pytest.fixture
def log():
def inner(x):
return sys.stdout.write(x + "\n")
return inner
class ReadableYamlDumper(yaml.dumper.SafeDumper):
"""Disable pyyaml aliases for identical object references"""
def ignore_aliases(self, data):
return True
@pytest.fixture
def insta_snapshot(request, log):
def inner(output, reference_file=None, subname=None):
if reference_file is None:
name = request.node.name
for c in UNSAFE_PATH_CHARS:
name = name.replace(c, "@")
for c in DIRECTORY_GROUPING_CHARS:
name = name.replace(c, "/")
name = name.strip("/")
if subname is not None:
name += f"_{subname}"
reference_file = os.path.join(
os.path.dirname(str(request.node.fspath)),
"snapshots",
os.path.splitext(os.path.basename(request.node.parent.name))[0],
name + ".pysnap",
)
elif subname is not None:
raise ValueError(
"subname only works if you don't provide your own entire reference_file"
)
if not isinstance(output, str):
output = yaml.dump(
output, indent=2, default_flow_style=False, Dumper=ReadableYamlDumper
)
try:
with open(reference_file, encoding="utf-8") as f:
match = _yaml_snap_re.match(f.read())
if match is None:
raise OSError()
_header, refval = match.groups()
except OSError:
refval = ""
refval = refval.rstrip()
output = output.rstrip()
if _snapshot_writeback is not None and refval != output:
if not os.path.isdir(os.path.dirname(reference_file)):
os.makedirs(os.path.dirname(reference_file))
source = os.path.realpath(str(request.node.fspath))
if source.startswith(_test_base + os.path.sep):
source = source[len(_test_base) + 1 :]
if _snapshot_writeback == "new":
reference_file += ".new"
with open(reference_file, "w") as f:
f.write(
"---\n%s\n---\n%s\n"
% (
yaml.safe_dump(
{
"created": datetime.utcnow().isoformat() + "Z",
"creator": "sentry",
"source": source,
},
indent=2,
default_flow_style=False,
).rstrip(),
output,
)
)
elif refval != output:
__tracebackhide__ = True
_print_insta_diff(reference_file, refval, output)
yield inner
def _print_insta_diff(reference_file, a, b):
__tracebackhide__ = True
pytest.fail(
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"Snapshot {} changed!\n\n"
"Re-run pytest with SENTRY_SNAPSHOTS_WRITEBACK=new and then use 'make review-python-snapshots' to review.\n"
"Or: Use SENTRY_SNAPSHOTS_WRITEBACK=1 to update snapshots directly.\n\n"
"{}\n"
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n".format(
reference_file, "\n".join(difflib.unified_diff(a.splitlines(), b.splitlines()))
)
)
@pytest.fixture
def call_snuba(settings):
def inner(endpoint):
return requests.post(settings.SENTRY_SNUBA + endpoint)
return inner
@pytest.fixture
def reset_snuba(call_snuba):
init_endpoints = [
"/tests/events/drop",
"/tests/groupedmessage/drop",
"/tests/transactions/drop",
"/tests/sessions/drop",
"/tests/metrics/drop",
"/tests/generic_metrics/drop",
"/tests/search_issues/drop",
]
assert all(
response.status_code == 200
for response in ThreadPoolExecutor(len(init_endpoints)).map(call_snuba, init_endpoints)
)
@pytest.fixture
def set_sentry_option():
"""
A pytest-style wrapper around override_options.
```python
def test_basic(set_sentry_option):
with set_sentry_option("key", 1.0):
do stuff
```
"""
from sentry.testutils.helpers.options import override_options
def inner(key, value):
return override_options({key: value})
return inner
@pytest.fixture
def django_cache():
yield cache
cache.clear()
# NOTE:
# If you are using a local instance of Symbolicator, you may need to either change `system.url-prefix`
# to `system.internal-url-prefix` or add `127.0.0.1 host.docker.internal` entry to your `/etc/hosts`.
@pytest.fixture(ids=["without_symbolicator", "with_symbolicator"], params=[0, 1])
def process_with_symbolicator(request, set_sentry_option, live_server):
with set_sentry_option("system.url-prefix", live_server.url), set_sentry_option(
"symbolicator.sourcemaps-processing-sample-rate", request.param
):
# Run test case
yield request.param