forked from mozilla/treeherder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconftest.py
1249 lines (972 loc) · 36.9 KB
/
conftest.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import datetime
import json
import os
import platform
import time
from os.path import join, dirname
from unittest.mock import MagicMock
import kombu
import pytest
import responses
from _pytest.monkeypatch import MonkeyPatch
from django.conf import settings
from django.core.management import call_command
from rest_framework.test import APIClient
import moz_measure_noise
from tests.autoclassify.utils import test_line, create_failure_lines, create_text_log_errors
import treeherder.etl.bugzilla
from treeherder.etl.jobs import store_job_data
from treeherder.etl.push import store_push_data
from treeherder.model import models as th_models
from treeherder.perf import models as perf_models
from treeherder.services import taskcluster
from treeherder.services.pulse.exchange import get_exchange
from treeherder.webapp.api import perfcompare_utils
IS_WINDOWS = "windows" in platform.system().lower()
SAMPLE_DATA_PATH = join(dirname(__file__), 'sample_data')
def pytest_addoption(parser):
parser.addoption(
"--runslow",
action="store_true",
help="run slow tests",
)
def pytest_runtest_setup(item):
"""
Per-test setup.
- Add an option to run those tests marked as 'slow'
- Clear the django cache between runs
"""
if 'slow' in item.keywords and not item.config.getoption("--runslow"):
pytest.skip("need --runslow option to run")
from django.core.cache import cache
cache.clear()
@pytest.fixture
def setup_repository_data(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
call_command('loaddata', join(SAMPLE_DATA_PATH, 'repository_group.json'))
with django_db_blocker.unblock():
call_command('loaddata', join(SAMPLE_DATA_PATH, 'repository.json'))
@pytest.fixture(scope="session", autouse=True)
def block_unmocked_requests():
"""
Prevents requests from being made unless they are mocked.
Helps avoid inadvertent dependencies on external resources during the test run.
"""
def mocked_send(*args, **kwargs):
raise RuntimeError('Tests must mock all HTTP requests!')
# The standard monkeypatch fixture cannot be used with session scope:
# https://github.com/pytest-dev/pytest/issues/363
monkeypatch = MonkeyPatch()
# Monkeypatching here since any higher level would break responses:
# https://github.com/getsentry/responses/blob/0.5.1/responses.py#L295
monkeypatch.setattr('requests.adapters.HTTPAdapter.send', mocked_send)
yield monkeypatch
monkeypatch.undo()
@pytest.fixture
def sample_data():
"""Returns a SampleData() object"""
from .sampledata import SampleData
return SampleData()
@pytest.fixture(scope='session')
def test_base_dir():
return os.path.dirname(__file__)
@pytest.fixture
def sample_push(sample_data):
return copy.deepcopy(sample_data.push_data)
@pytest.fixture(name='create_push')
def fixture_create_push():
"""Return a function to create a push"""
def create(
repository,
revision='4c45a777949168d16c03a4cba167678b7ab65f76',
author='[email protected]',
time=None,
explicit_id=None,
):
return th_models.Push.objects.create(
id=explicit_id,
repository=repository,
revision=revision,
author=author,
time=time or datetime.datetime.now(),
)
return create
@pytest.fixture(name='create_commit')
def fixture_create_commit():
"""Return a function to create a commit"""
def create(push, comments='Bug 12345 - This is a message'):
return th_models.Commit.objects.create(
push=push, revision=push.revision, author=push.author, comments=comments
)
return create
@pytest.fixture(name='create_signature')
def fixture_create_signature():
"""Returns a function to create a signature"""
def create(
signature_hash,
extra_options,
platform,
measurement_unit,
suite,
test,
test_perf_signature,
repository,
application='',
):
return perf_models.PerformanceSignature.objects.create(
repository=repository,
signature_hash=signature_hash,
framework=test_perf_signature.framework,
platform=platform,
option_collection=test_perf_signature.option_collection,
suite=suite,
test=test,
has_subtests=test_perf_signature.has_subtests,
extra_options=extra_options,
last_updated=datetime.datetime.now(),
measurement_unit=measurement_unit,
application=application,
)
return create
@pytest.fixture(name='create_perf_datum')
def fixture_create_perf_datum():
"""Returns a function to create a performance datum"""
def create(index, job, push, sig, sig_values):
job.push = push
job.save()
perf_datum = perf_models.PerformanceDatum.objects.create(
value=sig_values[index],
push_timestamp=job.push.time,
job=job,
push=job.push,
repository=job.repository,
signature=sig,
)
perf_datum.push.time = job.push.time
perf_datum.push.save()
return perf_datum
return create
@pytest.fixture
def test_repository(django_db_reset_sequences):
th_models.RepositoryGroup.objects.get_or_create(name="development", description="")
r = th_models.Repository.objects.create(
dvcs_type="hg",
name=settings.TREEHERDER_TEST_REPOSITORY_NAME,
url="https://hg.mozilla.org/mozilla-central",
active_status="active",
codebase="gecko",
repository_group_id=1,
description="",
performance_alerts_enabled=True,
tc_root_url="https://firefox-ci-tc.services.mozilla.com",
)
return r
@pytest.fixture
def try_repository(transactional_db):
repo_group, _ = th_models.RepositoryGroup.objects.get_or_create(
name="development", description=""
)
r = th_models.Repository.objects.create(
id=4,
dvcs_type="hg",
name="try",
url="https://hg.mozilla.org/try",
active_status="active",
codebase="gecko",
repository_group_id=repo_group.id,
description="",
is_try_repo=True,
tc_root_url="https://firefox-ci-tc.services.mozilla.com",
)
return r
@pytest.fixture
def relevant_repository(transactional_db):
repo_group, _ = th_models.RepositoryGroup.objects.get_or_create(
name="development", description=""
)
r = th_models.Repository.objects.create(
dvcs_type="hg",
name="relevant_repository",
url="https://hg.mozilla.org/try",
active_status="active",
codebase="gecko",
repository_group_id=repo_group.id,
description="",
tc_root_url="https://firefox-ci-tc.services.mozilla.com",
)
return r
@pytest.fixture
def test_issue_tracker(transactional_db):
return perf_models.IssueTracker.objects.create(
name="Bugzilla", task_base_url="https://bugzilla.mozilla.org/show_bug.cgi?id="
)
@pytest.fixture
def test_repository_2(test_repository):
return th_models.Repository.objects.create(
repository_group=test_repository.repository_group,
name=test_repository.name + '_2',
dvcs_type=test_repository.dvcs_type,
url=test_repository.url + '_2',
codebase=test_repository.codebase,
)
@pytest.fixture
def test_push(create_push, test_repository):
return create_push(test_repository)
@pytest.fixture
def test_perfcomp_push(create_push, test_repository):
return create_push(test_repository, '1377267c6dc1')
@pytest.fixture
def test_perfcomp_push_2(create_push, test_repository):
return create_push(test_repository, '08038e535f58')
@pytest.fixture
def test_linux_platform():
return th_models.MachinePlatform.objects.create(
os_name='-', platform='linux1804-64-shippable-qr', architecture='-'
)
@pytest.fixture
def test_macosx_platform():
return th_models.MachinePlatform.objects.create(
os_name='', platform='macosx1015-64-shippable-qr', architecture=''
)
@pytest.fixture
def test_option_collection():
return perfcompare_utils.get_option_collection_map()
@pytest.fixture
def test_commit(create_commit, test_push):
return create_commit(test_push)
@pytest.fixture(name='create_jobs')
def fixture_create_jobs(test_repository, failure_classifications):
"""Return a function to create jobs"""
def create(jobs):
store_job_data(test_repository, jobs)
return [th_models.Job.objects.get(id=i) for i in range(1, len(jobs) + 1)]
return create
@pytest.fixture
def test_job(eleven_job_blobs, create_jobs):
job = eleven_job_blobs[0]
job['job'].update(
{'taskcluster_task_id': 'V3SVuxO8TFy37En_6HcXLs', 'taskcluster_retry_id': '0'}
)
return create_jobs([job])[0]
@pytest.fixture
def test_two_jobs_tc_metadata(eleven_job_blobs_new_date, create_jobs):
job_1, job_2 = eleven_job_blobs_new_date[0:2]
job_1['job'].update(
{
'status': 'completed',
'result': 'testfailed',
'taskcluster_task_id': 'V3SVuxO8TFy37En_6HcXLs',
'taskcluster_retry_id': '0',
}
)
job_2['job'].update(
{
'status': 'completed',
'result': 'testfailed',
'taskcluster_task_id': 'FJtjczXfTAGClIl6wNBo9g',
'taskcluster_retry_id': '0',
}
)
return create_jobs([job_1, job_2])
@pytest.fixture
def test_job_2(eleven_job_blobs, create_jobs):
return create_jobs(eleven_job_blobs[0:2])[1]
@pytest.fixture
def test_job_3(eleven_job_blobs, create_jobs):
return create_jobs(eleven_job_blobs[0:3])[2]
@pytest.fixture
def mock_log_parser(monkeypatch):
from celery import shared_task
from treeherder.log_parser import tasks
@shared_task
def task_mock(*args, **kwargs):
pass
monkeypatch.setattr(tasks, 'parse_logs', task_mock)
@pytest.fixture
def taskcluster_notify_mock(monkeypatch):
mock = MagicMock()
def mockreturn(*arg, **kwargs):
nonlocal mock
return mock
monkeypatch.setattr(taskcluster, 'notify_client_factory', mockreturn)
return mock
@pytest.fixture
def mock_tc_prod_backfill_credentials(monkeypatch):
monkeypatch.setattr(settings, 'PERF_SHERIFF_BOT_CLIENT_ID', "client_id")
monkeypatch.setattr(settings, 'PERF_SHERIFF_BOT_ACCESS_TOKEN', "access_token")
@pytest.fixture
def mock_tc_prod_notify_credentials(monkeypatch):
monkeypatch.setattr(settings, 'NOTIFY_CLIENT_ID', "client_id")
monkeypatch.setattr(settings, 'NOTIFY_ACCESS_TOKEN', "access_token")
@pytest.fixture
def push_stored(test_repository, sample_push):
store_push_data(test_repository, sample_push)
return sample_push
@pytest.fixture
def try_push_stored(try_repository, sample_push):
store_push_data(try_repository, sample_push)
return sample_push
@pytest.fixture
def eleven_job_blobs(sample_data, sample_push, test_repository, mock_log_parser):
store_push_data(test_repository, sample_push)
num_jobs = 11
jobs = sample_data.job_data[0:num_jobs]
max_index = len(sample_push) - 1
push_index = 0
task_id_index = 0
blobs = []
for blob in jobs:
if push_index > max_index:
push_index = 0
# Modify job structure to sync with the push sample data
if 'sources' in blob:
del blob['sources']
blob['revision'] = sample_push[push_index]['revision']
blob['taskcluster_task_id'] = 'V3SVuxO8TFy37En_6HcXL{}'.format(task_id_index)
blob['taskcluster_retry_id'] = '0'
blobs.append(blob)
push_index += 1
task_id_index += 1
return blobs
@pytest.fixture
def eleven_job_blobs_new_date(sample_data, sample_push, test_repository, mock_log_parser):
# make unique revisions
counter = 0
for push in sample_push:
push['push_timestamp'] = int(time.time()) + counter
counter += 1
store_push_data(test_repository, sample_push)
num_jobs = 11
jobs = sample_data.job_data[0:num_jobs]
max_index = len(sample_push) - 1
push_index = 0
task_id_index = 0
blobs = []
for blob in jobs:
if push_index > max_index:
push_index = 0
# Modify job structure to sync with the push sample data
if 'sources' in blob:
del blob['sources']
blob['revision'] = sample_push[push_index]['revision']
blob['taskcluster_task_id'] = 'V3SVuxO8TFy37En_6HcX{:0>2}'.format(task_id_index)
blob['taskcluster_retry_id'] = '0'
blob['job']['revision'] = sample_push[push_index]['revision']
blob['job']['submit_timestamp'] = sample_push[push_index]['push_timestamp']
blob['job']['start_timestamp'] = sample_push[push_index]['push_timestamp'] + 10
blob['job']['end_timestamp'] = sample_push[push_index]['push_timestamp'] + 1000
blobs.append(blob)
push_index += 1
task_id_index += 1
return blobs
@pytest.fixture
def eleven_jobs_stored_new_date(
test_repository, failure_classifications, eleven_job_blobs_new_date
):
"""stores a list of 11 job samples"""
store_job_data(test_repository, eleven_job_blobs_new_date)
@pytest.fixture
def eleven_jobs_stored(test_repository, failure_classifications, eleven_job_blobs):
"""stores a list of 11 job samples"""
store_job_data(test_repository, eleven_job_blobs)
@pytest.fixture
def taskcluster_jobs_stored(test_repository, sample_data):
"""stores a list of TaskCluster job samples"""
store_job_data(test_repository, sample_data.transformed_pulse_jobs)
@pytest.fixture
def test_job_with_notes(test_job, test_user):
"""test job with job notes."""
for failure_classification_id in [2, 3]:
th_models.JobNote.objects.create(
job=test_job,
failure_classification_id=failure_classification_id,
user=test_user,
text="you look like a man-o-lantern",
)
test_job.refresh_from_db()
return test_job
@pytest.fixture
def activate_responses(request):
responses.start()
def fin():
responses.reset()
responses.stop()
request.addfinalizer(fin)
@pytest.fixture
def pulse_connection():
"""
Build a Pulse connection with the Kombu library
This is a non-lazy mirror of our Pulse service's build_connection as
explained in: https://bugzilla.mozilla.org/show_bug.cgi?id=1484196
"""
return kombu.Connection(settings.CELERY_BROKER_URL)
@pytest.fixture
def pulse_exchange(pulse_connection, request):
def build_exchange(name, create_exchange):
return get_exchange(pulse_connection, name, create=create_exchange)
return build_exchange
@pytest.fixture
def failure_lines(test_job):
return create_failure_lines(test_job, [(test_line, {}), (test_line, {"subtest": "subtest2"})])
@pytest.fixture
def failure_line_logs(test_job):
return create_failure_lines(
test_job,
[(test_line, {'action': 'log', 'test': None}), (test_line, {'subtest': 'subtest2'})],
)
@pytest.fixture
def failure_classifications(transactional_db):
for name in [
"not classified",
"fixed by commit",
"expected fail",
"intermittent",
"infra",
"intermittent needs filing",
"autoclassified intermittent",
]:
th_models.FailureClassification(name=name).save()
@pytest.fixture
def text_log_errors_failure_lines(test_job, failure_lines):
lines = [(test_line, {}), (test_line, {"subtest": "subtest2"})]
text_log_errors = create_text_log_errors(test_job, lines)
for error_line, failure_line in zip(text_log_errors, failure_lines):
th_models.TextLogErrorMetadata.objects.create(
text_log_error=error_line, failure_line=failure_line
)
return text_log_errors, failure_lines
@pytest.fixture
def test_matcher(request):
return "TreeherderUnitTestDetector"
@pytest.fixture
def classified_failures(
test_job, text_log_errors_failure_lines, test_matcher, failure_classifications
):
_, failure_lines = text_log_errors_failure_lines
classified_failures = []
for failure_line in failure_lines:
if failure_line.job_guid == test_job.guid:
classified_failure = th_models.ClassifiedFailure.objects.create()
failure_line.error.create_match(test_matcher, classified_failure)
classified_failures.append(classified_failure)
return classified_failures
@pytest.fixture
def test_user(db):
# a user *without* sheriff/staff permissions
user = th_models.User.objects.create(username="testuser1", email='[email protected]', is_staff=False)
return user
@pytest.fixture
def test_ldap_user(db):
"""
A user whose username matches those generated for LDAP SSO logins,
and who does not have `is_staff` permissions.
"""
user = th_models.User.objects.create(
username="mozilla-ldap/[email protected]", email='[email protected]', is_staff=False
)
return user
@pytest.fixture
def test_sheriff(db):
# a user *with* sheriff/staff permissions
user = th_models.User.objects.create(
username="testsheriff1", email='[email protected]', is_staff=True
)
return user
@pytest.fixture
def test_perf_framework(transactional_db):
return perf_models.PerformanceFramework.objects.create(name='test_talos', enabled=True)
@pytest.fixture
def test_perf_signature(test_repository, test_perf_framework) -> perf_models.PerformanceSignature:
windows_7_platform = th_models.MachinePlatform.objects.create(
os_name='win', platform='win7', architecture='x86'
)
return create_perf_signature(test_perf_framework, test_repository, windows_7_platform)
def create_perf_signature(
perf_framework, repository, machine_platform: th_models.MachinePlatform
) -> perf_models.PerformanceSignature:
option = th_models.Option.objects.create(name='opt')
option_collection = th_models.OptionCollection.objects.create(
option_collection_hash='my_option_hash', option=option
)
return perf_models.PerformanceSignature.objects.create(
repository=repository,
signature_hash=(40 * 't'),
framework=perf_framework,
platform=machine_platform,
option_collection=option_collection,
suite='mysuite',
test='mytest',
application='firefox',
has_subtests=False,
tags='warm pageload',
extra_options='e10s opt',
measurement_unit='ms',
last_updated=datetime.datetime.now(),
)
@pytest.fixture
def test_taskcluster_metadata(test_job_2) -> th_models.TaskclusterMetadata:
return create_taskcluster_metadata(test_job_2)
@pytest.fixture
def test_taskcluster_metadata_2(test_job_3) -> th_models.TaskclusterMetadata:
return create_taskcluster_metadata_2(test_job_3)
def create_taskcluster_metadata(test_job_2) -> th_models.TaskclusterMetadata:
return th_models.TaskclusterMetadata.objects.create(
job=test_job_2,
task_id='V3SVuxO8TFy37En_6HcXLp',
retry_id='0',
)
def create_taskcluster_metadata_2(test_job_3) -> th_models.TaskclusterMetadata:
return th_models.TaskclusterMetadata.objects.create(
job=test_job_3,
task_id='V3SVuxO8TFy37En_6HcXLq',
retry_id='0',
)
@pytest.fixture
def test_perf_signature_2(test_perf_signature):
return perf_models.PerformanceSignature.objects.create(
repository=test_perf_signature.repository,
signature_hash=(20 * 't2'),
framework=test_perf_signature.framework,
platform=test_perf_signature.platform,
option_collection=test_perf_signature.option_collection,
suite='mysuite2',
test='mytest2',
has_subtests=test_perf_signature.has_subtests,
extra_options=test_perf_signature.extra_options,
last_updated=datetime.datetime.now(),
)
@pytest.fixture
def test_stalled_data_signature(test_perf_signature):
stalled_data_timestamp = datetime.datetime.now() - datetime.timedelta(days=120)
return perf_models.PerformanceSignature.objects.create(
repository=test_perf_signature.repository,
signature_hash=(20 * 't3'),
framework=test_perf_signature.framework,
platform=test_perf_signature.platform,
option_collection=test_perf_signature.option_collection,
suite='mysuite3',
test='mytest3',
has_subtests=test_perf_signature.has_subtests,
extra_options=test_perf_signature.extra_options,
last_updated=stalled_data_timestamp,
)
@pytest.fixture
def test_perf_data(test_perf_signature, eleven_jobs_stored):
# for making things easier, ids for jobs
# and push should be the same;
# also, we only need a subset of jobs
perf_jobs = th_models.Job.objects.filter(pk__in=range(7, 11)).order_by('id').all()
for index, job in enumerate(perf_jobs, start=1):
job.push_id = index
job.save()
perf_datum = perf_models.PerformanceDatum.objects.create(
value=10,
push_timestamp=job.push.time,
job=job,
push=job.push,
repository=job.repository,
signature=test_perf_signature,
)
perf_datum.push.time = job.push.time
perf_datum.push.save()
return perf_models.PerformanceDatum.objects.order_by('id').all()
@pytest.fixture
def mock_bugzilla_api_request(monkeypatch):
"""Mock fetch_json() used by Bugzilla ETL to return a local sample file."""
def _fetch_json(url, params=None):
tests_folder = os.path.dirname(__file__)
bug_list_path = os.path.join(tests_folder, "sample_data", "bug_list.json")
with open(bug_list_path) as f:
last_change_time = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).strftime(
'%Y-%m-%dT%H:%M:%SZ'
)
data = json.load(f)
for bug in data["bugs"]:
bug["last_change_time"] = last_change_time
return data
monkeypatch.setattr(treeherder.etl.bugzilla, 'fetch_json', _fetch_json)
@pytest.fixture
def mock_deviance(monkeypatch):
"""
This mock should only be used when
dealing with a time-series of constant values.
"""
def _deviance(*args, **kwargs):
return "OK", 0
monkeypatch.setattr(moz_measure_noise, 'deviance', _deviance)
@pytest.fixture
def bugs(mock_bugzilla_api_request):
from treeherder.etl.bugzilla import BzApiBugProcess
process = BzApiBugProcess()
process.run()
return th_models.Bugscache.objects.all().order_by('id')
@pytest.fixture
def mock_bugzilla_reopen_request(monkeypatch, request):
"""Mock reopen_request() used to reopen incomplete bugs."""
def _reopen_request(url, method, headers, json):
import json as json_module
reopened_bugs = request.config.cache.get('reopened_bugs', {})
reopened_bugs[url] = json_module.dumps(json)
request.config.cache.set('reopened_bugs', reopened_bugs)
monkeypatch.setattr(treeherder.etl.bugzilla, 'reopen_request', _reopen_request)
@pytest.fixture
def client():
"""
A django-rest-framework APIClient instance:
http://www.django-rest-framework.org/api-guide/testing/#apiclient
"""
return APIClient()
@pytest.fixture
def authorized_sheriff_client(client, test_sheriff):
client.force_authenticate(user=test_sheriff)
return client
@pytest.fixture
def mock_file_bugzilla_map_request(monkeypatch):
"""
Mock fetch_json() used by files_bugzilla_map ETL to return local sample
files which map source files to Bugzilla components.
"""
import treeherder.etl.files_bugzilla_map
def _fetch_data(self, project):
url = (
'https://firefox-ci-tc.services.mozilla.com/api/index/v1/task/gecko.v2.%s.latest.source.source-bugzilla-info/artifacts/public/components.json'
% project
)
files_bugzilla_data = None
file_name = "files_bugzilla_map_%s_%s.json" % (project, self.run_id)
exception = None
try:
tests_folder = os.path.dirname(__file__)
data_path = os.path.join(tests_folder, "sample_data", "files_bugzilla_map", file_name)
with open(data_path) as f:
files_bugzilla_data = json.load(f)
except Exception as e:
exception = e
return {
"url": url,
"files_bugzilla_data": files_bugzilla_data,
"exception": exception,
}
monkeypatch.setattr(
treeherder.etl.files_bugzilla_map.FilesBugzillaMapProcess, 'fetch_data', _fetch_data
)
@pytest.fixture
def mock_bugscache_bugzilla_request(monkeypatch):
"""
Mock fetch_intermittent_bugs() used by bugzilla ETL to return local Bugzilla
sample data.
"""
def _fetch_intermittent_bugs(additional_params, limit, duplicate_chain_length):
tests_folder = os.path.dirname(__file__)
file_name = "run-%s.json" % str(duplicate_chain_length)
data_path = os.path.join(tests_folder, "sample_data", "bugscache_population", file_name)
with open(data_path) as f:
bugzilla_data = json.load(f)
for bug in bugzilla_data["bugs"]:
bug["last_change_time"] = (
datetime.datetime.now() - datetime.timedelta(20)
).isoformat(timespec='seconds') + 'Z'
return bugzilla_data["bugs"]
monkeypatch.setattr(
treeherder.etl.bugzilla, 'fetch_intermittent_bugs', _fetch_intermittent_bugs
)
@pytest.fixture
def text_log_error_lines(test_job, failure_lines):
lines = [
(item, {}) for item in th_models.FailureLine.objects.filter(job_guid=test_job.guid).values()
]
errors = create_text_log_errors(test_job, lines)
return errors
@pytest.fixture
def test_perf_tag():
return perf_models.PerformanceTag.objects.create(name='first_tag')
@pytest.fixture
def test_perf_tag_2():
return perf_models.PerformanceTag.objects.create(name='second_tag')
@pytest.fixture
def test_perf_alert_summary(test_repository, push_stored, test_perf_framework, test_issue_tracker):
test_perf_tag = perf_models.PerformanceTag.objects.create(name='harness')
performance_alert_summary = perf_models.PerformanceAlertSummary.objects.create(
repository=test_repository,
framework=test_perf_framework,
prev_push_id=1,
push_id=2,
manually_created=False,
created=datetime.datetime.now(),
)
performance_alert_summary.performance_tags.add(test_perf_tag)
return performance_alert_summary
@pytest.fixture
def test_perf_alert_summary_2(test_perf_alert_summary):
return perf_models.PerformanceAlertSummary.objects.create(
repository=test_perf_alert_summary.repository,
framework=test_perf_alert_summary.framework,
prev_push_id=test_perf_alert_summary.prev_push_id + 1,
push_id=test_perf_alert_summary.push_id + 1,
manually_created=False,
created=datetime.datetime.now(),
)
@pytest.fixture
def test_perf_alert_summary_with_bug(
test_repository, push_stored, test_perf_framework, test_issue_tracker
):
return perf_models.PerformanceAlertSummary.objects.create(
repository=test_repository,
framework=test_perf_framework,
prev_push_id=1,
push_id=2,
manually_created=False,
created=datetime.datetime.now(),
bug_number=123456,
bug_updated=datetime.datetime.now(),
)
@pytest.fixture
def test_perf_datum(test_repository, test_perf_signature, test_job_2):
push = th_models.Push.objects.get(id=1)
perf_models.PerformanceDatum.objects.create(
repository=test_repository,
job=test_job_2,
push_id=1,
signature=test_perf_signature,
value=1,
push_timestamp=push.time,
)
@pytest.fixture
def test_perf_datum_2(test_repository, test_perf_signature, test_job_3):
push = th_models.Push.objects.get(id=2)
perf_models.PerformanceDatum.objects.create(
repository=test_repository,
job=test_job_3,
push_id=2,
signature=test_perf_signature,
value=1,
push_timestamp=push.time,
)
@pytest.fixture
def test_perf_alert(test_perf_signature, test_perf_alert_summary) -> perf_models.PerformanceAlert:
return create_perf_alert(summary=test_perf_alert_summary, series_signature=test_perf_signature)
@pytest.fixture
def test_perf_alert_with_tcmetadata(
test_perf_signature, test_perf_alert_summary
) -> perf_models.PerformanceAlert:
perf_alert = create_perf_alert(
summary=test_perf_alert_summary, series_signature=test_perf_signature
)
perf_alert.taskcluster_metadata = test_taskcluster_metadata_2
perf_alert.prev_taskcluster_metadata = test_taskcluster_metadata
perf_alert.save()
return perf_alert
def create_perf_alert(**alert_properties) -> perf_models.PerformanceAlert: