Repository navigation
Expand file tree
/
Copy pathtest_quality_control.py
More file actions
2256 lines (1944 loc) · 86.3 KB
/
Copy pathtest_quality_control.py
File metadata and controls
2256 lines (1944 loc) · 86.3 KB
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
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import json
import math
from collections.abc import Collection, Iterable
from copy import deepcopy
from functools import partial
from http import HTTPStatus
from itertools import groupby, product
from typing import Any, Callable, Optional
import pytest
from cvat_sdk.api_client import exceptions, models
from cvat_sdk.api_client.api_client import ApiClient, Endpoint
from cvat_sdk.core.helpers import get_paginated_collection
from deepdiff import DeepDiff
from shared.tasks.utils import parse_frame_step
from shared.utils.config import make_api_client
from .utils import (
CollectionSimpleFilterTestBase,
invite_user_to_org,
register_new_user,
wait_background_request,
)
class _PermissionTestBase:
def create_quality_report(
self, *, user: str, task_id: Optional[int] = None, project_id: Optional[int] = None
) -> dict:
assert task_id is not None or project_id is not None
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.create_report(
quality_report_create_request=models.QualityReportCreateRequest(
**{"task_id": task_id} if task_id else {},
**{"project_id": project_id} if project_id else {},
),
_parse_response=False,
)
assert response.status == HTTPStatus.ACCEPTED
rq_id = json.loads(response.data)["rq_id"]
background_request, _ = wait_background_request(api_client, rq_id)
assert (
background_request.status.value
== models.RequestStatus.allowed_values[("value",)]["FINISHED"]
)
report_id = background_request.result_id
_, response = api_client.quality_api.retrieve_report(report_id, _parse_response=False)
return json.loads(response.data)
def create_gt_job(self, user: str, task_id: int, *, complete: bool = True) -> models.IJobRead:
with make_api_client(user) as api_client:
(meta, _) = api_client.tasks_api.retrieve_data_meta(task_id)
start_frame = meta.start_frame
(job, _) = api_client.jobs_api.create(
models.JobWriteRequest(
type="ground_truth",
task_id=task_id,
frame_selection_method="manual",
frames=[start_frame],
)
)
if complete:
(labels, _) = api_client.labels_api.list(
**({"project_id": job.project_id} if job.project_id else {"task_id": task_id})
)
api_client.jobs_api.update_annotations(
job.id,
labeled_data_request=dict(
shapes=[
dict(
frame=start_frame,
label_id=labels.results[0].id,
type="rectangle",
points=[1, 1, 2, 2],
),
],
),
)
api_client.jobs_api.partial_update(
job.id,
patched_job_write_request={
"stage": "acceptance",
"state": "completed",
},
)
return job
@pytest.fixture(scope="class")
def find_sandbox_task(self, tasks, jobs, users, is_task_staff):
def _find(
is_staff: bool, *, has_gt_jobs: Optional[bool] = None
) -> tuple[dict[str, Any], dict[str, Any]]:
task = next(
t
for t in tasks
if t["organization"] is None
and not users[t["owner"]["id"]]["is_superuser"]
and (
has_gt_jobs is None
or has_gt_jobs
== any(
j for j in jobs if j["task_id"] == t["id"] and j["type"] == "ground_truth"
)
)
)
if is_staff:
user = task["owner"]
else:
user = next(u for u in users if not is_task_staff(u["id"], task["id"]))
return task, user
return _find
@pytest.fixture(scope="class")
def find_sandbox_task_without_gt(self, find_sandbox_task):
return partial(find_sandbox_task, has_gt_jobs=False)
@pytest.fixture(scope="class")
def find_org_task(self, tasks, jobs, users, is_org_member, is_task_staff):
def _find(
is_staff: bool, user_org_role: str, *, has_gt_jobs: Optional[bool] = None
) -> tuple[dict[str, Any], dict[str, Any]]:
for user in users:
if user["is_superuser"]:
continue
task = next(
(
t
for t in tasks
if t["organization"] is not None
and is_task_staff(user["id"], t["id"]) == is_staff
and is_org_member(user["id"], t["organization"], role=user_org_role)
and (
has_gt_jobs is None
or has_gt_jobs
== any(
j
for j in jobs
if j["task_id"] == t["id"] and j["type"] == "ground_truth"
)
)
),
None,
)
if task is not None:
break
assert task
return task, user
return _find
@pytest.fixture(scope="class")
def find_org_task_without_gt(self, find_org_task):
return partial(find_org_task, has_gt_jobs=False)
@pytest.fixture(scope="class")
def find_sandbox_project(self, projects, tasks, users, labels, is_project_staff):
def _find(
is_staff: bool, has_gt_jobs: Optional[bool] = False
) -> tuple[dict[str, Any], dict[str, Any]]:
project = next(
p
for p in projects
if p["organization"] is None
if not users[p["owner"]["id"]]["is_superuser"]
if any(l for l in labels if l.get("project_id") == p["id"])
if any(t for t in tasks if t["project_id"] == p["id"] and t["size"])
if (
has_gt_jobs is None
or has_gt_jobs
== any(t["validation_mode"] for t in tasks if t["project_id"] == p["id"])
)
)
if is_staff:
user = project["owner"]
else:
user = next(u for u in users if not is_project_staff(u["id"], project["id"]))
return project, user
return _find
@pytest.fixture(scope="class")
def find_sandbox_project_without_validation(self, find_sandbox_project):
return partial(find_sandbox_project, has_gt_jobs=False)
@pytest.fixture
def find_org_project(
self,
restore_db_per_function,
admin_user,
projects,
tasks,
users,
labels,
is_org_member,
is_project_staff,
):
def _find(
is_staff: bool, user_org_role: str, has_gt_jobs: Optional[bool] = False
) -> tuple[dict[str, Any], dict[str, Any]]:
project = None
for user in users:
if user["is_superuser"]:
continue
project = next(
(
p
for p in projects
if p["organization"] is not None
if any(l for l in labels if l.get("project_id") == p["id"])
if (
has_gt_jobs is None
or has_gt_jobs
== any(
t["validation_mode"] for t in tasks if t["project_id"] == p["id"]
)
)
if any(t for t in tasks if t["project_id"] == p["id"] and t["size"])
if is_project_staff(user["id"], p["id"]) == is_staff
if is_org_member(user["id"], p["organization"], role=user_org_role)
),
None,
)
if project is not None:
break
if not project:
project = next(
p
for p in projects
if p["organization"] is not None
if any(l for l in labels if l.get("project_id") == p["id"])
if any(t for t in tasks if t["project_id"] == p["id"] and t["size"])
if (
has_gt_jobs is None
or has_gt_jobs
== any(t["validation_mode"] for t in tasks if t["project_id"] == p["id"])
)
)
user = next(
u
for u in users
if is_org_member(u["id"], project["organization"], role=user_org_role)
)
if is_staff:
with make_api_client(admin_user) as api_client:
api_client.projects_api.partial_update(
project["id"],
patched_project_write_request=models.PatchedProjectWriteRequest(
assignee_id=user["id"]
),
)
return project, user
return _find
@pytest.fixture
def find_org_project_without_validation(self, find_org_project):
return partial(find_org_project, has_gt_jobs=False)
_default_sandbox_cases = ("is_staff, allow", [(True, True), (False, False)])
_default_org_cases = (
"org_role, is_staff, allow",
[
("owner", True, True),
("owner", False, True),
("maintainer", True, True),
("maintainer", False, True),
("supervisor", True, True),
("supervisor", False, False),
("worker", True, True),
("worker", False, False),
],
)
_default_org_roles = ("owner", "maintainer", "supervisor", "worker")
key_field_for_target = {
"project": "project_id",
"task": "task_id",
"job": "job_id",
}
@pytest.mark.usefixtures("restore_db_per_class")
class TestListQualityReports(_PermissionTestBase):
def _test_list_reports_200(self, user, *, expected_data=None, **kwargs):
with make_api_client(user) as api_client:
results = get_paginated_collection(
api_client.quality_api.list_reports_endpoint,
return_json=True,
**kwargs,
)
if expected_data is not None:
assert DeepDiff(expected_data, results) == {}
def _test_list_reports_403(self, user, **kwargs):
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.list_reports(
**kwargs, _parse_response=False, _check_status=False
)
assert response.status == HTTPStatus.FORBIDDEN
def test_can_list_quality_reports(self, admin_user, quality_reports):
reports = sorted(quality_reports, key=lambda r: -r["id"])
self._test_list_reports_200(admin_user, sort="-id", expected_data=reports)
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.parametrize("target", ["project", "task", "job"])
@pytest.mark.parametrize(*_PermissionTestBase._default_sandbox_cases)
def test_user_list_reports_in_sandbox(
self,
is_staff,
allow,
admin_user,
tasks,
find_sandbox_task_without_gt,
find_sandbox_project_without_validation,
target,
):
if target == "project":
project, user = find_sandbox_project_without_validation(is_staff)
task = next(t for t in tasks if t["project_id"] == project["id"] and t["size"])
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, project_id=project["id"])
target_id = project["id"]
else:
task, user = find_sandbox_task_without_gt(is_staff)
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, task_id=task["id"])
target_id = task["id"]
if target == "job":
with make_api_client(admin_user) as api_client:
report = json.loads(
api_client.quality_api.list_reports(target="job", parent_id=report["id"])[
1
].data
)["results"][0]
target_id = report["job_id"]
list_kwargs = {
"user": user["username"],
"target": target,
self.key_field_for_target[target]: target_id,
}
if allow:
self._test_list_reports_200(expected_data=[report], **list_kwargs)
else:
self._test_list_reports_403(**list_kwargs)
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.parametrize("target", ["project", "task", "job"])
@pytest.mark.parametrize(*_PermissionTestBase._default_org_cases)
def test_user_list_reports_in_org(
self,
find_org_task_without_gt,
find_org_project_without_validation,
tasks,
org_role,
is_staff,
allow,
admin_user,
target,
):
if target == "project":
project, user = find_org_project_without_validation(is_staff, org_role)
task = next(t for t in tasks if t["project_id"] == project["id"] and t["size"])
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, project_id=project["id"])
target_id = project["id"]
else:
task, user = find_org_task_without_gt(is_staff, org_role)
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, task_id=task["id"])
target_id = task["id"]
if target == "job":
with make_api_client(admin_user) as api_client:
report = json.loads(
api_client.quality_api.list_reports(target="job", parent_id=report["id"])[
1
].data
)["results"][0]
target_id = report["job_id"]
list_kwargs = {
"user": user["username"],
"target": target,
self.key_field_for_target[target]: target_id,
}
if allow:
self._test_list_reports_200(expected_data=[report], **list_kwargs)
else:
self._test_list_reports_403(**list_kwargs)
@pytest.mark.usefixtures("restore_db_per_class")
class TestGetQualityReports(_PermissionTestBase):
def _test_get_report_200(
self, user: str, obj_id: int, *, expected_data: Optional[dict[str, Any]] = None, **kwargs
):
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.retrieve_report(obj_id, **kwargs)
assert response.status == HTTPStatus.OK
if expected_data is not None:
assert DeepDiff(expected_data, json.loads(response.data), ignore_order=True) == {}
return response
def _test_get_report_403(self, user: str, obj_id: int, **kwargs):
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.retrieve_report(
obj_id, **kwargs, _parse_response=False, _check_status=False
)
assert response.status == HTTPStatus.FORBIDDEN
return response
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.parametrize(*_PermissionTestBase._default_sandbox_cases)
def test_user_get_report_in_sandbox_task(
self, is_staff, allow, admin_user, find_sandbox_task_without_gt
):
task, user = find_sandbox_task_without_gt(is_staff)
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, task_id=task["id"])
if allow:
self._test_get_report_200(user["username"], report["id"], expected_data=report)
else:
self._test_get_report_403(user["username"], report["id"])
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.parametrize(*_PermissionTestBase._default_org_cases)
def test_user_get_report_in_org_task(
self,
find_org_task_without_gt,
org_role,
is_staff,
allow,
admin_user,
):
task, user = find_org_task_without_gt(is_staff, org_role)
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, task_id=task["id"])
if allow:
self._test_get_report_200(user["username"], report["id"], expected_data=report)
else:
self._test_get_report_403(user["username"], report["id"])
@pytest.mark.usefixtures("restore_db_per_class")
class TestGetQualityReportData(_PermissionTestBase):
def _test_get_report_data_200(
self, user: str, obj_id: int, *, expected_data: Optional[dict[str, Any]] = None, **kwargs
):
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.retrieve_report_data(obj_id, **kwargs)
assert response.status == HTTPStatus.OK
if expected_data is not None:
assert DeepDiff(expected_data, json.loads(response.data), ignore_order=True) == {}
return response
def _test_get_report_data_403(self, user: str, obj_id: int, **kwargs):
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.retrieve_report_data(
obj_id, **kwargs, _parse_response=False, _check_status=False
)
assert response.status == HTTPStatus.FORBIDDEN
return response
@pytest.mark.parametrize("target", ["project", "task", "job"])
def test_can_get_full_report_data(self, admin_user, target, quality_reports):
report = next(
r for r in quality_reports if r[self.key_field_for_target[target]] is not None
)
report_id = report["id"]
with make_api_client(admin_user) as api_client:
(report_data, response) = api_client.quality_api.retrieve_report_data(report_id)
assert response.status == HTTPStatus.OK
# Just check several keys exist
for key in ["parameters", "comparison_summary"] + (
["frame_results"] if target != "project" else []
):
assert key in report_data.keys(), key
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.parametrize(*_PermissionTestBase._default_sandbox_cases)
def test_user_get_report_data_in_sandbox_task(
self, is_staff, allow, admin_user, find_sandbox_task_without_gt
):
task, user = find_sandbox_task_without_gt(is_staff)
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, task_id=task["id"])
report_data = json.loads(self._test_get_report_data_200(admin_user, report["id"]).data)
if allow:
self._test_get_report_data_200(
user["username"], report["id"], expected_data=report_data
)
else:
self._test_get_report_data_403(user["username"], report["id"])
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.parametrize(*_PermissionTestBase._default_org_cases)
def test_user_get_report_data_in_org_task(
self,
find_org_task_without_gt,
org_role,
is_staff,
allow,
admin_user,
):
task, user = find_org_task_without_gt(is_staff, org_role)
self.create_gt_job(admin_user, task["id"])
report = self.create_quality_report(user=admin_user, task_id=task["id"])
report_data = json.loads(self._test_get_report_data_200(admin_user, report["id"]).data)
if allow:
self._test_get_report_data_200(
user["username"], report["id"], expected_data=report_data
)
else:
self._test_get_report_data_403(user["username"], report["id"])
@pytest.mark.usefixtures("restore_db_per_function")
@pytest.mark.parametrize("has_assignee", [False, True])
def test_can_get_report_data_with_job_assignees(
self, admin_user, jobs, users_by_name, has_assignee
):
gt_job = next(
j
for j in jobs
if j["type"] == "ground_truth"
and j["stage"] == "acceptance"
and j["state"] == "completed"
)
task_id = gt_job["task_id"]
normal_job = next(j for j in jobs if j["type"] == "annotation" and j["task_id"] == task_id)
if has_assignee:
new_assignee = users_by_name[admin_user]
else:
new_assignee = None
if bool(normal_job["assignee"]) != has_assignee:
with make_api_client(admin_user) as api_client:
api_client.jobs_api.partial_update(
normal_job["id"],
patched_job_write_request={
"assignee": new_assignee["id"] if new_assignee else None
},
)
task_report = self.create_quality_report(user=admin_user, task_id=task_id)
with make_api_client(admin_user) as api_client:
job_report = api_client.quality_api.list_reports(
job_id=normal_job["id"], parent_id=task_report["id"]
)[0].results[0]
report_data = json.loads(self._test_get_report_data_200(admin_user, job_report["id"]).data)
assert (
DeepDiff(
(
{
k: v
for k, v in new_assignee.items()
if k in ["id", "username", "first_name", "last_name"]
}
if new_assignee
else None
),
report_data["assignee"],
)
== {}
)
@pytest.mark.usefixtures("restore_db_per_function")
class TestPostQualityReports(_PermissionTestBase):
def test_can_create_report(self, admin_user, jobs):
gt_job = next(
j
for j in jobs
if j["type"] == "ground_truth"
and j["stage"] == "acceptance"
and j["state"] == "completed"
)
task_id = gt_job["task_id"]
report = self.create_quality_report(user=admin_user, task_id=task_id)
assert models.QualityReport._from_openapi_data(**report)
@pytest.mark.parametrize("has_assignee", [False, True])
def test_can_create_report_with_job_assignees(
self, admin_user, jobs, users_by_name, has_assignee
):
gt_job = next(
j
for j in jobs
if j["type"] == "ground_truth"
and j["stage"] == "acceptance"
and j["state"] == "completed"
)
task_id = gt_job["task_id"]
normal_job = next(j for j in jobs if j["type"] == "annotation")
if bool(normal_job["assignee"]) != has_assignee:
with make_api_client(admin_user) as api_client:
api_client.jobs_api.partial_update(
normal_job["id"],
patched_job_write_request={
"assignee": users_by_name[admin_user]["id"] if has_assignee else None
},
)
report = self.create_quality_report(user=admin_user, task_id=task_id)
assert models.QualityReport._from_openapi_data(**report)
def test_cannot_create_report_without_gt_job(self, admin_user, tasks):
task_id = next(t["id"] for t in tasks if t["jobs"]["count"] == 1)
with pytest.raises(exceptions.ApiException) as capture:
self.create_quality_report(user=admin_user, task_id=task_id)
assert (
"Quality reports require a Ground Truth job in the task at the acceptance "
"stage and in the completed state"
) in capture.value.body
@pytest.mark.parametrize(
"field_name, field_value",
[
("stage", "annotation"),
("stage", "validation"),
("state", "new"),
("state", "in progress"),
("state", "rejected"),
],
)
def test_cannot_create_report_with_incomplete_gt_job(
self, admin_user, jobs, field_name, field_value
):
gt_job = next(
j
for j in jobs
if j["type"] == "ground_truth"
and j["stage"] == "acceptance"
and j["state"] == "completed"
)
task_id = gt_job["task_id"]
with make_api_client(admin_user) as api_client:
api_client.jobs_api.partial_update(
gt_job["id"], patched_job_write_request={field_name: field_value}
)
with pytest.raises(exceptions.ApiException) as capture:
self.create_quality_report(user=admin_user, task_id=task_id)
assert (
"Quality reports require a Ground Truth job in the task at the acceptance "
"stage and in the completed state"
) in capture.value.body
def _test_create_report_200(self, user: str, task_id: int):
return self.create_quality_report(user=user, task_id=task_id)
def _test_create_report_403(self, user: str, task_id: int):
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.create_report(
quality_report_create_request=models.QualityReportCreateRequest(task_id=task_id),
_parse_response=False,
_check_status=False,
)
assert response.status == HTTPStatus.FORBIDDEN
return response
@pytest.mark.parametrize(*_PermissionTestBase._default_sandbox_cases)
def test_user_create_report_in_sandbox_task(
self, is_staff, allow, admin_user, find_sandbox_task_without_gt
):
task, user = find_sandbox_task_without_gt(is_staff)
self.create_gt_job(admin_user, task["id"])
if allow:
self._test_create_report_200(user["username"], task["id"])
else:
self._test_create_report_403(user["username"], task["id"])
@pytest.mark.parametrize(*_PermissionTestBase._default_org_cases)
def test_user_create_report_in_org_task(
self,
find_org_task_without_gt,
org_role,
is_staff,
allow,
admin_user,
):
task, user = find_org_task_without_gt(is_staff, org_role)
self.create_gt_job(admin_user, task["id"])
if allow:
self._test_create_report_200(user["username"], task["id"])
else:
self._test_create_report_403(user["username"], task["id"])
@staticmethod
def _initialize_report_creation(task_id: int, user: str) -> str:
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.create_report(
quality_report_create_request=models.QualityReportCreateRequest(task_id=task_id),
_parse_response=False,
)
rq_id = json.loads(response.data)["rq_id"]
assert rq_id
return rq_id
# users with task:view rights can check status of report creation
def _test_check_status_of_report_creation(
self,
rq_id: str,
*,
task_staff: str,
another_user: str,
another_user_status: int = HTTPStatus.FORBIDDEN,
):
with make_api_client(another_user) as api_client:
(_, response) = api_client.requests_api.retrieve(
rq_id, _parse_response=False, _check_status=False
)
assert response.status == another_user_status
with make_api_client(task_staff) as api_client:
wait_background_request(api_client, rq_id)
@pytest.mark.parametrize(
"role",
# owner and maintainer have rights even without being assigned to a task
("supervisor", "worker"),
)
def test_task_assignee_can_check_status_of_report_creation_in_org(
self,
find_org_task_without_gt: Callable[[bool, str], tuple[dict[str, Any], dict[str, Any]]],
role: str,
admin_user: str,
):
task, another_user = find_org_task_without_gt(is_staff=False, user_org_role=role)
self.create_gt_job(admin_user, task["id"])
task_owner = task["owner"]
rq_id = self._initialize_report_creation(task_id=task["id"], user=task_owner["username"])
self._test_check_status_of_report_creation(
rq_id,
task_staff=task_owner["username"],
another_user=another_user["username"],
)
with make_api_client(task_owner["username"]) as api_client:
api_client.tasks_api.partial_update(
task["id"],
patched_task_write_request=models.PatchedTaskWriteRequest(
assignee_id=another_user["id"]
),
)
self._test_check_status_of_report_creation(
rq_id,
task_staff=task_owner["username"],
another_user=another_user["username"],
another_user_status=HTTPStatus.OK,
)
def test_user_without_rights_cannot_check_status_of_report_creation_in_sandbox(
self,
find_sandbox_task_without_gt: Callable[[bool], tuple[dict[str, Any], dict[str, Any]]],
admin_user: str,
users: Iterable,
):
task, task_staff = find_sandbox_task_without_gt(is_staff=True)
self.create_gt_job(admin_user, task["id"])
another_user = next(
u
for u in users
if (
u["id"] != task_staff["id"]
and not u["is_superuser"]
and u["id"] != task["owner"]["id"]
and u["id"] != (task["assignee"] or {}).get("id")
)
)
rq_id = self._initialize_report_creation(task["id"], task_staff["username"])
self._test_check_status_of_report_creation(
rq_id, task_staff=task_staff["username"], another_user=another_user["username"]
)
@pytest.mark.parametrize(
"same_org, role",
[
pair
for pair in product([True, False], _PermissionTestBase._default_org_roles)
if not (pair[0] and pair[1] in ["owner", "maintainer"])
],
)
def test_user_without_rights_cannot_check_status_of_report_creation_in_org(
self,
same_org: bool,
role: str,
admin_user: str,
find_org_task_without_gt: Callable[[bool, str], tuple[dict[str, Any], dict[str, Any]]],
organizations,
):
task, task_staff = find_org_task_without_gt(is_staff=True, user_org_role="supervisor")
self.create_gt_job(admin_user, task["id"])
# create another user that passes the requirements
another_user = register_new_user(f"{same_org}{role}")
org_id = (
task["organization"]
if same_org
else next(o for o in organizations if o["id"] != task["organization"])["id"]
)
invite_user_to_org(another_user["email"], org_id, role)
rq_id = self._initialize_report_creation(task["id"], task_staff["username"])
self._test_check_status_of_report_creation(
rq_id, task_staff=task_staff["username"], another_user=another_user["username"]
)
@pytest.mark.parametrize("is_sandbox", (True, False))
def test_admin_can_check_status_of_report_creation(
self,
is_sandbox: bool,
users: Iterable,
admin_user: str,
find_org_task_without_gt: Callable[[bool, str], tuple[dict[str, Any], dict[str, Any]]],
find_sandbox_task_without_gt: Callable[[bool], tuple[dict[str, Any], dict[str, Any]]],
):
if is_sandbox:
task, task_staff = find_sandbox_task_without_gt(is_staff=True)
else:
task, task_staff = find_org_task_without_gt(is_staff=True, user_org_role="owner")
admin = next(
u
for u in users
if (
u["is_superuser"]
and u["id"] != task_staff["id"]
and u["id"] != task["owner"]["id"]
and u["id"] != (task["assignee"] or {}).get("id")
)
)
self.create_gt_job(admin_user, task["id"])
rq_id = self._initialize_report_creation(task["id"], task_staff["username"])
with make_api_client(admin["username"]) as api_client:
wait_background_request(api_client, rq_id)
class TestSimpleQualityReportsFilters(CollectionSimpleFilterTestBase):
@pytest.fixture(autouse=True)
def setup(self, restore_db_per_class, admin_user, quality_reports, jobs, tasks, projects):
self.user = admin_user
self.samples = quality_reports
self.job_samples = jobs
self.task_samples = tasks
self.project_samples = projects
def _get_endpoint(self, api_client: ApiClient) -> Endpoint:
return api_client.quality_api.list_reports_endpoint
def _get_field_samples(self, field: str) -> tuple[Any, list[dict[str, Any]]]:
def _get_job_reports(task_ids: Collection[int]) -> list[dict[str, Any]]:
job_ids = set(j["id"] for j in self.job_samples if j["task_id"] in task_ids)
job_reports = [
r for r in self.samples if self._get_field(r, self._map_field("job_id")) in job_ids
]
return job_reports
if field == "project_id":
# This filter includes both the project, task and nested job reports
project_id, project_reports = super()._get_field_samples(field)
return project_id, list(project_reports) + _get_job_reports(
[r["task_id"] for r in project_reports]
)
elif field == "task_id":
# This filter includes both the task and nested job reports
task_id, task_reports = super()._get_field_samples(field)
task_reports = list(task_reports) + _get_job_reports([task_id])
return task_id, task_reports
elif field == "org_id":
org_id = self.task_samples[
next(
s
for s in self.samples
if s["task_id"] and self.task_samples[s["task_id"]]["organization"]
)["task_id"]
]["organization"]
return org_id, [
s
for s in self.samples
if s["job_id"]
and self.job_samples[s["job_id"]]["organization"] == org_id
or s["task_id"]
and self.task_samples[s["task_id"]]["organization"] == org_id
or s["project_id"]
and self.project_samples[s["project_id"]]["organization"] == org_id
]
else:
return super()._get_field_samples(field)
@pytest.mark.parametrize(
"field",
("project_id", "task_id", "job_id", "parent_id", "target", "org_id"),
)
def test_can_use_simple_filter_for_object_list(self, field):
return super()._test_can_use_simple_filter_for_object_list(field)
@pytest.mark.usefixtures("restore_db_per_class")
class TestListQualityConflicts(_PermissionTestBase):
def _test_list_conflicts_200(self, user, report_id, *, expected_data=None, **kwargs):
with make_api_client(user) as api_client:
results = get_paginated_collection(
api_client.quality_api.list_conflicts_endpoint,
return_json=True,
report_id=report_id,
**kwargs,
)
if expected_data is not None:
assert DeepDiff(expected_data, results) == {}
return results
def _test_list_conflicts_403(self, user, report_id, **kwargs):
with make_api_client(user) as api_client:
(_, response) = api_client.quality_api.list_conflicts(
report_id=report_id, **kwargs, _parse_response=False, _check_status=False
)
assert response.status == HTTPStatus.FORBIDDEN
def test_can_list_job_report_conflicts(self, admin_user, quality_reports, quality_conflicts):
report = next(r for r in quality_reports if r["job_id"])
conflicts = [c for c in quality_conflicts if c["report_id"] == report["id"]]