-
Notifications
You must be signed in to change notification settings - Fork 69
/
tools_test.py
3223 lines (2823 loc) · 101 KB
/
tools_test.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 glob
import os
import shutil
from configparser import ConfigParser
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from typing import Callable, List, Optional, Tuple, Union
import pytest
import requests
from demisto_sdk.commands.common import tools
from demisto_sdk.commands.common.constants import (
DEFAULT_CONTENT_ITEM_TO_VERSION,
DOC_FILES_DIR,
INDICATOR_TYPES_DIR,
INTEGRATIONS_DIR,
LAYOUTS_DIR,
MARKETPLACE_TO_CORE_PACKS_FILE,
METADATA_FILE_NAME,
PACKS_DIR,
PACKS_PACK_IGNORE_FILE_NAME,
PLAYBOOKS_DIR,
SCRIPTS_DIR,
TEST_PLAYBOOKS_DIR,
TRIGGER_DIR,
XPANSE_INLINE_PREFIX_TAG,
XPANSE_INLINE_SUFFIX_TAG,
XPANSE_PREFIX_TAG,
XPANSE_SUFFIX_TAG,
XSIAM_DASHBOARDS_DIR,
XSIAM_INLINE_PREFIX_TAG,
XSIAM_INLINE_SUFFIX_TAG,
XSIAM_PREFIX_TAG,
XSIAM_REPORTS_DIR,
XSIAM_SUFFIX_TAG,
XSOAR_CONFIG_FILE,
XSOAR_INLINE_PREFIX_TAG,
XSOAR_INLINE_SUFFIX_TAG,
XSOAR_ON_PREM_INLINE_PREFIX_TAG,
XSOAR_ON_PREM_INLINE_SUFFIX_TAG,
XSOAR_ON_PREM_PREFIX_TAG,
XSOAR_ON_PREM_SUFFIX_TAG,
XSOAR_PREFIX_TAG,
XSOAR_SAAS_INLINE_PREFIX_TAG,
XSOAR_SAAS_INLINE_SUFFIX_TAG,
XSOAR_SAAS_PREFIX_TAG,
XSOAR_SAAS_SUFFIX_TAG,
XSOAR_SUFFIX_TAG,
FileType,
MarketplaceVersions,
)
from demisto_sdk.commands.common.content import Content
from demisto_sdk.commands.common.content.tests.objects.pack_objects.pack_ignore.pack_ignore_test import (
PACK_IGNORE,
)
from demisto_sdk.commands.common.git_content_config import (
GitContentConfig,
GitCredentials,
)
from demisto_sdk.commands.common.git_util import GitUtil
from demisto_sdk.commands.common.handlers import DEFAULT_JSON_HANDLER as json
from demisto_sdk.commands.common.handlers import DEFAULT_YAML_HANDLER as yaml
from demisto_sdk.commands.common.legacy_git_tools import git_path
from demisto_sdk.commands.common.tools import (
MarketplaceTagParser,
TagParser,
arg_to_list,
compare_context_path_in_yml_and_readme,
extract_field_from_mapping,
field_to_cli_name,
filter_files_by_type,
filter_files_on_pack,
filter_packagify_changes,
find_type,
find_type_by_path,
generate_xsiam_normalized_name,
get_code_lang,
get_current_repo,
get_dict_from_file,
get_display_name,
get_entity_id_by_entity_type,
get_entity_name_by_entity_type,
get_file,
get_file_displayed_name,
get_file_version_suffix_if_exists,
get_files_in_dir,
get_from_version,
get_ignore_pack_skipped_tests,
get_item_marketplaces,
get_last_release_version,
get_last_remote_release_version,
get_latest_release_notes_text,
get_marketplace_to_core_packs,
get_pack_metadata,
get_pack_names_from_files,
get_relative_path_from_packs_dir,
get_release_note_entries,
get_release_notes_file_path,
get_scripts_and_commands_from_yml_data,
get_test_playbook_id,
get_to_version,
get_yaml,
has_remote_configured,
is_content_item_dependent_in_conf,
is_object_in_id_set,
is_origin_content_repo,
is_pack_path,
is_uuid,
parse_multiple_path_inputs,
retrieve_file_ending,
run_command_os,
search_and_delete_from_conf,
server_version_compare,
str2bool,
string_to_bool,
to_kebab_case,
)
from demisto_sdk.tests.constants_test import (
DUMMY_SCRIPT_PATH,
IGNORED_PNG,
INDICATORFIELD_EXTRA_FIELDS,
SOURCE_FORMAT_INTEGRATION_COPY,
TEST_PLAYBOOK,
VALID_BETA_INTEGRATION_PATH,
VALID_DASHBOARD_PATH,
VALID_GENERIC_DEFINITION_PATH,
VALID_GENERIC_FIELD_PATH,
VALID_GENERIC_MODULE_PATH,
VALID_GENERIC_TYPE_PATH,
VALID_INCIDENT_FIELD_PATH,
VALID_INCIDENT_TYPE_FILE,
VALID_INCIDENT_TYPE_FILE__RAW_DOWNLOADED,
VALID_INCIDENT_TYPE_PATH,
VALID_INTEGRATION_TEST_PATH,
VALID_LAYOUT_PATH,
VALID_MD,
VALID_PLAYBOOK_ID_PATH,
VALID_REPUTATION_FILE,
VALID_SCRIPT_PATH,
VALID_WIDGET_PATH,
)
from demisto_sdk.tests.test_files.validate_integration_test_valid_types import (
LAYOUT,
MAPPER,
OLD_CLASSIFIER,
REPUTATION,
)
from TestSuite.file import File
from TestSuite.pack import Pack
from TestSuite.playbook import Playbook
from TestSuite.repo import Repo
from TestSuite.test_tools import ChangeCWD
GIT_ROOT = git_path()
SENTENCE_WITH_UMLAUTS = "Nett hier. Aber waren Sie schon mal in Baden-Württemberg?"
class TestGenericFunctions:
PATH_TO_HERE = f"{GIT_ROOT}/demisto_sdk/tests/test_files/"
FILE_PATHS = [
(os.path.join(PATH_TO_HERE, "fake_integration.yml"), tools.get_yaml),
(
os.path.join(
PATH_TO_HERE, "test_playbook_value_starting_with_equal_sign.yml"
),
tools.get_yaml,
),
(
str(
Path(PATH_TO_HERE, "test_playbook_value_starting_with_equal_sign.yaml")
),
tools.get_yaml,
),
(str(Path(PATH_TO_HERE, "fake_json.json")), tools.get_json),
]
@pytest.mark.parametrize("file_path, func", FILE_PATHS)
def test_get_file(self, file_path, func):
assert func(file_path)
@pytest.mark.parametrize("file_path, _", FILE_PATHS)
def test_get_file_or_remote_with_local(self, file_path: str, _):
"""
Given:
file_path to a file
When:
Calling `get_file_or_remote` when the file exists locally
Then
Ensure that the file data is returned
"""
absolute_path = Path(file_path)
relative_path = absolute_path.relative_to(GIT_ROOT)
assert (result_non_relative := tools.get_file_or_remote(absolute_path))
assert (result_relative := tools.get_file_or_remote(relative_path))
assert result_non_relative == result_relative
@pytest.mark.parametrize("file_path, _", FILE_PATHS)
def test_get_file_or_remote_with_origin(self, mocker, file_path: str, _):
"""
Given:
file_path to a file
When:
Calling `get_file_or_remote` when the file doesn't exist locally, but exists on origin
Then
Ensure that the file data is returned
"""
path = Path(file_path)
content = path.read_text()
mocker.patch.object(tools, "get_file", side_effect=FileNotFoundError)
mocker.patch.object(GitUtil, "get_local_remote_file_path")
mocker.patch.object(
GitUtil, "get_local_remote_file_content", return_value=content
)
mocker.patch.object(tools, "get_content_path", return_value=Path(GIT_ROOT))
relative_path = path.relative_to(GIT_ROOT)
assert (result_non_relative := tools.get_file_or_remote(path))
assert (result_relative := tools.get_file_or_remote(relative_path))
assert result_non_relative == result_relative
@pytest.mark.parametrize("file_path, _", FILE_PATHS)
def test_get_file_or_remote_with_api(
self, mocker, requests_mock, file_path: str, _
):
"""
Given:
file_path to a file
When:
Calling `get_file_or_remote` when the file doesn't exist locally, and not on origin, but exists GitHub
Then
Ensure that the file data is returned
"""
path = Path(file_path)
content = path.read_text()
mocker.patch.object(tools, "get_file", side_effect=FileNotFoundError)
mocker.patch.object(tools, "get_local_remote_file", side_effect=ValueError)
mocker.patch.object(tools, "get_content_path", return_value=Path(GIT_ROOT))
relative_path = path.relative_to(GIT_ROOT)
requests_mock.get("https://api.github.com/repos/demisto/demisto-sdk")
requests_mock.get(
f"https://raw.githubusercontent.com/demisto/demisto-sdk/master/{relative_path}",
text=content,
)
assert (result_non_relative := tools.get_file_or_remote(path))
assert (result_relative := tools.get_file_or_remote(relative_path))
assert result_non_relative == result_relative
@staticmethod
@pytest.mark.parametrize(
"suffix,dumps_method", ((".json", json.dumps), (".yml", yaml.dumps))
)
def test_get_file_non_unicode(
tmp_path,
suffix: str,
dumps_method: Callable,
):
"""Tests reading a non-unicode file"""
path = (tmp_path / "non_unicode").with_suffix(suffix)
path.write_bytes(
dumps_method({"text": SENTENCE_WITH_UMLAUTS}, ensure_ascii=False).encode(
"latin-1"
)
)
assert "ü" in path.read_text(encoding="latin-1")
assert get_file(path) == {"text": SENTENCE_WITH_UMLAUTS}
@pytest.mark.parametrize(
"file_name, prefix, result",
[
("test.json", "parsingrule", "parsingrule-external-test.json"),
(
"parsingrule-external-test.json",
"parsingrule",
"external-parsingrule-test.json",
),
("parsingrule-test.json", "parsingrule", "external-parsingrule-test.json"),
],
)
def test_generate_xsiam_normalized_name(self, file_name, prefix, result):
assert generate_xsiam_normalized_name(file_name, prefix)
@pytest.mark.parametrize(
"dir_path", ["demisto_sdk", f"{GIT_ROOT}/demisto_sdk/tests/test_files"]
)
def test_get_yml_paths_in_dir(self, dir_path):
yml_paths, first_yml_path = tools.get_yml_paths_in_dir(dir_path, error_msg="")
yml_paths_test = glob.glob(os.path.join(dir_path, "*yml"))
assert sorted(yml_paths) == sorted(yml_paths_test)
if yml_paths_test:
assert first_yml_path == yml_paths_test[0]
else:
assert not first_yml_path
data_test_get_dict_from_file = [
(VALID_REPUTATION_FILE, True, "json"),
(VALID_SCRIPT_PATH, True, "yml"),
("test", True, None),
(None, True, None),
("invalid-path.json", False, None),
(VALID_INCIDENT_TYPE_FILE__RAW_DOWNLOADED, False, "json"),
]
@pytest.mark.parametrize("path, raises_error, _type", data_test_get_dict_from_file)
def test_get_dict_from_file(self, path, raises_error, _type):
output = get_dict_from_file(str(path), raises_error=raises_error)[1]
assert (
output == _type
), f"get_dict_from_file({path}) returns: {output} instead {_type}"
data_test_find_type = [
(VALID_DASHBOARD_PATH, FileType.DASHBOARD),
(VALID_INCIDENT_FIELD_PATH, FileType.INCIDENT_FIELD),
(VALID_INCIDENT_TYPE_PATH, FileType.INCIDENT_TYPE),
(INDICATORFIELD_EXTRA_FIELDS, FileType.INDICATOR_FIELD),
(VALID_INTEGRATION_TEST_PATH, FileType.INTEGRATION),
(VALID_LAYOUT_PATH, FileType.LAYOUT),
(VALID_PLAYBOOK_ID_PATH, FileType.PLAYBOOK),
(VALID_REPUTATION_FILE, FileType.REPUTATION),
(VALID_SCRIPT_PATH, FileType.SCRIPT),
(VALID_WIDGET_PATH, FileType.WIDGET),
(VALID_GENERIC_TYPE_PATH, FileType.GENERIC_TYPE),
(VALID_GENERIC_FIELD_PATH, FileType.GENERIC_FIELD),
(VALID_GENERIC_MODULE_PATH, FileType.GENERIC_MODULE),
(VALID_GENERIC_DEFINITION_PATH, FileType.GENERIC_DEFINITION),
(IGNORED_PNG, None),
("Author_image.png", FileType.AUTHOR_IMAGE),
(FileType.PACK_IGNORE.value, FileType.PACK_IGNORE),
(FileType.SECRET_IGNORE.value, FileType.SECRET_IGNORE),
(Path(DOC_FILES_DIR) / "foo", FileType.DOC_FILE),
(METADATA_FILE_NAME, FileType.METADATA),
("", None),
]
@pytest.mark.parametrize("path, _type", data_test_find_type)
def test_find_type(self, path, _type):
output = find_type(str(path))
assert output == _type, f"find_type({path}) returns: {output} instead {_type}"
def test_find_type_ignore_sub_categories(self):
output = find_type(VALID_BETA_INTEGRATION_PATH)
assert (
output == FileType.BETA_INTEGRATION
), f"find_type({VALID_BETA_INTEGRATION_PATH}) returns: {output} instead {FileType.BETA_INTEGRATION}"
output = find_type(VALID_BETA_INTEGRATION_PATH, ignore_sub_categories=True)
assert (
output == FileType.INTEGRATION
), f"find_type({VALID_BETA_INTEGRATION_PATH}) returns: {output} instead {FileType.INTEGRATION}"
def test_find_type_with_invalid_yml(self, malformed_integration_yml):
"""
Given
- A malformed yml file.
When
- Running find_type.
Then
- Ensure no exception/error is raised and None is returned.
"""
try:
assert not find_type(
malformed_integration_yml.path, ignore_invalid_schema_file=True
)
except ValueError as err:
assert False, str(err)
def test_find_type_with_invalid_json(self, malformed_incident_field):
"""
Given
- A malformed json file.
When
- Running find_type.
Then
- Ensure no exception/error is raised and None is returned.
"""
try:
assert not find_type(
malformed_incident_field.path, ignore_invalid_schema_file=True
)
except ValueError as err:
assert False, str(err)
def test_find_type_no_file(self):
"""
Given
- A non existing file path.
When
- Running find_type.
Then
- Ensure None is returned
"""
madeup_path = "some/path"
output = find_type(madeup_path)
assert not output
test_path_md = [VALID_MD]
@pytest.mark.parametrize("path", test_path_md)
def test_filter_packagify_changes(self, path):
modified, added, removed = filter_packagify_changes(
modified_files=[], added_files=[], removed_files=[path]
)
assert modified == []
assert added == set()
assert removed == [VALID_MD]
test_content_path_on_pack = [
(
"AbuseDB",
{
"Packs/AbuseDB/Integrations/AbuseDB/AbuseDB.py",
"Packs/Another_pack/Integrations/example/example.py",
},
)
]
@pytest.mark.parametrize("pack, file_paths_list", test_content_path_on_pack)
def test_filter_files_on_pack(self, pack, file_paths_list):
"""
Given
- Set of files and pack name.
When
- Want to filter the list by specific pack.
Then:
- Ensure the set of file paths contains only files located in the given pack.
"""
files_paths = filter_files_on_pack(pack, file_paths_list)
assert files_paths == {"Packs/AbuseDB/Integrations/AbuseDB/AbuseDB.py"}
for_test_filter_files_by_type = [
(
{VALID_INCIDENT_FIELD_PATH, VALID_PLAYBOOK_ID_PATH},
[FileType.PLAYBOOK],
{VALID_INCIDENT_FIELD_PATH},
),
(
{VALID_INCIDENT_FIELD_PATH, VALID_INCIDENT_TYPE_PATH},
[],
{VALID_INCIDENT_FIELD_PATH, VALID_INCIDENT_TYPE_PATH},
),
(set(), [FileType.PLAYBOOK], set()),
]
@pytest.mark.parametrize("files, types, output", for_test_filter_files_by_type)
def test_filter_files_by_type(self, files, types, output, mocker):
"""
Given
- Sets of content files and file types to skip.
When
- Want to filter the lists by file typs.
Then:
- Ensure the list returned Whiteout the files to skip.
"""
mocker.patch(
"demisto_sdk.commands.common.tools.is_file_path_in_pack",
return_value="True",
)
files = filter_files_by_type(files, types)
assert files == output
@pytest.mark.parametrize("path, output", [("demisto.json", "json"), ("wow", "")])
def test_retrieve_file_ending(self, path, output):
assert retrieve_file_ending(path) == output
@pytest.mark.parametrize(
"data, entity, output",
[
({"script": {"type": "javascript"}}, INTEGRATIONS_DIR, "javascript"),
({"type": "javascript"}, SCRIPTS_DIR, "javascript"),
({}, LAYOUTS_DIR, ""),
],
)
def test_get_code_lang(self, data, entity, output):
assert get_code_lang(data, entity) == output
def test_camel_to_snake(self):
snake = tools.camel_to_snake("CamelCase")
assert snake == "camel_case"
class TestGetRemoteFile:
content_repo = "demisto/content"
def test_get_remote_file_sanity(self):
hello_world_yml = tools.get_remote_file(
"Packs/HelloWorld/Integrations/HelloWorld/HelloWorld.yml",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert hello_world_yml
assert hello_world_yml["commonfields"]["id"] == "HelloWorld"
def test_get_remote_file_content_sanity(self):
hello_world_py = tools.get_remote_file(
"Packs/HelloWorld/Integrations/HelloWorld/HelloWorld.py",
return_content=True,
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert hello_world_py
def test_get_remote_file_content(self):
hello_world_py = tools.get_remote_file(
"Packs/HelloWorld/Integrations/HelloWorld/HelloWorld.py",
return_content=True,
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
hello_world_text = hello_world_py.decode()
assert isinstance(hello_world_py, bytes)
assert hello_world_py
assert "main()" in hello_world_text
assert (
"""HelloWorld Integration for Cortex XSOAR (aka Demisto)"""
in hello_world_text
)
def test_get_remote_file_origin(self):
hello_world_yml = tools.get_remote_file(
"Packs/HelloWorld/Integrations/HelloWorld/HelloWorld.yml",
"master",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert hello_world_yml
assert hello_world_yml["commonfields"]["id"] == "HelloWorld"
def test_get_remote_file_tag(self):
gmail_yml = tools.get_remote_file(
"Integrations/Gmail/Gmail.yml",
"19.10.0",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert gmail_yml
assert gmail_yml["commonfields"]["id"] == "Gmail"
def test_get_remote_file_origin_tag(self):
gmail_yml = tools.get_remote_file(
"Integrations/Gmail/Gmail.yml",
"origin/19.10.0",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert gmail_yml
assert gmail_yml["commonfields"]["id"] == "Gmail"
def test_get_remote_file_invalid(self):
invalid_yml = tools.get_remote_file(
"Integrations/File/File.yml",
"19.10.0",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert not invalid_yml
def test_get_remote_file_invalid_branch(self):
invalid_yml = tools.get_remote_file(
"Integrations/Gmail/Gmail.yml",
"NoSuchBranch",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert not invalid_yml
def test_get_remote_file_invalid_origin_branch(self):
invalid_yml = tools.get_remote_file(
"Integrations/Gmail/Gmail.yml",
"origin/NoSuchBranch",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert not invalid_yml
def test_get_remote_md_file_origin(self):
hello_world_readme = tools.get_remote_file(
"Packs/HelloWorld/README.md",
"master",
git_content_config=GitContentConfig(repo_name=self.content_repo),
)
assert hello_world_readme == {}
def test_should_file_skip_validation_negative(self):
should_skip = tools.should_file_skip_validation(
"Packs/HelloWorld/Integrations/HelloWorld/search_alerts.json"
)
assert not should_skip
SKIPPED_FILE_PATHS = [
"some_text_file.txt",
"pack_metadata.json",
"testdata/file.json",
"test_data/file.json",
"data_test/file.json",
"testcommandsfunctions/file.json",
"testhelperfunctions/file.json",
"StixDecodeTest/file.json",
"TestCommands/file.json",
"SetGridField_test/file.json",
"IPNetwork_test/file.json",
"test-data/file.json"
"some_file/integration_DESCRIPTION.md"
"some_file/integration_CHANGELOG.md"
"some_file/integration_unified.md",
]
@pytest.mark.parametrize("file_path", SKIPPED_FILE_PATHS)
def test_should_file_skip_validation_positive(self, file_path):
should_skip = tools.should_file_skip_validation(file_path)
assert should_skip
class TestGetRemoteFileLocally:
REPO_NAME = "example_repo"
FILE_NAME = "somefile.json"
FILE_CONTENT = '{"id": "some_file"}'
git_util = Content.git_util()
main_branch = git_util.handle_prev_ver()[1]
def setup_method(self):
# create local git repo
example_repo = GitUtil.REPO_CLS.init(self.REPO_NAME)
origin_branch = self.main_branch
if not origin_branch.startswith("origin"):
origin_branch = "origin/" + origin_branch
example_repo.git.checkout("-b", f"{origin_branch}")
with open(os.path.join(self.REPO_NAME, self.FILE_NAME), "w+") as somefile:
somefile.write(self.FILE_CONTENT)
example_repo.git.add(self.FILE_NAME)
example_repo.git.config("user.email", "automatic@example.com")
example_repo.git.config("user.name", "AutomaticTest")
example_repo.git.commit("-m", "test_commit", "-a")
example_repo.git.checkout("-b", self.main_branch)
def test_get_file_from_master_when_in_private_repo(self, mocker):
mocker.patch.object(tools, "is_external_repository", return_value=True)
class Response:
ok = False
mocker.patch.object(requests, "get", return_value=Response)
mocker.patch.dict(
os.environ,
{
GitCredentials.ENV_GITHUB_TOKEN_NAME: "",
GitCredentials.ENV_GITLAB_TOKEN_NAME: "",
},
)
with ChangeCWD(self.REPO_NAME):
some_file_json = tools.get_remote_file(self.FILE_NAME)
assert some_file_json
assert some_file_json["id"] == "some_file"
def teardown_method(self):
shutil.rmtree(self.REPO_NAME)
class TestServerVersionCompare:
V5 = "5.0.0"
V0 = "0.0.0"
EQUAL = 0
LEFT_IS_LATER = 1
RIGHT_IS_LATER = -1
INPUTS = [
(V0, V5, RIGHT_IS_LATER),
(V5, V0, LEFT_IS_LATER),
(V5, V5, EQUAL),
("4.5.0", "4.5", EQUAL),
]
@pytest.mark.parametrize("left, right, answer", INPUTS)
def test_server_version_compare(self, left, right, answer):
assert server_version_compare(left, right) == answer
def test_pascal_case():
res = tools.pascal_case("PowerShell Remoting")
assert res == "PowerShellRemoting"
res = tools.pascal_case("good life")
assert res == "GoodLife"
res = tools.pascal_case("good_life-here v2")
assert res == "GoodLifeHereV2"
def test_capital_case():
res = tools.capital_case("PowerShell Remoting")
assert res == "PowerShell Remoting"
res = tools.capital_case("good life")
assert res == "Good Life"
res = tools.capital_case("good_life-here v2")
assert res == "Good_life-here V2"
res = tools.capital_case("")
assert res == ""
class TestReleaseVersion:
def test_get_last_release(self, mocker):
mocker.patch(
"demisto_sdk.commands.common.tools.run_command",
return_value="1.2.3\n4.5.6\n3.2.1\n20.0.0",
)
tag = get_last_release_version()
assert tag == "20.0.0"
class TestEntityAttributes:
@pytest.mark.parametrize(
"data, entity",
[
({"commonfields": {"id": 1}}, INTEGRATIONS_DIR),
({"typeId": 1}, LAYOUTS_DIR),
({"id": 1}, PLAYBOOKS_DIR),
],
)
def test_get_entity_id_by_entity_type(self, data, entity):
assert get_entity_id_by_entity_type(data, entity) == 1
@pytest.mark.parametrize(
"data, entity",
[
({"typeId": "wow"}, LAYOUTS_DIR),
({"name": "wow"}, LAYOUTS_DIR),
({"name": "wow"}, PLAYBOOKS_DIR),
],
)
def test_get_entity_name_by_entity_type(self, data, entity):
assert get_entity_name_by_entity_type(data, entity) == "wow"
class TestGetFilesInDir:
def test_project_dir_is_file(self):
project_dir = "demisto_sdk/commands/download/downloader.py"
assert get_files_in_dir(project_dir, ["py"]) == [project_dir]
def test_not_recursive(self):
project_dir = "demisto_sdk/commands/download"
files = [
f"{project_dir}/__init__.py",
f"{project_dir}/downloader.py",
f"{project_dir}/README.md",
]
assert sorted(get_files_in_dir(project_dir, ["py", "md"], False)) == sorted(
files
)
def test_recursive(self):
integrations_dir = "demisto_sdk/commands/download/tests/tests_env/content/Packs/TestPack/Integrations"
integration_instance_dir = f"{integrations_dir}/TestIntegration"
files = [
f"{integration_instance_dir}/TestIntegration.py",
f"{integration_instance_dir}/TestIntegration_testt.py",
]
assert sorted(get_files_in_dir(integrations_dir, ["py"])) == sorted(files)
def test_recursive_pack(self):
pack_dir = (
"demisto_sdk/commands/download/tests/tests_env/content/Packs/TestPack"
)
files = [
f"{pack_dir}/Integrations/TestIntegration/TestIntegration.py",
f"{pack_dir}/Integrations/TestIntegration/TestIntegration_testt.py",
f"{pack_dir}/Scripts/TestScript/TestScript.py",
]
assert sorted(get_files_in_dir(pack_dir, ["py"])) == sorted(files)
run_command_os_inputs = [("ls", os.getcwd()), ("ls", Path(os.getcwd()))]
@pytest.mark.parametrize("command, cwd", run_command_os_inputs)
def test_run_command_os(command, cwd):
"""Tests a simple command, to check if it works"""
stdout, stderr, return_code = run_command_os(command, cwd=cwd)
assert 0 == return_code
assert stdout
assert not stderr
class TestGetFile:
def test_get_yaml(self):
file_data = get_yaml(SOURCE_FORMAT_INTEGRATION_COPY)
assert file_data
assert file_data.get("name") is not None
def test_get_latest_release_notes_text_invalid():
"""
Given
- Invalid release notes
When
- Running validation on release notes.
Then
- Ensure None is returned
"""
PATH_TO_HERE = f"{GIT_ROOT}/demisto_sdk/tests/test_files/"
file_path = os.path.join(PATH_TO_HERE, "empty-RN.md")
assert get_latest_release_notes_text(file_path) is None
def test_get_release_notes_file_path_valid():
"""
Given
- Valid release notes path
When
- Running validation on release notes.
Then
- Ensure valid file path is returned
"""
filepath = "/SomePack/1_1_1.md"
assert get_release_notes_file_path(filepath) == filepath
def test_get_release_notes_file_path_invalid():
"""
Given
- Invalid release notes path
When
- Running validation on release notes.
Then
- Ensure None is returned
"""
filepath = "/SomePack/1_1_1.json"
assert get_release_notes_file_path(filepath) is None
remote_testbank = [
("origin https://github.com/turbodog/content.git", False),
("upstream https://github.com/demisto/content.git", True),
]
@pytest.mark.parametrize("git_value, response", remote_testbank)
def test_has_remote(mocker, git_value, response):
"""
While: Testing if the remote upstream contains demisto/content
Given:
1. Origin string not containing demisto/content
2. Upstream string containing demisto/content
Expects:
1. Test condition fails
2. Test condition passes
:param git_value: Git string from `git remotes -v`
"""
mocker.patch(
"demisto_sdk.commands.common.tools.run_command", return_value=git_value
)
test_remote = has_remote_configured()
assert response == test_remote
origin_testbank = [
("origin https://github.com/turbodog/content.git", False),
("origin https://github.com/demisto/content.git", True),
]
@pytest.mark.parametrize("git_value, response", origin_testbank)
def test_origin_content(mocker, git_value, response):
"""
While: Testing if the remote origin contains demisto/content
Given:
1. Origin string not containing demisto/content
2. Origin string containing demisto/content
Expects:
1. Test condition fails
2. Test condition passes
:param git_value: Git string from `git remotes -v`
"""
mocker.patch(
"demisto_sdk.commands.common.tools.run_command", return_value=git_value
)
test_remote = is_origin_content_repo()
assert response == test_remote
def test_get_ignore_pack_tests__no_pack():
"""
Given
- Pack that doesn't exist
When
- Collecting packs' ignored tests - running `get_ignore_pack_tests()`
Then:
- returns an empty set
"""
nonexistent_pack = "NonexistentFakeTestPack"
ignore_test_set = get_ignore_pack_skipped_tests(
nonexistent_pack, {nonexistent_pack}, {}
)
assert len(ignore_test_set) == 0
def test_get_ignore_pack_tests__no_ignore_pack(tmpdir):
"""
Given
- Pack doesn't have .pack-ignore file
When
- Collecting packs' ignored tests - running `get_ignore_pack_tests()`
Then:
- returns an empty set
"""
fake_pack_name = "FakeTestPack"
# prepare repo
repo = Repo(tmpdir)
repo_path = Path(repo.path)
pack = Pack(repo_path / PACKS_DIR, fake_pack_name, repo)
pack_ignore_path = os.path.join(pack.path, PACKS_PACK_IGNORE_FILE_NAME)
# remove .pack-ignore if exists
Path(pack_ignore_path).unlink(missing_ok=True)
ignore_test_set = get_ignore_pack_skipped_tests(
fake_pack_name, {fake_pack_name}, {}
)
assert len(ignore_test_set) == 0
def test_get_ignore_pack_tests__test_not_ignored(tmpdir):
"""
Given
- Pack have .pack-ignore file
- There are no skipped tests in .pack-ignore
When
- Collecting packs' ignored tests - running `get_ignore_pack_tests()`
Then:
- returns an empty set
"""
fake_pack_name = "FakeTestPack"
# prepare repo
repo = Repo(tmpdir)
repo_path = Path(repo.path)
pack = Pack(repo_path / PACKS_DIR, fake_pack_name, repo)
pack_ignore_path = os.path.join(pack.path, PACKS_PACK_IGNORE_FILE_NAME)
# prepare .pack-ignore
open(pack_ignore_path, "a").close()
ignore_test_set = get_ignore_pack_skipped_tests(
fake_pack_name, {fake_pack_name}, {}
)
assert len(ignore_test_set) == 0
def test_get_ignore_pack_tests__ignore_test(tmpdir, mocker):
"""
Given
- Pack have .pack-ignore file
- There are skipped tests in .pack-ignore
- Set of modified packs.
When
- Collecting packs' ignored tests - running `get_ignore_pack_tests()`
Then:
- returns a list with the skipped tests
"""
fake_pack_name = "FakeTestPack"
fake_test_name = "FakeTestPlaybook"
expected_id = "SamplePlaybookTest"
# prepare repo
repo = Repo(tmpdir)
packs_path = Path(repo.path) / PACKS_DIR
pack = Pack(packs_path, fake_pack_name, repo)
test_playbook_path = packs_path / fake_pack_name / TEST_PLAYBOOKS_DIR
test_playbook = Playbook(
test_playbook_path, fake_test_name, repo, is_test_playbook=True
)
pack_ignore_path = os.path.join(pack.path, PACKS_PACK_IGNORE_FILE_NAME)
# prepare .pack-ignore
with open(pack_ignore_path, "a") as pack_ignore_f:
pack_ignore_f.write(
"[file:TestIntegration.yml]\nignore=IN126\n\n"
f"[file:{test_playbook.name}]\nignore=auto-test"
)
# prepare mocks
mocker.patch.object(
tools, "get_pack_ignore_file_path", return_value=pack_ignore_path
)
mocker.patch.object(