-
Notifications
You must be signed in to change notification settings - Fork 329
/
Copy pathtest_base.py
1637 lines (1430 loc) · 62.6 KB
/
test_base.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 logging
import re
import warnings
from collections import defaultdict
from datetime import date, datetime
from unittest.mock import ANY, Mock, call, mock_open, patch
import numpy as np
import pandas as pd
import pytest
from sdv import version
from sdv.errors import (
ConstraintsNotMetError, InvalidDataError, NotFittedError, SamplingError, SynthesizerInputError,
VersionError)
from sdv.metadata.multi_table import MultiTableMetadata
from sdv.metadata.single_table import SingleTableMetadata
from sdv.multi_table.base import BaseMultiTableSynthesizer
from sdv.multi_table.hma import HMASynthesizer
from sdv.single_table.copulas import GaussianCopulaSynthesizer
from sdv.single_table.ctgan import CTGANSynthesizer
from tests.utils import catch_sdv_logs, get_multi_table_data, get_multi_table_metadata
class TestBaseMultiTableSynthesizer:
def test__initialize_models(self):
"""Test that this method initializes the ``self._synthezier`` for each table.
This tests that we iterate over the tables within the metadata and if there are
``table_parameters`` we use those to initialize the model.
"""
# Setup
locales = ['en_CA', 'fr_CA']
instance = Mock()
instance._table_synthesizers = {}
instance._table_parameters = {
'nesreca': {
'default_distribution': 'gamma'
}
}
instance.locales = locales
instance.metadata = get_multi_table_metadata()
# Run
BaseMultiTableSynthesizer._initialize_models(instance)
# Assert
assert instance._table_synthesizers == {
'nesreca': instance._synthesizer.return_value,
'oseba': instance._synthesizer.return_value,
'upravna_enota': instance._synthesizer.return_value
}
instance._synthesizer.assert_has_calls([
call(metadata=instance.metadata.tables['nesreca'], default_distribution='gamma',
locales=locales),
call(metadata=instance.metadata.tables['oseba'], locales=locales),
call(metadata=instance.metadata.tables['upravna_enota'], locales=locales)
])
def test__get_pbar_args(self):
"""Test that ``_get_pbar_args`` returns a dictionary with disable opposite to verbose."""
# Setup
instance = Mock()
instance.verbose = False
# Run
result = BaseMultiTableSynthesizer._get_pbar_args(instance)
# Assert
assert result == {'disable': True}
def test__get_pbar_args_kwargs(self):
"""Test that ``_get_pbar_args`` returns a dictionary with the given kwargs."""
# Setup
instance = Mock()
instance.verbose = True
# Run
result = BaseMultiTableSynthesizer._get_pbar_args(
instance,
desc='Process Table',
position=0
)
# Assert
assert result == {
'disable': False,
'desc': 'Process Table',
'position': 0
}
@patch('sdv.multi_table.base.print')
def test__print(self, mock_print):
"""Test that print info will print a message if verbose is True."""
# Setup
instance = Mock(verbose=True)
# Run
BaseMultiTableSynthesizer._print(instance, text='Fitting', end='')
# Assert
mock_print.assert_called_once_with('Fitting', end='')
@patch('sdv.multi_table.base.datetime')
@patch('sdv.multi_table.base.generate_synthesizer_id')
@patch('sdv.multi_table.base.BaseMultiTableSynthesizer._check_metadata_updated')
def test___init__(self, mock_check_metadata_updated, mock_generate_synthesizer_id,
mock_datetime, caplog):
"""Test that when creating a new instance this sets the defaults.
Test that the metadata object is being stored and also being validated. Afterwards, this
calls the ``self._initialize_models`` which creates the initial instances of those.
"""
# Setup
synthesizer_id = 'BaseMultiTableSynthesizer_1.0.0_92aff11e9a5649d1a280990d1231a5f5'
mock_generate_synthesizer_id.return_value = synthesizer_id
mock_datetime.datetime.now.return_value = '2024-04-19 16:20:10.037183'
metadata = get_multi_table_metadata()
metadata.validate = Mock()
# Run
with catch_sdv_logs(caplog, logging.INFO, 'MultiTableSynthesizer'):
instance = BaseMultiTableSynthesizer(metadata)
# Assert
assert instance.metadata == metadata
assert isinstance(instance._table_synthesizers['nesreca'], GaussianCopulaSynthesizer)
assert isinstance(instance._table_synthesizers['oseba'], GaussianCopulaSynthesizer)
assert isinstance(instance._table_synthesizers['upravna_enota'], GaussianCopulaSynthesizer)
assert instance._table_parameters == defaultdict(dict)
instance.metadata.validate.assert_called_once_with()
mock_check_metadata_updated.assert_called_once()
mock_generate_synthesizer_id.assert_called_once_with(instance)
assert instance._synthesizer_id == synthesizer_id
assert caplog.messages[0] == str({
'EVENT': 'Instance',
'TIMESTAMP': '2024-04-19 16:20:10.037183',
'SYNTHESIZER CLASS NAME': 'BaseMultiTableSynthesizer',
'SYNTHESIZER ID': 'BaseMultiTableSynthesizer_1.0.0_92aff11e9a5649d1a280990d1231a5f5'
})
def test__init__column_relationship_warning(self):
"""Test that a warning is raised only once when the metadata has column relationships."""
# Setup
metadata = get_multi_table_metadata()
metadata.add_column('nesreca', 'lat', sdtype='latitude')
metadata.add_column('nesreca', 'lon', sdtype='longitude')
metadata.add_column_relationship('nesreca', 'gps', ['lat', 'lon'])
expected_warning = (
"The metadata contains a column relationship of type 'gps' "
'which requires the gps add-on. This relationship will be ignored. For higher'
' quality data in this relationship, please inquire about the SDV Enterprise tier.'
)
# Run
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter('always')
BaseMultiTableSynthesizer(metadata)
# Assert
column_relationship_warnings = [
warning for warning in caught_warnings if expected_warning in str(warning.message)
]
assert len(column_relationship_warnings) == 1
def test___init___synthesizer_kwargs_deprecated(self):
"""Test that the ``synthesizer_kwargs`` method is deprecated."""
# Setup
metadata = get_multi_table_metadata()
metadata.validate = Mock()
# Run and Assert
warn_message = (
'The `synthesizer_kwargs` parameter is deprecated as of SDV 1.2.0 and does not '
'affect the synthesizer. Please use the `set_table_parameters` method instead.'
)
with pytest.warns(FutureWarning, match=warn_message):
BaseMultiTableSynthesizer(metadata, synthesizer_kwargs={})
def test__check_metadata_updated(self):
"""Test the ``_check_metadata_updated`` method."""
# Setup
instance = Mock()
instance.metadata = Mock()
instance.metadata._check_updated_flag = Mock()
instance.metadata._reset_updated_flag = Mock()
# Run
expected_message = re.escape(
"We strongly recommend saving the metadata using 'save_to_json' for replicability"
' in future SDV versions.'
)
with pytest.warns(UserWarning, match=expected_message):
BaseMultiTableSynthesizer._check_metadata_updated(instance)
# Assert
instance.metadata._check_updated_flag.assert_called_once()
instance.metadata._reset_updated_flag.assert_called_once()
def test_set_address_columns(self):
"""Test the ``set_address_columns`` method."""
# Setup
metadata = MultiTableMetadata().load_from_dict({
'tables': {
'address_table': {
'columns': {
'country_column': {'sdtype': 'country_code'},
'city_column': {'sdtype': 'city'},
'parent_key': {'sdtype': 'id'},
},
'primary_key': 'parent_key'
},
'other_table': {
'columns': {
'numerical_column': {'sdtype': 'numerical'},
'child_foreign_key': {'sdtype': 'id'},
}
}
},
'relationships': [
{
'parent_table_name': 'address_table',
'parent_primary_key': 'parent_key',
'child_table_name': 'other_table',
'child_foreign_key': 'child_foreign_key'
}
]
})
columns = ('country_column', 'city_column')
metadata.validate = Mock()
SingleTableMetadata.validate = Mock()
instance = BaseMultiTableSynthesizer(metadata)
instance._table_synthesizers['address_table'].set_address_columns = Mock()
# Run
instance.set_address_columns(
'address_table', columns, anonymization_level='street_address'
)
# Assert
instance._table_synthesizers['address_table'].set_address_columns.assert_called_once_with(
columns, 'street_address'
)
def test_set_address_columns_error(self):
"""Test that ``set_address_columns`` raises an error for unknown table."""
# Setup
metadata = MultiTableMetadata()
columns = ('country_column', 'city_column')
metadata.validate = Mock()
SingleTableMetadata.validate = Mock()
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
expected_error = re.escape(
'The provided data does not match the metadata:\n'
"Table 'address_table' is not present in the metadata."
)
with pytest.raises(ValueError, match=expected_error):
instance.set_address_columns(
'address_table', columns, anonymization_level='street_address'
)
def test_get_table_parameters_empty(self):
"""Test that this method returns an empty dictionary when there are no parameters."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
# Run
result = instance.get_table_parameters('oseba')
# Assert
assert result == {
'synthesizer_name': 'GaussianCopulaSynthesizer',
'synthesizer_parameters': {
'default_distribution': 'beta',
'enforce_min_max_values': True,
'enforce_rounding': True,
'locales': ['en_US'],
'numerical_distributions': {}
}
}
def test_get_table_parameters_has_parameters(self):
"""Test that this method returns a dictionary with the parameters."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
instance.set_table_parameters('oseba', {'default_distribution': 'gamma'})
# Run
result = instance.get_table_parameters('oseba')
# Assert
assert result['synthesizer_parameters'] == {
'default_distribution': 'gamma',
'enforce_min_max_values': True,
'enforce_rounding': True,
'locales': ['en_US'],
'numerical_distributions': {}
}
def test_get_parameters(self):
"""Test that the synthesizer's parameters are being returned."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata, locales='en_CA')
# Run
result = instance.get_parameters()
# Assert
assert result == {'locales': 'en_CA', 'synthesizer_kwargs': None}
def test_set_table_parameters(self):
"""Test that the table's parameters are being updated.
This test should ensure that the ``self._table_parameters`` for the given table
are being updated with the given parameters, and also that the model is re-created
and updated it's parameters as well.
"""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
# Run
instance.set_table_parameters('oseba', {'default_distribution': 'gamma'})
# Assert
table_parameters = instance.get_table_parameters('oseba')
assert instance._table_parameters['oseba'] == {'default_distribution': 'gamma'}
assert table_parameters['synthesizer_name'] == 'GaussianCopulaSynthesizer'
assert table_parameters['synthesizer_parameters'] == {
'default_distribution': 'gamma',
'enforce_min_max_values': True,
'locales': ['en_US'],
'enforce_rounding': True,
'numerical_distributions': {}
}
def test_set_table_parameters_invalid_enforce_min_max_values(self):
"""Test it crashes when ``enforce_min_max_values`` is not a boolean."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
err_msg = re.escape(
"Invalid value 'invalid' for parameter 'enforce_min_max_values'."
' Please provide True or False.'
)
with pytest.raises(SynthesizerInputError, match=err_msg):
instance.set_table_parameters('oseba', {'enforce_min_max_values': 'invalid'})
def test_set_table_parameters_invalid_enforce_rounding(self):
"""Test it crashes when ``enforce_rounding`` is not a boolean."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
err_msg = re.escape(
"Invalid value 'invalid' for parameter 'enforce_rounding'."
' Please provide True or False.'
)
with pytest.raises(SynthesizerInputError, match=err_msg):
instance.set_table_parameters('oseba', {'enforce_rounding': 'invalid'})
def test_get_metadata(self):
"""Test that the metadata object is returned."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
# Run
result = instance.get_metadata()
# Assert
assert metadata == result
def test_validate(self):
"""Test that no error is being raised when the data is valid."""
# Setup
metadata = get_multi_table_metadata()
data = get_multi_table_data()
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
instance.validate(data)
def test_validate_missing_table(self):
"""Test that an error is being raised when there is a missing table in the dictionary."""
# Setup
metadata = get_multi_table_metadata()
data = get_multi_table_data()
data.pop('nesreca')
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
error_msg = "The provided data is missing the tables {'nesreca'}."
with pytest.raises(InvalidDataError, match=error_msg):
instance.validate(data)
def test_validate_key_error(self):
"""Test that if a ``KeyError`` is raised the code will continue without erroring."""
# Setup
metadata = get_multi_table_metadata()
data = get_multi_table_data()
instance = BaseMultiTableSynthesizer(metadata)
instance._table_synthesizers.popitem()
# Run and Assert
instance.validate(data)
def test_validate_data_is_not_dataframe(self):
"""Test that an error is being raised when the data is not a dataframe."""
# Setup
metadata = get_multi_table_metadata()
data = get_multi_table_data()
data['nesreca'] = pd.Series({
'id_nesreca': np.arange(10),
'upravna_enota': np.arange(10),
})
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
error_msg = "Data must be a DataFrame, not a <class 'pandas.core.series.Series'>."
with pytest.raises(InvalidDataError, match=error_msg):
instance.validate(data)
def test_validate_data_does_not_match(self):
"""Test that an error is being raised when the data does not match the metadata."""
# Setup
metadata = get_multi_table_metadata()
data = {
'nesreca': pd.DataFrame({
'id_nesreca': np.arange(10),
'upravna_enota': np.arange(10),
'nesreca_val': np.arange(10).astype(str)
}),
'oseba': pd.DataFrame({
'upravna_enota': np.arange(10),
'id_nesreca': np.arange(10),
'oseba_val': np.arange(10).astype(str)
}),
'upravna_enota': pd.DataFrame({
'id_upravna_enota': np.arange(10),
'upravna_val': np.arange(10).astype(str)
}),
}
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
error_msg = re.escape(
'The provided data does not match the metadata:\n'
"Table: 'nesreca'\n"
"Error: Invalid values found for numerical column 'nesreca_val': ['0', '1', '2', "
"'+ 7 more']."
"\n\nTable: 'oseba'\n"
"Error: Invalid values found for numerical column 'oseba_val': ['0', '1', '2', "
"'+ 7 more']."
"\n\nTable: 'upravna_enota'\n"
"Error: Invalid values found for numerical column 'upravna_val': ['0', '1', '2', "
"'+ 7 more']."
)
with pytest.raises(InvalidDataError, match=error_msg):
instance.validate(data)
def test_validate_missing_foreign_keys(self):
"""Test that errors are being raised when there are missing foreign keys."""
# Setup
metadata = get_multi_table_metadata()
data = {
'nesreca': pd.DataFrame({
'id_nesreca': np.arange(0, 20, 2),
'upravna_enota': np.arange(10),
'nesreca_val': np.arange(10)
}),
'oseba': pd.DataFrame({
'upravna_enota': np.arange(10),
'id_nesreca': np.arange(10),
'oseba_val': np.arange(10)
}),
'upravna_enota': pd.DataFrame({
'id_upravna_enota': np.arange(10),
'upravna_val': np.arange(10)
}),
}
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
error_msg = re.escape(
'The provided data does not match the metadata:\n'
'Relationships:\n'
"Error: foreign key column 'id_nesreca' contains unknown references: (1, 3, 5, 7, 9). "
"Please use the method 'drop_unknown_references' from sdv.utils to clean the data."
)
with pytest.raises(InvalidDataError, match=error_msg):
instance.validate(data)
def test_validate_constraints_not_met(self):
"""Test that errors are being raised when there are constraints not met."""
# Setup
metadata = get_multi_table_metadata()
data = get_multi_table_data()
data['nesreca']['val'] = list(range(4))
metadata.add_column('nesreca', 'val', sdtype='numerical')
instance = BaseMultiTableSynthesizer(metadata)
inequality_constraint = {
'constraint_class': 'Inequality',
'table_name': 'nesreca',
'constraint_parameters': {
'low_column_name': 'nesreca_val',
'high_column_name': 'val',
'strict_boundaries': True
}
}
instance.add_constraints([inequality_constraint])
# Run and Assert
error_msg = (
"\nData is not valid for the 'Inequality' constraint:\n"
' nesreca_val val\n'
'0 0 0\n'
'1 1 1\n'
'2 2 2\n'
'3 3 3'
)
with pytest.raises(ConstraintsNotMetError, match=error_msg):
instance.validate(data)
def test_validate_table_synthesizers_errors(self):
"""Test that errors are being raised when the table synthesizer is erroring."""
# Setup
metadata = get_multi_table_metadata()
data = get_multi_table_data()
instance = BaseMultiTableSynthesizer(metadata)
nesreca_synthesizer = Mock()
nesreca_synthesizer._validate.return_value = ['Invalid data for PAR synthesizer.']
instance._table_synthesizers['nesreca'] = nesreca_synthesizer
# Run and Assert
error_msg = (
'The provided data does not match the metadata:\n'
'Invalid data for PAR synthesizer.'
)
with pytest.raises(InvalidDataError, match=error_msg):
instance.validate(data)
def test_auto_assign_transformers(self):
"""Test that each table of the data calls its single table auto assign method."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
table1 = pd.DataFrame({'col1': [1, 2]})
table2 = pd.DataFrame({'col2': [1, 2]})
data = {
'nesreca': table1,
'oseba': table2
}
instance._table_synthesizers['nesreca'] = Mock()
instance._table_synthesizers['oseba'] = Mock()
# Run
instance.auto_assign_transformers(data)
# Assert
instance._table_synthesizers['nesreca'].auto_assign_transformers.assert_called_once_with(
table1)
instance._table_synthesizers['oseba'].auto_assign_transformers.assert_called_once_with(
table2)
def test_auto_assign_transformers_foreign_key_none(self):
"""Test that each table's foreign key transformers are set to None."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
data = {
'nesreca': Mock(),
'oseba': Mock()
}
instance.validate = Mock()
instance.metadata._get_all_foreign_keys = Mock(return_value=['a', 'b'])
nesreca_synthesizer = Mock()
oseba_synthesizer = Mock()
instance._table_synthesizers['nesreca'] = nesreca_synthesizer
instance._table_synthesizers['oseba'] = oseba_synthesizer
# Run
instance.auto_assign_transformers(data)
# Assert
nesreca_synthesizer.update_transformers.assert_called_once_with({'a': None, 'b': None})
oseba_synthesizer.update_transformers.assert_called_once_with({'a': None, 'b': None})
def test_auto_assign_transformers_missing_table(self):
"""Test it errors out when the passed table was not seen in the metadata."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
data = {'not_seen': pd.DataFrame({'col': [1, 2]})}
# Run and Assert
err_msg = re.escape(
'The provided data does not match the metadata:'
"\nTable 'not_seen' is not present in the metadata"
)
with pytest.raises(ValueError, match=err_msg):
instance.auto_assign_transformers(data)
def test_get_transformers(self):
"""Test that each table of the data calls its single table get_transformers method."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
instance._table_synthesizers['nesreca'] = Mock()
instance._table_synthesizers['oseba'] = Mock()
# Run
instance.get_transformers('oseba')
# Assert
instance._table_synthesizers['nesreca'].get_transformers.assert_not_called()
instance._table_synthesizers['oseba'].get_transformers.assert_called_once()
def test_get_transformers_missing_table(self):
"""Test it errors out when the passed table name was not seen in the metadata."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
err_msg = re.escape(
'The provided data does not match the metadata:'
"\nTable 'not_seen' is not present in the metadata."
)
with pytest.raises(ValueError, match=err_msg):
instance.get_transformers('not_seen')
def test_update_transformers(self):
"""Test that each table of the data calls its single table update_transformers method."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
instance._table_synthesizers['nesreca'] = Mock()
instance._table_synthesizers['oseba'] = Mock()
# Run
instance.update_transformers('oseba', {})
# Assert
instance._table_synthesizers['nesreca'].update_transformers.assert_not_called()
instance._table_synthesizers['oseba'].update_transformers.assert_called_once_with({})
def test_update_transformers_missing_table(self):
"""Test it errors out when the passed table name was not seen in the metadata."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
# Run and Assert
err_msg = re.escape(
'The provided data does not match the metadata:'
"\nTable 'not_seen' is not present in the metadata."
)
with pytest.raises(ValueError, match=err_msg):
instance.update_transformers('not_seen', {})
def test__model_tables(self):
"""Test that ``_model_tables`` raises a ``NotImplementedError``."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
data = {
'nesreca': pd.DataFrame({
'id_nesreca': np.arange(0, 20, 2),
'upravna_enota': np.arange(10),
}),
'oseba': pd.DataFrame({
'upravna_enota': np.arange(10),
'id_nesreca': np.arange(10),
}),
'upravna_enota': pd.DataFrame({
'id_upravna_enota': np.arange(10),
}),
}
# Run and Assert
with pytest.raises(NotImplementedError, match=''):
instance._model_tables(data)
def test__assign_table_transformers(self):
"""Test the ``_assign_table_transformers`` method.
Test that the function creates a dictionary mapping with the columns returned from
``_get_all_foreign_keys`` and maps them to the value ``None`` to avoid being transformed.
Then calls ``update_transformers`` for the given ``synthesizer``.
"""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
instance.validate = Mock()
instance.metadata._get_all_foreign_keys = Mock(return_value=['a', 'b'])
synthesizer = Mock()
table_data = Mock()
# Run
instance._assign_table_transformers(synthesizer, 'oseba', table_data)
# Assert
synthesizer.auto_assign_transformers.assert_called_once_with(table_data)
synthesizer.update_transformers.assert_called_once_with({'a': None, 'b': None})
def test_preprocess(self):
"""Test that ``preprocess`` iterates over the ``data`` and preprocess it.
This method should call ``instance.validate`` to validate the data, then
iterate over the ``data`` dictionary and transform it using the ``synthesizer``
``preprocess`` method.
"""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
instance.validate = Mock()
instance.metadata._get_all_foreign_keys = Mock(return_value=['a', 'b'])
data = {
'nesreca': pd.DataFrame({
'id_nesreca': np.arange(0, 20, 2),
'upravna_enota': np.arange(10),
}),
'oseba': pd.DataFrame({
'upravna_enota': np.arange(10),
'id_nesreca': np.arange(10),
}),
'upravna_enota': pd.DataFrame({
'id_upravna_enota': np.arange(10),
}),
}
synth_nesreca = Mock()
synth_oseba = Mock()
synth_upravna_enota = Mock()
instance._table_synthesizers = {
'nesreca': synth_nesreca,
'oseba': synth_oseba,
'upravna_enota': synth_upravna_enota
}
# Run
result = instance.preprocess(data)
# Assert
assert result == {
'nesreca': synth_nesreca._preprocess.return_value,
'oseba': synth_oseba._preprocess.return_value,
'upravna_enota': synth_upravna_enota._preprocess.return_value
}
instance.validate.assert_called_once_with(data)
assert instance.metadata._get_all_foreign_keys.call_args_list == [
call('nesreca'),
call('oseba'),
call('upravna_enota')
]
synth_nesreca.auto_assign_transformers.assert_called_once_with(data['nesreca'])
synth_nesreca._preprocess.assert_called_once_with(data['nesreca'])
synth_nesreca.update_transformers.assert_called_once_with({'a': None, 'b': None})
synth_oseba._preprocess.assert_called_once_with(data['oseba'])
synth_oseba._preprocess.assert_called_once_with(data['oseba'])
synth_oseba.update_transformers.assert_called_once_with({'a': None, 'b': None})
synth_upravna_enota._preprocess.assert_called_once_with(data['upravna_enota'])
synth_upravna_enota._preprocess.assert_called_once_with(data['upravna_enota'])
synth_upravna_enota.update_transformers.assert_called_once_with({'a': None, 'b': None})
def test_preprocess_int_columns(self):
"""Test the preprocess method.
Ensure that data with column names as integers are not changed by
preprocess.
"""
# Setup
metadata_dict = {
'tables': {
'first_table': {
'primary_key': '1',
'columns': {
'1': {'sdtype': 'id'},
'2': {'sdtype': 'categorical'},
'str': {'sdtype': 'categorical'}
}
},
'second_table': {
'columns': {
'3': {'sdtype': 'id'},
'str': {'sdtype': 'categorical'}
}
}
},
'relationships': [
{
'parent_table_name': 'first_table',
'parent_primary_key': '1',
'child_table_name': 'second_table',
'child_foreign_key': '3'
}
]
}
metadata = MultiTableMetadata.load_from_dict(metadata_dict)
instance = BaseMultiTableSynthesizer(metadata)
instance.validate = Mock()
instance._table_synthesizers = {
'first_table': Mock(),
'second_table': Mock()
}
multi_data = {
'first_table': pd.DataFrame({
1: ['abc', 'def', 'ghi'],
2: ['x', 'a', 'b'],
'str': ['John', 'Doe', 'John Doe'],
}),
'second_table': pd.DataFrame({
3: ['abc', 'def', 'ghi'],
'another': ['John', 'Doe', 'John Doe'],
}),
}
# Run
instance.preprocess(multi_data)
# Assert
corrected_frame = {
'first_table': pd.DataFrame({
1: ['abc', 'def', 'ghi'],
2: ['x', 'a', 'b'],
'str': ['John', 'Doe', 'John Doe'],
}),
'second_table': pd.DataFrame({
3: ['abc', 'def', 'ghi'],
'another': ['John', 'Doe', 'John Doe'],
}),
}
pd.testing.assert_frame_equal(multi_data['first_table'], corrected_frame['first_table'])
pd.testing.assert_frame_equal(multi_data['second_table'], corrected_frame['second_table'])
@patch('sdv.multi_table.base.warnings')
def test_preprocess_warning(self, mock_warnings):
"""Test that ``preprocess`` warns the user if the model has already been fitted."""
# Setup
metadata = get_multi_table_metadata()
instance = BaseMultiTableSynthesizer(metadata)
instance.validate = Mock()
data = {
'nesreca': pd.DataFrame({
'id_nesreca': np.arange(0, 20, 2),
'upravna_enota': np.arange(10),
}),
'oseba': pd.DataFrame({
'upravna_enota': np.arange(10),
'id_nesreca': np.arange(10),
}),
'upravna_enota': pd.DataFrame({
'id_upravna_enota': np.arange(10),
}),
}
synth_nesreca = Mock()
synth_oseba = Mock()
synth_upravna_enota = Mock()
instance._table_synthesizers = {
'nesreca': synth_nesreca,
'oseba': synth_oseba,
'upravna_enota': synth_upravna_enota
}
instance._fitted = True
# Run
result = instance.preprocess(data)
# Assert
assert result == {
'nesreca': synth_nesreca._preprocess.return_value,
'oseba': synth_oseba._preprocess.return_value,
'upravna_enota': synth_upravna_enota._preprocess.return_value
}
instance.validate.assert_called_once_with(data)
synth_nesreca._preprocess.assert_called_once_with(data['nesreca'])
synth_oseba._preprocess.assert_called_once_with(data['oseba'])
synth_upravna_enota._preprocess.assert_called_once_with(data['upravna_enota'])
mock_warnings.warn.assert_called_once_with(
'This model has already been fitted. To use the new preprocessed data, '
"please refit the model using 'fit' or 'fit_processed_data'."
)
@patch('sdv.multi_table.base.datetime')
def test_fit_processed_data(self, mock_datetime, caplog):
"""Test that fit processed data calls ``_augment_tables`` and ``_model_tables``.
Ensure that the ``fit_processed_data`` augments the tables and then models those using
the ``_model_tables`` method. Then sets the state to fitted.
"""
# Setup
mock_datetime.datetime.now.return_value = '2024-04-19 16:20:10.037183'
instance = Mock(
_fitted_sdv_version=None,
_fitted_sdv_enterprise_version=None,
_synthesizer_id='BaseMultiTableSynthesizer_1.0.0_92aff11e9a5649d1a280990d1231a5f5'
)
processed_data = {
'table1': pd.DataFrame({'id': [1, 2, 3], 'name': ['John', 'Johanna', 'Doe']}),
'table2': pd.DataFrame({'id': [1, 2, 3], 'name': ['John', 'Johanna', 'Doe']})
}
# Run
with catch_sdv_logs(caplog, logging.INFO, 'MultiTableSynthesizer'):
BaseMultiTableSynthesizer.fit_processed_data(instance, processed_data)
# Assert
instance._augment_tables.assert_called_once_with(processed_data)
instance._model_tables.assert_called_once_with(instance._augment_tables.return_value)
assert instance._fitted
assert caplog.messages[0] == str({
'EVENT': 'Fit processed data',
'TIMESTAMP': '2024-04-19 16:20:10.037183',
'SYNTHESIZER CLASS NAME': 'Mock',
'SYNTHESIZER ID': 'BaseMultiTableSynthesizer_1.0.0_92aff11e9a5649d1a280990d1231a5f5',
'TOTAL NUMBER OF TABLES': 2,
'TOTAL NUMBER OF ROWS': 6,
'TOTAL NUMBER OF COLUMNS': 4
})
def test_fit_processed_data_empty_table(self):
"""Test attributes are properly set when data is empty and that _fit is not called."""
# Setup
instance = Mock(
_fitted_sdv_version=None,
_fitted_sdv_enterprise_version=None
)
processed_data = {
'table1': pd.DataFrame(),
'table2': pd.DataFrame()
}
# Run
BaseMultiTableSynthesizer.fit_processed_data(instance, processed_data)
# Assert
instance._fit.assert_not_called()
assert instance._fitted
assert instance._fitted_date
assert instance._fitted_sdv_version
def test_fit_processed_data_raises_version_error(self):
"""Test that fit_processed data will raise a ``VersionError``."""
# Setup
instance = Mock(
_fitted_sdv_version='1.0.0',
_fitted_sdv_enterprise_version=None
)
instance.metadata = Mock()
processed_data = {
'table1': pd.DataFrame(),
'table2': pd.DataFrame()
}
# Run and Assert
error_msg = (
f'You are currently on SDV version {version.public} but this synthesizer '
'was created on version 1.0.0. Fitting this synthesizer again is not supported. '
'Please create a new synthesizer.'
)
with pytest.raises(VersionError, match=error_msg):
BaseMultiTableSynthesizer.fit_processed_data(instance, processed_data)
# Assert
instance.preprocess.assert_not_called()
instance.fit_processed_data.assert_not_called()
instance._check_metadata_updated.assert_not_called()
@patch('sdv.multi_table.base.datetime')
@patch('sdv.multi_table.base._validate_foreign_keys_not_null')
def test_fit(self, mock_validate_foreign_keys_not_null, mock_datetime, caplog):
"""Test that it calls the appropriate methods."""
# Setup
mock_datetime.datetime.now.return_value = '2024-04-19 16:20:10.037183'
instance = Mock(
_fitted_sdv_version=None,
_fitted_sdv_enterprise_version=None,
_synthesizer_id='BaseMultiTableSynthesizer_1.0.0_92aff11e9a5649d1a280990d1231a5f5'
)
instance.metadata = Mock()