-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathtest_models.py
2974 lines (2517 loc) · 128 KB
/
test_models.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
# SPDX-License-Identifier: Apache-2.0
#
# http://nexb.com and https://github.com/nexB/scancode.io
# The ScanCode.io software is licensed under the Apache License version 2.0.
# Data generated with ScanCode.io is provided as-is without warranties.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# Data Generated with ScanCode.io is provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# ScanCode.io should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
#
# ScanCode.io is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/nexB/scancode.io for support and download.
import io
import json
import shutil
import sys
import tempfile
import uuid
from contextlib import redirect_stdout
from datetime import datetime
from datetime import timezone as tz
from pathlib import Path
from unittest import mock
from unittest import skipIf
from unittest.mock import patch
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management import call_command
from django.db import DataError
from django.db import IntegrityError
from django.db import connection
from django.test import TestCase
from django.test import TransactionTestCase
from django.test import override_settings
from django.test.utils import CaptureQueriesContext
from django.urls import reverse
from django.utils import timezone
import saneyaml
from packagedcode.models import PackageData
from packageurl import PackageURL
from requests.exceptions import RequestException
from rq.job import JobStatus
from scancodeio import __version__ as scancodeio_version
from scanpipe.models import CodebaseRelation
from scanpipe.models import CodebaseResource
from scanpipe.models import DiscoveredDependency
from scanpipe.models import DiscoveredPackage
from scanpipe.models import Project
from scanpipe.models import ProjectMessage
from scanpipe.models import Run
from scanpipe.models import RunInProgressError
from scanpipe.models import RunNotAllowedToStart
from scanpipe.models import UUIDTaggedItem
from scanpipe.models import WebhookSubscription
from scanpipe.models import convert_glob_to_django_regex
from scanpipe.models import get_project_work_directory
from scanpipe.models import normalize_package_url_data
from scanpipe.pipes.fetch import Download
from scanpipe.pipes.input import copy_input
from scanpipe.tests import dependency_data1
from scanpipe.tests import dependency_data2
from scanpipe.tests import license_policies_index
from scanpipe.tests import make_dependency
from scanpipe.tests import make_message
from scanpipe.tests import make_package
from scanpipe.tests import make_project
from scanpipe.tests import make_resource_directory
from scanpipe.tests import make_resource_file
from scanpipe.tests import mocked_now
from scanpipe.tests import package_data1
from scanpipe.tests import package_data2
from scanpipe.tests.pipelines.do_nothing import DoNothing
scanpipe_app = apps.get_app_config("scanpipe")
User = get_user_model()
class ScanPipeModelsTest(TestCase):
data = Path(__file__).parent / "data"
fixtures = [data / "asgiref" / "asgiref-3.3.0_fixtures.json"]
def setUp(self):
self.project1 = make_project("Analysis")
self.project_asgiref = Project.objects.get(name="asgiref")
def create_run(self, pipeline="pipeline", **kwargs):
return Run.objects.create(
project=self.project1,
pipeline_name=pipeline,
**kwargs,
)
def test_scanpipe_project_model_extra_data(self):
self.assertEqual({}, self.project1.extra_data)
project1_from_db = Project.objects.get(name=self.project1.name)
self.assertEqual({}, project1_from_db.extra_data)
def test_scanpipe_project_model_work_directories(self):
expected_work_directory = f"projects/analysis-{self.project1.short_uuid}"
self.assertTrue(self.project1.work_directory.endswith(expected_work_directory))
self.assertTrue(self.project1.work_path.exists())
self.assertTrue(self.project1.input_path.exists())
self.assertTrue(self.project1.output_path.exists())
self.assertTrue(self.project1.codebase_path.exists())
self.assertTrue(self.project1.tmp_path.exists())
def test_scanpipe_get_project_work_directory(self):
project = make_project("Name with spaces and @£$éæ")
expected = f"/projects/name-with-spaces-and-e-{project.short_uuid}"
self.assertTrue(get_project_work_directory(project).endswith(expected))
self.assertTrue(project.work_directory.endswith(expected))
def test_scanpipe_project_model_clear_tmp_directory(self):
new_file_path = self.project1.tmp_path / "file.ext"
new_file_path.touch()
self.assertEqual([new_file_path], list(self.project1.tmp_path.glob("*")))
self.project1.clear_tmp_directory()
self.assertTrue(self.project1.tmp_path.exists())
self.assertEqual([], list(self.project1.tmp_path.glob("*")))
self.assertTrue(self.project1.tmp_path.exists())
shutil.rmtree(self.project1.work_path, ignore_errors=True)
self.assertFalse(self.project1.tmp_path.exists())
self.project1.clear_tmp_directory()
self.assertTrue(self.project1.tmp_path.exists())
def test_scanpipe_project_model_archive(self):
(self.project1.input_path / "input_file").touch()
(self.project1.codebase_path / "codebase_file").touch()
(self.project1.output_path / "output_file").touch()
self.assertEqual(1, len(Project.get_root_content(self.project1.input_path)))
self.assertEqual(1, len(Project.get_root_content(self.project1.codebase_path)))
self.assertEqual(1, len(Project.get_root_content(self.project1.output_path)))
self.project1.archive()
self.project1.refresh_from_db()
self.assertTrue(self.project1.is_archived)
self.assertEqual(1, len(Project.get_root_content(self.project1.input_path)))
self.assertEqual(1, len(Project.get_root_content(self.project1.codebase_path)))
self.assertEqual(1, len(Project.get_root_content(self.project1.output_path)))
self.project1.archive(remove_input=True, remove_codebase=True)
self.assertEqual(0, len(Project.get_root_content(self.project1.input_path)))
self.assertEqual(0, len(Project.get_root_content(self.project1.codebase_path)))
self.assertEqual(1, len(Project.get_root_content(self.project1.output_path)))
def test_scanpipe_project_model_delete_related_objects(self):
work_path = self.project1.work_path
self.assertTrue(work_path.exists())
self.project1.add_pipeline("analyze_docker_image")
self.project1.labels.add("label1", "label2")
self.assertEqual(2, UUIDTaggedItem.objects.count())
resource = CodebaseResource.objects.create(project=self.project1, path="path")
package = DiscoveredPackage.objects.create(project=self.project1)
resource.discovered_packages.add(package)
delete_log = self.project1.delete_related_objects(keep_labels=True)
expected = {
"scanpipe.CodebaseRelation": 0,
"scanpipe.CodebaseResource": 1,
"scanpipe.DiscoveredDependency": 0,
"scanpipe.DiscoveredPackage": 1,
"scanpipe.DiscoveredPackage_codebase_resources": 1,
"scanpipe.InputSource": 0,
"scanpipe.ProjectMessage": 0,
"scanpipe.Run": 1,
"scanpipe.WebhookDelivery": 0,
"scanpipe.WebhookSubscription": 0,
}
self.assertEqual(expected, delete_log)
# Make sure the labels were deleted too.
self.assertEqual(2, UUIDTaggedItem.objects.count())
self.project1.delete_related_objects()
self.assertEqual(0, UUIDTaggedItem.objects.count())
def test_scanpipe_project_model_delete(self):
work_path = self.project1.work_path
self.assertTrue(work_path.exists())
uploaded_file = SimpleUploadedFile("file.ext", content=b"content")
self.project1.add_upload(uploaded_file=uploaded_file, tag="tag1")
self.project1.add_pipeline("analyze_docker_image")
resource = CodebaseResource.objects.create(project=self.project1, path="path")
package = DiscoveredPackage.objects.create(project=self.project1)
resource.discovered_packages.add(package)
delete_log = self.project1.delete()
expected = {"scanpipe.Project": 1}
self.assertEqual(expected, delete_log[1])
self.assertFalse(Project.objects.filter(name=self.project1.name).exists())
self.assertFalse(work_path.exists())
def test_scanpipe_project_model_reset(self):
work_path = self.project1.work_path
self.assertTrue(work_path.exists())
uploaded_file = SimpleUploadedFile("file.ext", content=b"content")
self.project1.add_upload(uploaded_file=uploaded_file, tag="tag1")
self.project1.add_pipeline("analyze_docker_image")
resource = CodebaseResource.objects.create(project=self.project1, path="path")
package = DiscoveredPackage.objects.create(project=self.project1)
resource.discovered_packages.add(package)
make_message(self.project1, description="Error")
self.assertEqual(1, self.project1.projectmessages.count())
self.assertEqual(1, self.project1.runs.count())
self.assertEqual(1, self.project1.discoveredpackages.count())
self.assertEqual(1, self.project1.codebaseresources.count())
self.assertEqual(1, self.project1.inputsources.count())
self.project1.reset(restore_pipelines=True, execute_now=False)
self.assertEqual(0, self.project1.projectmessages.count())
self.assertEqual(1, self.project1.runs.count())
self.assertEqual(0, self.project1.discoveredpackages.count())
self.assertEqual(0, self.project1.codebaseresources.count())
self.project1.reset()
self.assertTrue(Project.objects.filter(name=self.project1.name).exists())
self.assertEqual(0, self.project1.projectmessages.count())
self.assertEqual(0, self.project1.runs.count())
self.assertEqual(0, self.project1.discoveredpackages.count())
self.assertEqual(0, self.project1.codebaseresources.count())
# The InputSource objects are kept
self.assertEqual(1, self.project1.inputsources.count())
self.assertTrue(work_path.exists())
self.assertTrue(self.project1.input_path.exists())
self.assertEqual(["file.ext"], self.project1.input_root)
self.assertTrue(self.project1.output_path.exists())
self.assertTrue(self.project1.codebase_path.exists())
self.assertTrue(self.project1.tmp_path.exists())
def test_scanpipe_project_model_clone(self):
self.project1.add_input_source(filename="file1", is_uploaded=True)
self.project1.add_input_source(
filename="file2", download_url="https://download.url"
)
self.project1.update(settings={"product_name": "My Product"})
new_file_path1 = self.project1.input_path / "file.zip"
new_file_path1.touch()
run1 = self.project1.add_pipeline("analyze_docker_image", selected_groups=["g"])
run2 = self.project1.add_pipeline("find_vulnerabilities")
subscription1 = self.project1.add_webhook_subscription(
target_url="http://domain.url"
)
cloned_project = self.project1.clone("cloned project")
self.assertIsInstance(cloned_project, Project)
self.assertNotEqual(self.project1.pk, cloned_project.pk)
self.assertNotEqual(self.project1.slug, cloned_project.slug)
self.assertNotEqual(self.project1.work_directory, cloned_project.work_directory)
self.assertEqual("cloned project", cloned_project.name)
self.assertEqual({}, cloned_project.settings)
self.assertEqual([], cloned_project.input_sources)
self.assertEqual([], list(cloned_project.inputs()))
self.assertEqual([], list(cloned_project.runs.all()))
self.assertEqual([], list(cloned_project.webhooksubscriptions.all()))
cloned_project2 = self.project1.clone(
"cloned project full",
copy_inputs=True,
copy_pipelines=True,
copy_settings=True,
copy_subscriptions=True,
execute_now=False,
)
self.assertEqual(self.project1.settings, cloned_project2.settings)
self.assertEqual(
len(self.project1.input_sources), len(cloned_project2.input_sources)
)
self.assertEqual(1, len(list(cloned_project2.inputs())))
runs = cloned_project2.runs.all()
self.assertEqual(
["analyze_docker_image", "find_vulnerabilities"],
[run.pipeline_name for run in runs],
)
self.assertNotEqual(run1.pk, runs[0].pk)
self.assertEqual(run1.selected_groups, runs[0].selected_groups)
self.assertNotEqual(run2.pk, runs[1].pk)
self.assertEqual(1, len(cloned_project2.webhooksubscriptions.all()))
cloned_subscription = cloned_project2.webhooksubscriptions.get()
self.assertNotEqual(subscription1.uuid, cloned_subscription.uuid)
def test_scanpipe_project_model_inputs_and_input_files_and_input_root(self):
self.assertEqual([], list(self.project1.inputs()))
self.assertEqual([], self.project1.input_files)
self.assertEqual([], self.project1.input_root)
new_file_path1 = self.project1.input_path / "file.zip"
new_file_path1.touch()
new_dir1 = self.project1.input_path / "dir1"
new_dir1.mkdir(parents=True, exist_ok=True)
new_file_path2 = new_dir1 / "file2.tar"
new_file_path2.touch()
inputs = list(self.project1.inputs())
expected = [new_dir1, new_file_path1, new_file_path2]
self.assertEqual(sorted(expected), sorted(inputs))
with self.assertRaises(TypeError) as error:
self.project1.inputs(extensions="str")
self.assertEqual("extensions should be a list or tuple", str(error.exception))
inputs = list(self.project1.inputs(extensions=["zip"]))
self.assertEqual([new_file_path1], inputs)
inputs = list(self.project1.inputs(extensions=[".tar"]))
self.assertEqual([new_file_path2], inputs)
inputs = list(self.project1.inputs(extensions=[".zip", "tar"]))
self.assertEqual(sorted([new_file_path1, new_file_path2]), sorted(inputs))
expected = ["file.zip", "dir1/file2.tar"]
self.assertEqual(sorted(expected), sorted(self.project1.input_files))
expected = ["dir1", "file.zip"]
self.assertEqual(sorted(expected), sorted(self.project1.input_root))
@mock.patch("scanpipe.pipes.datetime", mocked_now)
def test_scanpipe_project_model_get_output_file_path(self):
filename = self.project1.get_output_file_path("file", "ext")
self.assertTrue(str(filename).endswith("/output/file-2010-10-10-10-10-10.ext"))
# get_output_file_path always ensure the work_directory is setup
shutil.rmtree(self.project1.work_directory)
self.assertFalse(self.project1.work_path.exists())
self.project1.get_output_file_path("file", "ext")
self.assertTrue(self.project1.work_path.exists())
def test_scanpipe_project_model_get_latest_output(self):
scan1 = self.project1.get_output_file_path("scancode", "json")
scan1.write_text("")
scan2 = self.project1.get_output_file_path("scancode", "json")
scan2.write_text("")
summary1 = self.project1.get_output_file_path("summary", "json")
summary1.write_text("")
scan3 = self.project1.get_output_file_path("scancode", "json")
scan3.write_text("")
summary2 = self.project1.get_output_file_path("summary", "json")
summary2.write_text("")
self.assertIsNone(self.project1.get_latest_output("none"))
self.assertEqual(scan3, self.project1.get_latest_output("scancode"))
self.assertEqual(summary2, self.project1.get_latest_output("summary"))
@mock.patch("scanpipe.pipes.datetime", mocked_now)
def test_scanpipe_project_model_get_output_files_info(self):
self.assertEqual([], self.project1.get_output_files_info())
self.project1.get_output_file_path("file", "ext").write_text("Some content")
expected = [{"name": "file-2010-10-10-10-10-10.ext", "size": 12}]
self.assertEqual(expected, self.project1.get_output_files_info())
def test_scanpipe_project_model_write_input_file(self):
self.assertEqual([], self.project1.input_files)
uploaded_file = SimpleUploadedFile("file.ext", content=b"content")
self.project1.write_input_file(uploaded_file)
self.assertEqual(["file.ext"], self.project1.input_files)
def test_scanpipe_project_model_copy_input_from(self):
self.assertEqual([], self.project1.input_files)
_, input_location = tempfile.mkstemp()
input_filename = Path(input_location).name
self.project1.copy_input_from(input_location)
self.assertEqual([input_filename], self.project1.input_files)
self.assertTrue(Path(input_location).exists())
def test_scanpipe_project_model_move_input_from(self):
self.assertEqual([], self.project1.input_files)
_, input_location = tempfile.mkstemp()
input_filename = Path(input_location).name
self.project1.move_input_from(input_location)
self.assertEqual([input_filename], self.project1.input_files)
self.assertFalse(Path(input_location).exists())
def test_scanpipe_project_model_get_inputs_with_source(self):
self.assertEqual([], self.project1.get_inputs_with_source())
uploaded_file = SimpleUploadedFile("file.ext", content=b"content")
self.project1.add_upload(uploaded_file)
self.project1.copy_input_from(self.data / "aboutcode" / "notice.NOTICE")
self.project1.add_input_source(filename="missing.zip", is_uploaded=True)
uuid1, uuid2 = (
str(input_source.uuid) for input_source in self.project1.inputsources.all()
)
expected = [
{
"uuid": uuid1,
"filename": "file.ext",
"download_url": "",
"is_uploaded": True,
"tag": "",
"size": 7,
"is_file": True,
"exists": True,
},
{
"uuid": uuid2,
"filename": "missing.zip",
"download_url": "",
"is_uploaded": True,
"tag": "",
"size": None,
"is_file": True,
"exists": False,
},
{
"filename": "notice.NOTICE",
"is_uploaded": False,
"is_file": True,
"size": 1178,
"exists": True,
},
]
self.assertEqual(expected, self.project1.get_inputs_with_source())
self.assertEqual(expected, self.project1.input_sources)
def test_scanpipe_project_model_can_start_pipelines(self):
self.assertFalse(self.project1.can_start_pipelines)
# Not started
run = self.project1.add_pipeline("analyze_docker_image")
self.project1 = Project.objects.get(uuid=self.project1.uuid)
self.assertTrue(self.project1.can_start_pipelines)
# Queued
run.task_start_date = timezone.now()
run.save()
self.project1 = Project.objects.get(uuid=self.project1.uuid)
self.assertFalse(self.project1.can_start_pipelines)
# Success
run.task_end_date = timezone.now()
run.task_exitcode = 0
run.save()
self.project1 = Project.objects.get(uuid=self.project1.uuid)
self.assertFalse(self.project1.can_start_pipelines)
# Another "Not started"
self.project1.add_pipeline("analyze_docker_image")
self.project1 = Project.objects.get(uuid=self.project1.uuid)
self.assertTrue(self.project1.can_start_pipelines)
def test_scanpipe_project_model_can_change_inputs(self):
self.assertTrue(self.project1.can_change_inputs)
run = self.project1.add_pipeline("analyze_docker_image")
self.project1 = Project.objects.get(uuid=self.project1.uuid)
self.assertTrue(self.project1.can_change_inputs)
run.task_start_date = timezone.now()
run.save()
self.project1 = Project.objects.get(uuid=self.project1.uuid)
self.assertFalse(self.project1.can_change_inputs)
def test_scanpipe_project_model_add_input_source(self):
self.assertEqual(0, self.project1.inputsources.count())
with self.assertRaises(Exception) as cm:
self.project1.add_input_source()
expected = "Provide at least a value for download_url or filename."
self.assertEqual(expected, str(cm.exception))
source = self.project1.add_input_source(
download_url="https://download.url", tag="tag"
)
self.assertFalse(source.is_uploaded)
self.assertEqual("", source.filename)
self.assertEqual("tag", source.tag)
source = self.project1.add_input_source(filename="file.tar", is_uploaded=True)
self.assertTrue(source.is_uploaded)
self.assertEqual("", source.download_url)
self.assertEqual("", source.tag)
input_sources = self.project1.inputsources.all()
self.assertEqual(2, len(input_sources))
url_with_fragment = "https://download.url#tag_value"
input_source = self.project1.add_input_source(download_url=url_with_fragment)
self.assertEqual("tag_value", input_source.tag)
def test_scanpipe_project_model_add_downloads(self):
file_location = self.data / "aboutcode" / "notice.NOTICE"
copy_input(file_location, self.project1.tmp_path)
download = Download(
uri="https://example.com/filename.zip",
directory="",
filename="notice.NOTICE",
path=self.project1.tmp_path / "notice.NOTICE",
size="",
sha1="",
md5="",
)
self.project1.add_downloads([download])
inputs_with_source = self.project1.get_inputs_with_source()
expected = [
{
"uuid": str(self.project1.inputsources.get().uuid),
"filename": "notice.NOTICE",
"download_url": "https://example.com/filename.zip",
"is_uploaded": False,
"tag": "",
"size": 1178,
"is_file": True,
"exists": True,
}
]
self.assertEqual(expected, inputs_with_source)
def test_scanpipe_project_model_add_uploads(self):
uploaded_file = SimpleUploadedFile("file.ext", content=b"content")
self.project1.add_uploads([uploaded_file])
inputs_with_source = self.project1.get_inputs_with_source()
expected = [
{
"uuid": str(self.project1.inputsources.get().uuid),
"filename": "file.ext",
"download_url": "",
"is_uploaded": True,
"tag": "",
"size": 7,
"is_file": True,
"exists": True,
}
]
self.assertEqual(expected, inputs_with_source)
def test_scanpipe_project_model_add_webhook_subscription(self):
self.assertEqual(0, self.project1.webhooksubscriptions.count())
self.project1.add_webhook_subscription(target_url="https://localhost")
self.assertEqual(1, self.project1.webhooksubscriptions.count())
def test_scanpipe_project_model_get_next_run(self):
self.assertEqual(None, self.project1.get_next_run())
run1 = self.create_run()
run2 = self.create_run()
self.assertEqual(run1, self.project1.get_next_run())
run1.task_start_date = timezone.now()
run1.save()
self.assertEqual(run2, self.project1.get_next_run())
run2.task_start_date = timezone.now()
run2.save()
self.assertEqual(None, self.project1.get_next_run())
def test_scanpipe_project_model_raise_if_run_in_progress(self):
run1 = self.create_run()
self.assertIsNone(self.project1._raise_if_run_in_progress())
run1.set_task_started(task_id=1)
with self.assertRaises(RunInProgressError):
self.project1._raise_if_run_in_progress()
with self.assertRaises(RunInProgressError):
self.project1.archive()
with self.assertRaises(RunInProgressError):
self.project1.delete()
with self.assertRaises(RunInProgressError):
self.project1.reset()
def test_scanpipe_project_queryset_with_counts(self):
self.project_asgiref.add_error("error 1", "model")
self.project_asgiref.add_error("error 2", "model")
project_qs = Project.objects.with_counts(
"codebaseresources",
"discoveredpackages",
"projectmessages",
)
project = project_qs.get(pk=self.project_asgiref.pk)
self.assertEqual(18, project.codebaseresources_count)
self.assertEqual(18, project.codebaseresources.count())
self.assertEqual(2, project.discoveredpackages_count)
self.assertEqual(2, project.discoveredpackages.count())
self.assertEqual(2, project.projectmessages_count)
self.assertEqual(2, project.projectmessages.count())
def test_scanpipe_project_related_queryset_get_or_none(self):
self.assertIsNone(CodebaseResource.objects.get_or_none(path="path/"))
self.assertIsNone(DiscoveredPackage.objects.get_or_none(name="name"))
def test_scanpipe_project_related_model_clone(self):
subscription1 = self.project1.add_webhook_subscription(
target_url="http://domain.url"
)
new_project = make_project("New Project")
subscription1.clone(to_project=new_project)
cloned_subscription = new_project.webhooksubscriptions.get()
subscription1 = self.project1.webhooksubscriptions.get()
self.assertEqual(new_project, cloned_subscription.project)
self.assertNotEqual(cloned_subscription.pk, subscription1.pk)
def test_scanpipe_project_get_codebase_config_directory(self):
self.assertIsNone(self.project1.get_codebase_config_directory())
(self.project1.codebase_path / settings.SCANCODEIO_CONFIG_DIR).mkdir()
config_directory = str(self.project1.get_codebase_config_directory())
self.assertTrue(config_directory.endswith("codebase/.scancode"))
def test_scanpipe_project_get_input_config_file(self):
self.assertIsNone(self.project1.get_input_config_file())
config_file = self.project1.input_path / settings.SCANCODEIO_CONFIG_FILE
config_file.touch()
config_file_location = str(self.project1.get_input_config_file())
self.assertTrue(config_file_location.endswith("input/scancode-config.yml"))
dir1_path = self.project1.codebase_path / "dir1"
dir1_path.mkdir(parents=True, exist_ok=True)
dir1_config_file = dir1_path / settings.SCANCODEIO_CONFIG_FILE
dir1_config_file.touch()
# If a config file exists directly in the input directory, return it.
config_file_location = str(self.project1.get_input_config_file())
self.assertTrue(config_file_location.endswith("input/scancode-config.yml"))
config_file.unlink()
config_file_location = str(self.project1.get_input_config_file())
self.assertTrue(
config_file_location.endswith("codebase/dir1/scancode-config.yml")
)
dir2_path = self.project1.codebase_path / "dir2"
dir2_path.mkdir(parents=True, exist_ok=True)
dir2_config_file = dir2_path / settings.SCANCODEIO_CONFIG_FILE
dir2_config_file.touch()
# If multiple config files are found, report an error.
self.assertIsNone(self.project1.get_input_config_file())
error = self.project1.projectmessages.get()
self.assertIn("More than one scancode-config.yml found", error.description)
dir1_config_file.unlink()
dir2_config_file.unlink()
sub_dir1_path = self.project1.codebase_path / "dir1" / "subdir1"
sub_dir1_path.mkdir(parents=True, exist_ok=True)
sub_dir1_config_file = sub_dir1_path / settings.SCANCODEIO_CONFIG_FILE
sub_dir1_config_file.touch()
# Search for config files *ONLY* in immediate codebase/ subdirectories.
self.assertIsNone(self.project1.get_input_config_file())
def test_scanpipe_project_get_input_policies_file(self):
self.assertIsNone(self.project1.get_input_policies_file())
policies_file = self.project1.input_path / "policies.yml"
policies_file.touch()
policies_file_location = str(self.project1.get_input_policies_file())
self.assertTrue(policies_file_location.endswith("input/policies.yml"))
def test_scanpipe_project_model_get_policy_index(self):
scanpipe_app.license_policies_index = None
self.assertFalse(self.project1.policies_enabled)
policies_from_app_settings = {"from": "scanpipe_app"}
scanpipe_app.license_policies_index = policies_from_app_settings
self.assertEqual(policies_from_app_settings, self.project1.get_policy_index())
policies_from_input_dir = {"license_policies": [{"license_key": "input_dir"}]}
policies_file = self.project1.input_path / "policies.yml"
policies_file.touch()
policies_as_yaml = saneyaml.dump(policies_from_input_dir)
policies_file.write_text(policies_as_yaml)
expected_index_from_input = {"input_dir": {"license_key": "input_dir"}}
self.assertEqual(expected_index_from_input, self.project1.get_policy_index())
# Refresh the instance to bypass the cached_property cache.
self.project1 = Project.objects.get(uuid=self.project1.uuid)
self.assertTrue(self.project1.policies_enabled)
policies_from_project_env = {
"license_policies": [{"license_key": "project_env"}]
}
config = {"policies": policies_from_project_env}
self.project1.settings = config
self.project1.save()
expected_index_from_env = {"project_env": {"license_key": "project_env"}}
self.assertEqual(expected_index_from_env, self.project1.get_policy_index())
# Reset the index value
scanpipe_app.license_policies_index = None
def test_scanpipe_project_get_settings_as_yml(self):
self.assertEqual("{}\n", self.project1.get_settings_as_yml())
test_config_file = self.data / "settings" / "scancode-config.yml"
config_file = copy_input(test_config_file, self.project1.input_path)
env_from_test_config = self.project1.get_env().copy()
self.project1.settings = env_from_test_config
self.project1.save()
config_file.write_text(self.project1.get_settings_as_yml())
self.assertEqual(env_from_test_config, self.project1.get_env())
def test_get_enabled_settings(self):
self.assertEqual({}, self.project1.settings)
self.assertEqual({}, self.project1.get_enabled_settings())
self.project1.update(
settings={"ignored_patterns": None, "attribution_template": ""}
)
self.assertEqual({}, self.project1.get_enabled_settings())
self.project1.update(
settings={"ignored_patterns": "ignore_me", "attribution_template": ""}
)
self.assertEqual(
{"ignored_patterns": "ignore_me"}, self.project1.get_enabled_settings()
)
def test_scanpipe_project_get_env(self):
self.assertEqual({}, self.project1.get_env())
test_config_file = self.data / "settings" / "scancode-config.yml"
copy_input(test_config_file, self.project1.input_path)
expected = {
"product_name": "My Product Name",
"product_version": "1.0",
"ignored_patterns": ["*.tmp", "tests/*"],
"ignored_dependency_scopes": [
{"package_type": "npm", "scope": "devDependencies"},
{"package_type": "pypi", "scope": "tests"},
],
"ignored_vulnerabilities": [
"VCID-q4q6-yfng-aaag",
"CVE-2024-27351",
"GHSA-vm8q-m57g-pff3",
],
}
self.assertEqual(expected, self.project1.get_env())
config = {"ignored_patterns": None}
self.project1.settings = config
self.project1.save()
self.assertEqual(expected, self.project1.get_env())
config = {"ignored_patterns": ["*.txt"], "product_name": "Product1"}
self.project1.settings = config
self.project1.save()
expected["product_name"] = "Product1"
expected["ignored_patterns"] = ["*.txt"]
self.assertEqual(expected, self.project1.get_env())
def test_scanpipe_project_get_env_invalid_yml_content(self):
config_file = self.project1.input_path / settings.SCANCODEIO_CONFIG_FILE
config_file.write_text("{*this is not valid yml*}")
config_file_location = str(self.project1.get_input_config_file())
self.assertTrue(config_file_location.endswith("input/scancode-config.yml"))
self.assertEqual({}, self.project1.get_env())
error = self.project1.projectmessages.get()
self.assertIn("Failed to load configuration from", error.description)
self.assertIn("The file format is invalid.", error.description)
def test_scanpipe_project_get_ignored_dependency_scopes_index(self):
self.project1.settings = {
"ignored_dependency_scopes": [{"package_type": "pypi", "scope": "tests"}]
}
expected = {"pypi": ["tests"]}
self.assertEqual(expected, self.project1.ignored_dependency_scopes_index)
self.assertEqual(expected, self.project1.get_ignored_dependency_scopes_index())
self.project1.settings = {
"ignored_dependency_scopes": [
{"package_type": "pypi", "scope": "tests"},
{"package_type": "pypi", "scope": "build"},
{"package_type": "npm", "scope": "devDependencies"},
]
}
# Since this is a cache property, it still returns the previous value
self.assertEqual(expected, self.project1.ignored_dependency_scopes_index)
# The following function call always build and return the index
expected = {"npm": ["devDependencies"], "pypi": ["tests", "build"]}
self.assertEqual(expected, self.project1.get_ignored_dependency_scopes_index())
def test_scanpipe_normalize_package_url_data(self):
purl = PackageURL.from_string("pkg:npm/[email protected]")
purl_data = normalize_package_url_data(purl_mapping=purl.to_dict())
self.assertEqual(purl_data.get("namespace"), "")
purl_data = normalize_package_url_data(
purl_mapping=purl.to_dict(),
ignore_nulls=True,
)
self.assertEqual(purl_data.get("namespace"), None)
def test_scanpipe_project_get_ignored_vulnerabilities_set(self):
self.project1.settings = {
"ignored_vulnerabilities": [
"VCID-q4q6-yfng-aaag",
"CVE-2024-27351",
"GHSA-vm8q-m57g-pff3",
],
}
expected = {"VCID-q4q6-yfng-aaag", "CVE-2024-27351", "GHSA-vm8q-m57g-pff3"}
self.assertEqual(expected, self.project1.ignored_vulnerabilities_set)
self.assertEqual(expected, self.project1.get_ignored_vulnerabilities_set())
def test_scanpipe_project_model_labels(self):
self.project1.labels.add("label2", "label1")
self.assertEqual(2, UUIDTaggedItem.objects.count())
self.assertEqual(["label1", "label2"], list(self.project1.labels.names()))
self.project1.labels.remove("label1")
self.assertEqual(1, UUIDTaggedItem.objects.count())
self.assertEqual(["label2"], list(self.project1.labels.names()))
self.project1.labels.clear()
self.assertEqual(0, UUIDTaggedItem.objects.count())
@patch.object(Project, "setup_global_webhook")
def test_scanpipe_project_model_call_setup_global_webhook(self, mock_setup_webhook):
webhook_data = {
"target_url": "https://webhook.url",
"trigger_on_each_run": "False",
"include_summary": "True",
"include_results": "False",
}
with override_settings(SCANCODEIO_GLOBAL_WEBHOOK=webhook_data):
# Case 1: New project, not a clone (Webhook should be called)
project = Project(name="Test Project")
project.save()
mock_setup_webhook.assert_called_once()
mock_setup_webhook.reset_mock()
# Case 2: Project is a clone (Webhook should NOT be called)
project = Project(name="Cloned Project")
project.save(is_clone=True)
mock_setup_webhook.assert_not_called()
# Case 3: Skip global webhook (Webhook should NOT be called)
project = Project(name="Project with skip")
project.save(skip_global_webhook=True)
mock_setup_webhook.assert_not_called()
# Case 4: Global webhook is disabled (Webhook should NOT be called)
with override_settings(SCANCODEIO_GLOBAL_WEBHOOK=None):
project = Project(name="No Webhook Project")
project.save()
mock_setup_webhook.assert_not_called()
def test_scanpipe_project_model_setup_global_webhook(self):
self.project1.setup_global_webhook()
self.assertEqual(0, self.project1.webhooksubscriptions.count())
webhook_data = {"target_url": ""}
with override_settings(SCANCODEIO_GLOBAL_WEBHOOK=webhook_data):
self.project1.setup_global_webhook()
self.assertEqual(0, self.project1.webhooksubscriptions.count())
webhook_data = {
"target_url": "https://webhook.url",
"trigger_on_each_run": "False",
"include_summary": "True",
"include_results": "False",
}
with override_settings(SCANCODEIO_GLOBAL_WEBHOOK=webhook_data):
self.project1.setup_global_webhook()
self.assertEqual(1, self.project1.webhooksubscriptions.count())
webhook = self.project1.webhooksubscriptions.get()
self.assertEqual("https://webhook.url", webhook.target_url)
self.assertTrue(webhook.is_active)
self.assertFalse(webhook.trigger_on_each_run)
self.assertTrue(webhook.include_summary)
self.assertFalse(webhook.include_results)
def test_scanpipe_model_update_mixin(self):
resource = CodebaseResource.objects.create(project=self.project1, path="file")
self.assertEqual("", resource.status)
with CaptureQueriesContext(connection) as queries_context:
resource.update(status="updated")
self.assertEqual(1, len(queries_context.captured_queries))
sql = queries_context.captured_queries[0]["sql"]
expected = """UPDATE "scanpipe_codebaseresource" SET "status" = 'updated'"""
self.assertTrue(sql.startswith(expected))
resource.refresh_from_db()
self.assertEqual("updated", resource.status)
package = DiscoveredPackage.objects.create(project=self.project1)
purl_data = DiscoveredPackage.extract_purl_data(package_data1)
with CaptureQueriesContext(connection) as queries_context:
package.update(**purl_data)
self.assertEqual(1, len(queries_context.captured_queries))
sql = queries_context.captured_queries[0]["sql"]
expected = (
'UPDATE "scanpipe_discoveredpackage" SET "type" = "deb", '
'"namespace" = "debian", "name" = "adduser", "version" = "3.118", '
'"qualifiers" = "arch=all", "subpath" = ""'
)
self.assertTrue(sql.replace("'", '"').startswith(expected))
package.refresh_from_db()
self.assertEqual("pkg:deb/debian/[email protected]?arch=all", package.package_url)
def test_scanpipe_model_convert_glob_to_django_regex(self):
test_data = [
("", r"^$"),
# Single segment
("example", r"^example$"),
# Single segment with dot
("example.xml", r"^example\.xml$"),
# Single segment with prefix dot
(".example", r"^\.example$"),
# Single segment wildcard with dot
("*.xml", r"^.*\.xml$"),
("*_map.xml", r"^.*_map\.xml$"),
# Single segment wildcard with slash
("*/.example", r"^.*/\.example$"),
("*/readme.html", r"^.*/readme\.html$"),
# Single segment with wildcards
("*README*", r"^.*README.*$"),
# Multi segments
("path/to/file", r"^path/to/file$"),
# Multi segments with wildcards
("path/*/file", r"^path/.*/file$"),
("*path/to/*", r"^.*path/to/.*$"),
# Multiple segments and wildcards
("path/*/to/*/file.*", r"^path/.*/to/.*/file\..*$"),
# Escaped character
(r"path\*\.txt", r"^path\\.*\\\.txt$"),
(r"path/*/foo$.class", r"^path/.*/foo\$\.class$"),
# Question mark
("path/file?", r"^path/file.$"),
]
for pattern, expected in test_data:
self.assertEqual(expected, convert_glob_to_django_regex(pattern))
def test_scanpipe_run_model_set_scancodeio_version(self):
run1 = Run.objects.create(project=self.project1)
self.assertEqual("", run1.scancodeio_version)
run1.set_scancodeio_version()
run1 = Run.objects.get(pk=run1.pk)
self.assertEqual(scancodeio_version, run1.scancodeio_version)
with self.assertRaises(ValueError) as cm:
run1.set_scancodeio_version()
self.assertIn("Field scancodeio_version already set to", str(cm.exception))
def test_scanpipe_run_model_get_diff_url(self):
run1 = Run.objects.create(project=self.project1)
self.assertEqual("", run1.scancodeio_version)
self.assertIsNone(run1.get_diff_url())
with mock.patch("scancodeio.__version__", "v32.3.0-28-g0000000"):
run1.set_scancodeio_version()
self.assertEqual("v32.3.0-28-g0000000", run1.scancodeio_version)
expected = (
"https://github.com/aboutcode-org/scancode.io/compare/0000000..ffffffff"
)
with mock.patch("scancodeio.__version__", "v31.0.0-1-gffffffff"):
self.assertEqual(expected, run1.get_diff_url())
def test_scanpipe_run_model_set_current_step(self):
run1 = Run.objects.create(project=self.project1)