-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_core.py
More file actions
3239 lines (2990 loc) · 130 KB
/
test_core.py
File metadata and controls
3239 lines (2990 loc) · 130 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) 2023-2025 Orange. All rights reserved. #
# This software is distributed under the BSD 3-Clause-clear License, the text of #
# which is available at https://spdx.org/licenses/BSD-3-Clause-Clear.html or #
# see the "LICENSE.md" file for more details. #
######################################################################################
"""Tests for the khiops.core module"""
import glob
import io
import json
import math
import os
import pathlib
import shutil
import tempfile
import textwrap
import unittest
import warnings
from copy import copy
from difflib import unified_diff
from pathlib import Path
from unittest import mock
import khiops
import khiops.core as kh
import khiops.core.internals.filesystems as fs
from khiops.core import KhiopsRuntimeError
from khiops.core.internals.io import KhiopsOutputWriter
from khiops.core.internals.runner import KhiopsLocalRunner, KhiopsRunner
from khiops.core.internals.scenario import ConfigurableKhiopsScenario
from khiops.core.internals.version import KhiopsVersion
# Disable warning about access to protected member: These are tests
# pylint: disable=protected-access
class KhiopsCoreIOTests(unittest.TestCase):
"""Tests the reading/writing of files for the core module classes/functions"""
def _assert_coclustering_report_is_written_to_sorted_json_file(
self, cc_report, ref_json_report
):
# Write the coclustering report to a JSON file, sorted according to
# the spec defined in the CoclusteringResults class
# Set _ensure_ascii, as non-ASCII characters are escaped in the reference
# reports
tmp_dir = tempfile.mkdtemp()
output_report = os.path.join(tmp_dir, "TestCoclustering.khcj")
cc_report.write_khiops_json_file(output_report, _ensure_ascii=True)
# Load JSON Khiops reports into Python dictionaries
with open(ref_json_report, encoding="utf-8") as ref_json_file:
ref_json = json.load(ref_json_file)
with open(output_report, encoding="utf-8") as output_json_file:
output_json = json.load(output_json_file)
# Dump reports with consistent indentation
ref_json_string = json.dumps(ref_json, indent=4)
output_json_string = json.dumps(output_json, indent=4)
# Succeed if the dumped reports are equal
if output_json_string == ref_json_string:
shutil.rmtree(tmp_dir)
return
# On failure print the differences
output_json_lines = output_json_string.splitlines(keepends=True)
ref_json_lines = ref_json_string.splitlines(keepends=True)
out_ref_diff = "".join(unified_diff(ref_json_lines, output_json_lines))
if out_ref_diff:
self.fail(
"CoclusteringResults JSON dump differs from reference "
f"'{ref_json_report}':\n{out_ref_diff}"
)
def _assert_analysis_report_is_dumped_to_correct_json(
self, report, ref_json_report
):
# Dump the report as JSON (4-space indented and keys sorted in
# lexicographic order)
output_json = report.to_dict()
output_json_string = json.dumps(output_json, indent=4, sort_keys=True)
# Dump the reference JSON report (4-space indented and keys sorted in
# lexicographic order)
with open(ref_json_report, encoding="utf-8") as ref_json_file:
ref_json = json.load(ref_json_file)
ref_json_string = json.dumps(ref_json, indent=4, sort_keys=True)
# Succeed if the dumped reports are equal
if output_json_string == ref_json_string:
return
# On failure print the differences
output_json_lines = output_json_string.splitlines(keepends=True)
ref_json_lines = ref_json_string.splitlines(keepends=True)
out_ref_diff = "".join(unified_diff(ref_json_lines, output_json_lines))
if out_ref_diff:
self.fail(
f"AnalysisResults JSON dump differs from reference "
f"'{ref_json_report}':\n{out_ref_diff}"
)
def test_analysis_results(self):
"""Tests for the analysis_results module"""
# Set the test paths
test_resources_dir = os.path.join(resources_dir(), "analysis_results")
ref_json_reports_dir = os.path.join(test_resources_dir, "ref_json_reports")
# Read the json reports, dump them as txt reports, and compare to the reference
reports = [
"Adult",
"AdultEvaluation",
"Ansi",
"AnsiGreek",
"AnsiLatin",
"AnsiLatinGreek",
"BadTool",
"Deft2017ChallengeNGrams1000",
"EmptyDatabase",
"Greek",
"Iris2D",
"IrisC",
"IrisG",
"IrisR",
"IrisRWithTrees",
"SpliceJunctionWithTrees",
"IrisU",
"IrisU2D",
"Latin",
"LatinGreek",
"MissingDiscretization",
"MissingMODLEqualWidth",
"NoBivariateDetailedStats",
"NoPredictorDetails",
"NoVersion",
"XORRegression",
]
reports_warn = [
"AnsiLatin",
"AnsiLatinGreek",
]
reports_ko = ["BadTool", "NoVersion"]
for report in reports:
ref_json_report = os.path.join(ref_json_reports_dir, f"{report}.khj")
with self.subTest(report=report):
if report in reports_ko:
with self.assertRaises(kh.KhiopsJSONError):
results = kh.read_analysis_results_file(ref_json_report)
elif report in reports_warn:
with self.assertWarns(UserWarning):
results = kh.read_analysis_results_file(ref_json_report)
self._assert_analysis_report_is_dumped_to_correct_json(
results, ref_json_report
)
else:
results = kh.read_analysis_results_file(ref_json_report)
self._assert_analysis_report_is_dumped_to_correct_json(
results, ref_json_report
)
def test_coclustering_results(self):
"""Tests for the coclustering_results module"""
# Set the test paths
test_resources_dir = os.path.join(resources_dir(), "coclustering_results")
ref_json_reports_dir = os.path.join(test_resources_dir, "ref_json_reports")
# Read then json reports, dump them as txt reports and compare to the reference
reports = [
"Adult",
"Iris",
"IrisSimplified",
"IrisIV",
"Ansi_Coclustering",
"AnsiGreek_Coclustering",
"AnsiLatin_Coclustering",
"AnsiLatinGreek_Coclustering",
"Greek_Coclustering",
"Latin_Coclustering",
"LatinGreek_Coclustering",
"MushroomAnnotated",
]
reports_warn = [
"AnsiLatin_Coclustering",
"AnsiLatinGreek_Coclustering",
]
for report in reports:
ref_json_report = os.path.join(ref_json_reports_dir, f"{report}.khcj")
with self.subTest(report=report):
if report in reports_warn:
with self.assertWarns(UserWarning):
results = kh.read_coclustering_results_file(ref_json_report)
else:
results = kh.read_coclustering_results_file(ref_json_report)
self._assert_coclustering_report_is_written_to_sorted_json_file(
results, ref_json_report
)
def test_binary_dictionary_domain(self):
"""Test binary dictionary write"""
# Set the test paths
test_resources_dir = os.path.join(resources_dir(), "dictionary")
dictionary_name = "Bytes"
ref_kdic = os.path.join(
test_resources_dir, "ref_kdic", f"{dictionary_name}.kdic"
)
ref_kdicj = os.path.join(
test_resources_dir, "ref_kdicj", f"{dictionary_name}.kdicj"
)
output_kdic_dir = os.path.join(test_resources_dir, "output_kdic")
output_kdic = os.path.join(output_kdic_dir, f"{dictionary_name}.kdic")
copy_output_kdic_dir = os.path.join(test_resources_dir, "copy_output_kdic")
copy_output_kdic = os.path.join(copy_output_kdic_dir, f"{dictionary_name}.kdic")
# Create output dirs if not existing, and delete their contents
cleanup_dir(output_kdic_dir, "*.kdic")
cleanup_dir(copy_output_kdic_dir, "*.kdic")
# Build dictionary domain programmatically
domain_from_api = kh.DictionaryDomain()
domain_from_api.version = b"10.0.0.3i"
dictionary = kh.Dictionary()
dictionary.name = bytes("MyDictê", encoding="cp1252")
metadata = kh.MetaData()
metadata.add_value(
bytes("aKey", encoding="cp1252"), bytes("aValué", encoding="cp1252")
)
variable = kh.Variable()
variable.name = bytes("MyVarî", encoding="cp1252")
variable.type = "Categorical"
variable.meta_data = metadata
dictionary.add_variable(variable)
domain_from_api.add_dictionary(dictionary)
# Read domain from JSON file
domain_from_json = kh.read_dictionary_file(ref_kdicj)
for domain in (domain_from_api, domain_from_json):
# Dump domain object as kdic file and compare it to the reference
domain.export_khiops_dictionary_file(output_kdic)
assert_files_equal(self, ref_kdic, output_kdic)
# Make a copy of the domain object, then dump it as kdic file and
# compare it to the reference
domain_copy = domain.copy()
domain_copy.export_khiops_dictionary_file(copy_output_kdic)
assert_files_equal(self, ref_kdic, copy_output_kdic)
def test_dictionary(self):
"""Tests for the dictionary module"""
# Set the test paths
test_resources_dir = os.path.join(resources_dir(), "dictionary")
ref_kdic_dir = os.path.join(test_resources_dir, "ref_kdic")
ref_kdicj_dir = os.path.join(test_resources_dir, "ref_kdicj")
output_kdic_dir = os.path.join(test_resources_dir, "output_kdic")
copy_output_kdic_dir = os.path.join(test_resources_dir, "copy_output_kdic")
# Cleanup previous output files
cleanup_dir(output_kdic_dir, "*.kdic")
cleanup_dir(copy_output_kdic_dir, "*.kdic")
# Read then json reports then:
# - dump the domain objects as kdic files and compare to the reference
# - make a copy of the domain objects and then dump and compare to the reference
dictionaries = [
"AIDSBondCounts",
"Adult",
"AdultKey",
"AdultModeling",
"Ansi",
"AnsiGreek",
"AnsiGreek_Modeling",
"AnsiLatin",
"AnsiLatinGreek",
"AnsiLatinGreek_Modeling",
"AnsiLatin_Modeling",
"Ansi_Modeling",
"CommentedIris",
"CommentedSpliceJunction",
"CommentedSparseCustomer",
"Customer",
"CustomerExtended",
"D_Modeling",
"Dorothea",
"Greek",
"Greek_Modeling",
"Latin",
"LatinGreek",
"LatinGreek_Modeling",
"Latin_Modeling",
"SpliceJunction",
"SpliceJunctionModeling",
]
dictionaries_warn = [
"AnsiLatin",
"AnsiLatinGreek",
"AnsiLatinGreek_Modeling",
"AnsiLatin_Modeling",
]
for dictionary in dictionaries:
ref_kdic = os.path.join(ref_kdic_dir, f"{dictionary}.kdic")
ref_kdicj = os.path.join(ref_kdicj_dir, f"{dictionary}.kdicj")
output_kdic = os.path.join(output_kdic_dir, f"{dictionary}.kdic")
output_kdic_new_dir = os.path.join(output_kdic_dir, "missing_folder")
# Cleanup the previous `output_kdic_new_dir` folder (if it exists)
shutil.rmtree(output_kdic_new_dir, ignore_errors=True)
self.assertFalse(os.path.exists(output_kdic_new_dir))
copy_output_kdic = os.path.join(copy_output_kdic_dir, f"{dictionary}.kdic")
with self.subTest(dictionary=dictionary):
if dictionary in dictionaries_warn:
with self.assertWarns(UserWarning):
domain = kh.read_dictionary_file(ref_kdicj)
else:
domain = kh.read_dictionary_file(ref_kdicj)
domain.export_khiops_dictionary_file(output_kdic)
assert_files_equal(self, ref_kdic, output_kdic)
domain.export_khiops_dictionary_file(
os.path.join(output_kdic_new_dir, f"{dictionary}.kdic")
)
# Ensure a missing parent directory is created automatically
self.assertTrue(os.path.exists(output_kdic_new_dir))
domain_copy = domain.copy()
domain_copy.export_khiops_dictionary_file(copy_output_kdic)
assert_files_equal(self, ref_kdic, copy_output_kdic)
def _build_mock_deprecated_data_path_api_method_parameters(self):
# Mock data to test the update of legacy data paths in the created
# scenarios
additional_data_tables = {
"Customer`Services": "ServicesBidon.csv",
"Customer`Services`Usages": "UsagesBidon.csv",
"Customer`Address": "AddressBidon.csv",
}
output_additional_data_tables = {
"Customer`Services": "TransferServicesBidon.csv",
"Customer`Services`Usages": "TransferUsagesBidon.csv",
"Customer`Address": "TransferAddressBidon.csv",
}
# Store the relation method_name -> mock args and kwargs
# Copy `additional_data_tables` as it is mutated by each function
method_test_args = {
"check_database": {
"args": ["Customer.kdic", "Customer", "Customer.csv"],
"kwargs": {"additional_data_tables": copy(additional_data_tables)},
},
# Test byte strings in the `deploy_model` test
"deploy_model": {
"args": [
bytes("Customer.kdic", encoding="ascii"),
bytes("Customer", encoding="ascii"),
bytes("Customer.csv", encoding="ascii"),
bytes("CustomerDeployed.csv", encoding="ascii"),
],
"kwargs": {
"additional_data_tables": (
{
bytes(key, encoding="ascii"): bytes(value, encoding="ascii")
for key, value in additional_data_tables.items()
}
),
"output_additional_data_tables": (
{
bytes(key, encoding="ascii"): bytes(value, encoding="ascii")
for key, value in output_additional_data_tables.items()
}
),
},
},
"evaluate_predictor": {
"args": [
"ModelingCustomer.kdic",
"Customer",
"Customer.csv",
"CustomerResults/CustomerAnalysisResults.khj",
],
"kwargs": {"additional_data_tables": copy(additional_data_tables)},
},
"train_coclustering": {
"args": [
"Customer.kdic",
"Customer",
"Customer.csv",
["id_customer", "Name"],
"CustomerResults/CustomerCoclusteringResults._khcj",
],
"kwargs": {
"additional_data_tables": copy(additional_data_tables),
},
},
"train_predictor": {
"args": [
"Customer.kdic",
"Customer",
"Customer.csv",
"",
"CustomerResults/CustomerAnalysisResults._khj",
],
"kwargs": {
"additional_data_tables": copy(additional_data_tables),
},
},
"train_recoder": {
"args": [
"Customer.kdic",
"Customer",
"Customer.csv",
"",
"CustomerResults/CustomerAnalysisResults._khj",
],
"kwargs": {
"additional_data_tables": copy(additional_data_tables),
},
},
}
return method_test_args
def _build_mock_api_method_parameters(self):
# Pseudo-mock data to test the creation of scenarios
datasets = ["Adult", "SpliceJunction", "Customer"]
additional_data_tables = {
"Adult": None,
"SpliceJunction": {"DNA": "SpliceJunctionDNABidon.csv"},
"Customer": {
"Services": "ServicesBidon.csv",
"Services/Usages": "UsagesBidon.csv",
"Address": "AddressBidon.csv",
"/City": "CityBidon.csv",
"/Country": "CountryBidon.csv",
"/Product": "ProductBidon.csv",
},
}
output_additional_data_tables = {
"Adult": None,
"SpliceJunction": {"DNA": "TransferSpliceJunctionDNABidon.csv"},
"Customer": {
"Services": "TransferServicesBidon.csv",
"Services/Usages": "TransferUsagesBidon.csv",
"Address": "TransferAddressBidon.csv",
"/City": "TransferCityBidon.csv",
"/Country": "TransferCountryBidon.csv",
"/Product": "TransferProductBidon.csv",
},
}
target_variables = {"Adult": "class", "SpliceJunction": "Class", "Customer": ""}
construction_rules = {
"Adult": [],
"SpliceJunction": ["TableMode", "TableSelection"],
"Customer": None,
}
coclustering_variables = {
"Adult": ["age", "workclass", "race", "sex"],
"SpliceJunction": ["SampleId", "NonExistentVar"],
"Customer": ["id_customer", "Name"],
}
max_part_numbers = {
"Adult": {"age": 2, "workclass": 4, "race": 8, "sex": 16},
"SpliceJunction": {"SampleId": 32, "NonExistentVar": 64},
"Customer": None,
}
sort_variables = {
"Adult": ["Label", "age", "race"],
"SpliceJunction": ["SampleId"],
"Customer": None,
}
specific_pairs = {
"Adult": [("age", "rage"), ("Label", ""), ("", "capital_gain")],
"SpliceJunction": [],
"Customer": None,
}
detect_data_table_format_kwargs = {
"Adult": {
"dictionary_file_path_or_domain": "Adult.kdic",
"dictionary_name": "Adult",
},
"SpliceJunction": {
"dictionary_file_path_or_domain": "SpliceJunctionDNA.kdic",
"dictionary_name": "SpliceJunctionDNA",
},
"Customer": {
"dictionary_file_path_or_domain": None,
"dictionary_name": None,
},
}
# Store the relation method_name -> (dataset -> mock args and kwargs)
method_test_args = {
"build_deployed_dictionary": {
dataset: {
"args": [
f"{dataset}.kdic",
dataset,
f"{dataset}Deployed.kdic",
],
"kwargs": {},
}
for dataset in datasets
},
"build_dictionary_from_data_table": {
dataset: {
"args": [f"{dataset}.csv", dataset, f"{dataset}.kdic"],
"kwargs": {},
}
for dataset in datasets
},
"check_database": {
dataset: {
"args": [f"{dataset}.kdic", dataset, f"{dataset}.csv"],
"kwargs": {
"additional_data_tables": additional_data_tables[dataset]
},
}
for dataset in datasets
},
"detect_data_table_format": {
dataset: {
"args": [f"{dataset}.csv"],
"kwargs": detect_data_table_format_kwargs[dataset],
}
for dataset in datasets
},
# We profit to test byte strings in the deploy_model test
"deploy_model": {
dataset: {
"args": [
bytes(f"{dataset}.kdic", encoding="ascii"),
bytes(dataset, encoding="ascii"),
bytes(f"{dataset}.csv", encoding="ascii"),
bytes(f"{dataset}Deployed.csv", encoding="ascii"),
],
"kwargs": {
"additional_data_tables": (
{
bytes(key, encoding="ascii"): bytes(
value, encoding="ascii"
)
for key, value in additional_data_tables[
dataset
].items()
}
if additional_data_tables[dataset] is not None
else None
),
"output_additional_data_tables": (
{
bytes(key, encoding="ascii"): bytes(
value, encoding="ascii"
)
for key, value in output_additional_data_tables[
dataset
].items()
}
if output_additional_data_tables[dataset] is not None
else None
),
},
}
for dataset in datasets
},
"evaluate_predictor": {
dataset: {
"args": [
f"Modeling{dataset}.kdic",
dataset,
f"{dataset}.csv",
f"{dataset}Results/{dataset}AnalysisResults.khj",
],
"kwargs": {
"additional_data_tables": additional_data_tables[dataset]
},
}
for dataset in datasets
},
"export_dictionary_as_json": {
dataset: {
"args": [f"{dataset}.kdic", f"{dataset}.kdicj"],
"kwargs": {},
}
for dataset in datasets
},
"extract_clusters": {
dataset: {
"args": [
f"{dataset}Coclustering.khcj",
coclustering_variables[dataset][0],
f"{dataset}Clusters.txt",
],
"kwargs": {},
}
for dataset in datasets
},
"extract_keys_from_data_table": {
dataset: {
"args": [
f"{dataset}.kdic",
dataset,
f"{dataset}.csv",
f"{dataset}Keys.csv",
],
"kwargs": {},
}
for dataset in datasets
},
"prepare_coclustering_deployment": {
dataset: {
"args": [
f"{dataset}.kdic",
dataset,
f"{dataset}._khcj",
coclustering_variables[dataset][0],
coclustering_variables[dataset][1],
f"{dataset}Results/{dataset}CoclusteringResults.khcj",
],
"kwargs": {
"max_part_numbers": max_part_numbers[dataset],
},
}
for dataset in datasets
},
"simplify_coclustering": {
dataset: {
"args": [
f"{dataset}._khcj",
f"{dataset}Results/{dataset}SimplifiedCoclusteringResults.khcj",
],
"kwargs": {
"max_part_numbers": max_part_numbers[dataset],
},
}
for dataset in datasets
},
"sort_data_table": {
dataset: {
"args": [
f"{dataset}.kdic",
dataset,
f"{dataset}.csv",
f"{dataset}Sorted.csv",
],
"kwargs": {
"sort_variables": sort_variables[dataset],
},
}
for dataset in datasets
},
"train_coclustering": {
dataset: {
"args": [
f"{dataset}.kdic",
dataset,
f"{dataset}.csv",
coclustering_variables[dataset],
f"{dataset}Results/{dataset}CoclusteringResults._khcj",
],
"kwargs": {
"additional_data_tables": additional_data_tables[dataset],
},
}
for dataset in datasets
},
"train_predictor": {
dataset: {
"args": [
f"{dataset}.kdic",
dataset,
f"{dataset}.csv",
target_variables[dataset],
f"{dataset}Results/{dataset}AnalysisResults._khj",
],
"kwargs": {
"additional_data_tables": additional_data_tables[dataset],
"construction_rules": construction_rules[dataset],
"specific_pairs": specific_pairs[dataset],
},
}
for dataset in datasets
},
"train_recoder": {
dataset: {
"args": [
f"{dataset}.kdic",
dataset,
f"{dataset}.csv",
target_variables[dataset],
f"{dataset}Results/{dataset}AnalysisResults._khj",
],
"kwargs": {
"additional_data_tables": additional_data_tables[dataset],
"construction_rules": construction_rules[dataset],
"specific_pairs": specific_pairs[dataset],
},
}
for dataset in datasets
},
}
return method_test_args
def test_api_scenario_generation(self):
"""Tests the scenarios generated by the API
These tests are not exhaustive, executed with the minimal parameters to trigger
the more complex scenario generation code (lists, key-value sections) when they
are present.
"""
# Set the root directory of these tests
test_resources_dir = os.path.join(resources_dir(), "scenario_generation", "api")
# Use the test runner that only compares the scenarios
default_runner = kh.get_runner()
test_runner = ScenarioWriterRunner(self, test_resources_dir)
kh.set_runner(test_runner)
# Run test for all methods and all mock datasets parameters
method_test_args = self._build_mock_api_method_parameters()
for method_name, method_full_args in method_test_args.items():
# Set the runners test name
test_runner.test_name = method_name
# Clean the directory for this method's tests
cleanup_dir(test_runner.output_scenario_dir, "*/output/*._kh", verbose=True)
# Test for each dataset mock parameters
for dataset, dataset_method_args in method_full_args.items():
test_runner.subtest_name = dataset
with self.subTest(dataset=dataset, method=method_name):
# Execute the method
method = getattr(kh, method_name)
dataset_args = dataset_method_args["args"]
dataset_kwargs = dataset_method_args["kwargs"]
method(*dataset_args, **dataset_kwargs)
# Compare the reference with the output
assert_files_equal(
self,
test_runner.ref_scenario_path,
test_runner.output_scenario_path,
line_comparator=scenario_line_comparator,
)
# Restore the default runner
kh.set_runner(default_runner)
def test_data_path_deprecation_in_api_method(self):
"""Tests if the core.api deprecates legacy data paths"""
# Set the root directory of these tests
test_resources_dir = os.path.join(
resources_dir(), "scenario_generation", "data_path_deprecation"
)
# Use the test runner that only compares the scenarios
default_runner = kh.get_runner()
test_runner = ScenarioWriterRunner(self, test_resources_dir)
kh.set_runner(test_runner)
# Obtain mock arguments for each API call
method_test_args = self._build_mock_deprecated_data_path_api_method_parameters()
# Test for each dataset mock parameters
for method_name, method_full_args in method_test_args.items():
# Set the runners test name
test_runner.test_name = method_name
# Clean the directory for this method's tests
cleanup_dir(test_runner.output_scenario_dir, "*/output/*._kh", verbose=True)
test_runner.subtest_name = "Customer"
with self.subTest(method=method_name):
# Get the API function and its args and kwargs
method = getattr(kh, method_name)
args = method_full_args["args"]
kwargs = method_full_args["kwargs"]
# Test that using legacy paths entails a deprecation warning
with warnings.catch_warnings(record=True) as warning_list:
method(*args, **kwargs)
# Check that there is at least one deprecation warning message
# related to the data paths
self.assertTrue(len(warning_list) > 0)
deprecation_warning_found = False
for warning in warning_list:
warning_message = warning.message
if (
issubclass(warning.category, UserWarning)
and len(warning_message.args) == 1
and "'`'-based dictionary data path" in warning_message.args[0]
and "deprecated" in warning_message.args[0]
):
deprecation_warning_found = True
break
self.assertTrue(deprecation_warning_found)
# Compare the reference with the output
assert_files_equal(
self,
test_runner.ref_scenario_path,
test_runner.output_scenario_path,
line_comparator=scenario_line_comparator,
)
# Restore the default runner
kh.set_runner(default_runner)
def test_unknown_argument_in_api_method(self):
"""Tests if core.api raises ValueError when an unknown argument is passed"""
# Obtain mock arguments for each API call
method_test_args = self._build_mock_api_method_parameters()
# Test for each dataset mock parameters
for method_name, method_full_args in method_test_args.items():
for dataset, dataset_method_args in method_full_args.items():
# Test only for the Adult dataset
if dataset != "Adult":
continue
with self.subTest(method=method_name):
# These methods do not have kwargs so they cannot have extra args
if method_name in [
"detect_data_table_format",
"export_dictionary_as_json",
]:
continue
# Execute the method with an invalid parameter
method = getattr(kh, method_name)
dataset_args = dataset_method_args["args"]
dataset_kwargs = dataset_method_args["kwargs"]
dataset_kwargs["INVALID_PARAM"] = False
# Check that the call raised ValueError
with self.assertRaises(ValueError) as context:
method(*dataset_args, **dataset_kwargs)
# Check the message
expected_msg = "Unknown argument 'INVALID_PARAM'"
output_msg = str(context.exception)
self.assertEqual(output_msg, expected_msg)
def test_system_settings(self):
"""Test that the system settings are written to the scenario file"""
# Create the root directory of these tests
test_resources_dir = os.path.join(resources_dir(), "scenario_generation")
# Use the test runner that only compares the scenarios
default_runner = kh.get_runner()
test_runner = ScenarioWriterRunner(self, test_resources_dir)
test_runner.test_name = "system_settings"
test_runner.subtest_name = "default"
cleanup_dir(test_runner.output_scenario_dir, "*/output/*._kh")
kh.set_runner(test_runner)
# Call check_database (could be any other method), with the common execution
# options set
kh.check_database(
"a.kdic",
"dict_name",
"data.txt",
max_cores=10,
memory_limit_mb=1000,
temp_dir="/another/tmp",
scenario_prologue="// Scenario prologue test",
)
# Compare the reference with the output
assert_files_equal(
self,
test_runner.ref_scenario_path,
test_runner.output_scenario_path,
line_comparator=scenario_line_comparator,
)
# Set the runner to the default one
kh.set_runner(default_runner)
def test_runner_version(self):
"""Test that the runner respects the _write_version internal parameter"""
# Create the root directory of these tests
test_resources_dir = os.path.join(resources_dir(), "scenario_generation")
# Use the test runner that only compares the scenarios, set _write_version
default_runner = kh.get_runner()
test_runner = ScenarioWriterRunner(self, test_resources_dir)
test_runner.test_name = "runner_version"
test_runner.subtest_name = "default"
test_runner._write_version = True
cleanup_dir(test_runner.output_scenario_dir, "*/output/*._kh")
kh.set_runner(test_runner)
# Call check_database (could be any other method)
kh.check_database("a.kdic", "dict_name", "data.txt")
# Check that the output scenario path has the version in its first line
with open(
test_runner.output_scenario_path, "r", encoding="ascii"
) as scenario_file:
first_line = next(scenario_file).strip()
self.assertEqual(
first_line, f"// Generated by khiops-python {khiops.__version__}"
)
kh.set_runner(default_runner)
def test_std_streams_files(self):
"""Test that the std* streams are written correctly to the specified files"""
# Run the tests for each stream
fixtures = {
"stdout": create_mocked_raw_run(True, False, 0),
"stderr": create_mocked_raw_run(False, True, 0),
}
test_resources_dir = os.path.join(resources_dir(), "tmp")
for stream_name, mocked_raw_run in fixtures.items():
# Run the subtest with the mocked runner
stream_file_path = os.path.join(
test_resources_dir, f"{stream_name}_test.txt"
)
fun_kwargs = {f"{stream_name}_file_path": stream_file_path}
with self.subTest(stream_name=stream_name):
with MockedRunnerContext(mocked_raw_run):
kh.check_database("a.kdic", "a", "a.txt", **fun_kwargs)
# Check that the stream file exists and that the contents match the mock
with open(stream_file_path, encoding="ascii") as stream_file:
stream = stream_file.read().strip()
self.assertEqual(stream, f"{stream_name}_content")
# Clean up the output file
os.remove(stream_file_path)
def test_std_stream_warnings(self):
"""Test that if Khiops OK + non-empty std streams they are shown in a warning"""
# Run the tests for each stream
fixtures = {
"stdout": create_mocked_raw_run(True, False, 0),
"stderr": create_mocked_raw_run(False, True, 0),
}
for stream_name, mocked_raw_run in fixtures.items():
# Run the subtest with the mocked runner
with self.subTest(stream_name=stream_name):
with MockedRunnerContext(mocked_raw_run):
with self.assertWarns(UserWarning) as cm:
kh.check_database("a.kdic", "a", "a.txt")
# Check that the warning contains the stream content
self.assertIn(f"{stream_name}_content", str(cm.warning))
def test_std_stream_errors(self):
"""Test that if Khiops KO + non-empty std streams they are show in the exc."""
# Run the tests for each stream
fixtures = {
"stdout": create_mocked_raw_run(True, False, 1),
"stderr": create_mocked_raw_run(False, True, 1),
}
for stream_name, mocked_raw_run in fixtures.items():
# Run the subtest with the mocked runner
with self.subTest(stream_name=stream_name):
with MockedRunnerContext(mocked_raw_run):
with self.assertRaises(kh.KhiopsRuntimeError) as cm:
kh.check_database("a.kdic", "a", "a.txt")
# Check that the error contains the stream content
self.assertIn(f"{stream_name}_content", str(cm.exception))
class MockedRunnerContext:
"""A context to mock the `~.KhiopsLocalRunner.raw_run` function"""
def __init__(self, mocked_raw_run):
self.mocked_raw_run = mocked_raw_run
def __enter__(self):
# Save the initial runner
self._initial_runner = kh.get_runner()
# Create the mock runner, patch the `raw_run` function, enter its context
self.mocked_runner = KhiopsLocalRunner()
kh.set_runner(self.mocked_runner)
self.mock_context = mock.patch.object(
self.mocked_runner, "raw_run", new=self.mocked_raw_run
)
self.mock_context.__enter__()
# The original `KhiopsLocalRunner._get_khiops_version` method needs to
# call into the Khiops binary via `raw_run` which is mocked; hence, it
# needs to be mocked as well
self.mock_context = mock.patch.object(
self.mocked_runner,
"_get_khiops_version",
return_value=KhiopsVersion("10.6.0-b.0"),
)
self.mock_context.__enter__()
# Return the runner to be used in the context