-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathtest_sources.py
More file actions
402 lines (276 loc) · 13.2 KB
/
test_sources.py
File metadata and controls
402 lines (276 loc) · 13.2 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
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from datetime import datetime
from unittest.mock import Mock
import pytest
import data_designer.lazy_heavy_imports as lazy
from data_designer.config.sampler_params import (
BernoulliSamplerParams,
CategorySamplerParams,
DatetimeSamplerParams,
GaussianSamplerParams,
PersonSamplerParams,
SamplerType,
ScipySamplerParams,
SubcategorySamplerParams,
TimeDeltaSamplerParams,
UniformSamplerParams,
UUIDSamplerParams,
)
from data_designer.engine.sampling_gen.data_sources.base import (
DataSource,
DatetimeFormatMixin,
PassthroughMixin,
Sampler,
ScipyStatsSampler,
TypeConversionMixin,
)
from data_designer.engine.sampling_gen.data_sources.errors import InvalidSamplerParamsError
from data_designer.engine.sampling_gen.data_sources.sources import (
BernoulliSampler,
CategorySampler,
DatetimeSampler,
GaussianSampler,
PersonSampler,
SamplerRegistry,
ScipySampler,
SubcategorySampler,
TimeDeltaSampler,
UniformSampler,
UUIDSampler,
load_sampler,
)
@pytest.fixture
def stub_people_gen():
mock_gen = Mock()
mock_gen.generate.return_value = [
{"first_name": "John", "last_name": "Doe"},
{"first_name": "Jane", "last_name": "Smith"},
]
return mock_gen
def test_data_source_get_param_type():
assert hasattr(DataSource, "get_param_type")
def test_data_source_get_required_column_names():
assert hasattr(DataSource, "get_required_column_names")
def test_sampler_recast_types_if_needed():
assert hasattr(Sampler, "_recast_types_if_needed")
def test_sampler_inject_data_column_empty_index():
assert hasattr(Sampler, "inject_data_column")
def test_scipy_stats_sampler_sample_method():
assert hasattr(ScipyStatsSampler, "sample")
def test_passthrough_mixin_preproc_passthrough():
series = lazy.pd.Series([1, 2, 3])
result = PassthroughMixin.preproc(series, "int")
lazy.pd.testing.assert_series_equal(result, series)
def test_passthrough_mixin_postproc_passthrough():
series = lazy.pd.Series([1, 2, 3])
result = PassthroughMixin.postproc(series, "int")
lazy.pd.testing.assert_series_equal(result, series)
def test_passthrough_mixin_validate_data_conversion_passthrough():
PassthroughMixin.validate_data_conversion("int")
PassthroughMixin.validate_data_conversion(None)
def test_type_conversion_mixin_preproc_type_conversion():
series = lazy.pd.Series([1.5, 2.7, 3.2])
result = TypeConversionMixin.preproc(series, "int")
expected = lazy.pd.Series([2, 3, 3], dtype="int64")
lazy.pd.testing.assert_series_equal(result, expected)
result = TypeConversionMixin.preproc(series, "str")
expected = lazy.pd.Series(["1.5", "2.7", "3.2"], dtype="str")
lazy.pd.testing.assert_series_equal(result, expected)
def test_type_conversion_mixin_postproc_type_conversion():
series = lazy.pd.Series([1.5, 2.7, 3.2])
result = TypeConversionMixin.postproc(series, "int")
expected = lazy.pd.Series([2, 3, 3], dtype="int64")
lazy.pd.testing.assert_series_equal(result, expected)
def test_type_conversion_mixin_validate_data_conversion_valid():
TypeConversionMixin.validate_data_conversion("float")
TypeConversionMixin.validate_data_conversion("int")
TypeConversionMixin.validate_data_conversion("str")
TypeConversionMixin.validate_data_conversion(None)
def test_type_conversion_mixin_validate_data_conversion_invalid():
with pytest.raises(ValueError, match="Invalid `convert_to` value"):
TypeConversionMixin.validate_data_conversion("invalid")
def test_datetime_format_mixin_preproc_datetime():
series = lazy.pd.Series(lazy.pd.date_range("2023-01-01", periods=3))
result = DatetimeFormatMixin.preproc(series, "%Y-%m-%d")
lazy.pd.testing.assert_series_equal(result, series)
def test_datetime_format_mixin_postproc_datetime_formatting():
series = lazy.pd.Series(lazy.pd.date_range("2023-01-01", periods=3))
result = DatetimeFormatMixin.postproc(series, "%Y-%m-%d")
expected = lazy.pd.Series(["2023-01-01", "2023-01-02", "2023-01-03"], dtype="str")
lazy.pd.testing.assert_series_equal(result, expected)
def test_datetime_format_mixin_validate_data_conversion_valid_format():
DatetimeFormatMixin.validate_data_conversion("%Y-%m-%d")
DatetimeFormatMixin.validate_data_conversion(None)
def test_datetime_format_mixin_postproc_no_convert_to_returns_isoformat():
series = lazy.pd.Series(lazy.pd.date_range("2023-01-01", periods=3))
result = DatetimeFormatMixin.postproc(series, None)
expected = lazy.pd.Series(["2023-01-01T00:00:00", "2023-01-02T00:00:00", "2023-01-03T00:00:00"], dtype="str")
lazy.pd.testing.assert_series_equal(result, expected)
def test_datetime_format_mixin_postproc_single_record():
series = lazy.pd.Series(lazy.pd.to_datetime(["2024-06-15 14:30:00"]))
result = DatetimeFormatMixin.postproc(series, None)
expected = lazy.pd.Series(["2024-06-15T14:30:00"], dtype="str")
lazy.pd.testing.assert_series_equal(result, expected)
def test_datetime_format_mixin_postproc_same_month_records():
series = lazy.pd.Series(lazy.pd.to_datetime(["2024-03-01", "2024-03-15", "2024-03-28"]))
result = DatetimeFormatMixin.postproc(series, None)
expected = lazy.pd.Series(["2024-03-01T00:00:00", "2024-03-15T00:00:00", "2024-03-28T00:00:00"], dtype="str")
lazy.pd.testing.assert_series_equal(result, expected)
def test_datetime_format_mixin_postproc_stdlib_fromisoformat():
"""Output must be parseable by Python stdlib datetime.fromisoformat, not just pandas."""
series = lazy.pd.Series(lazy.pd.to_datetime(["2024-06-15 14:30:00", "2025-01-01 00:00:00"]))
result = DatetimeFormatMixin.postproc(series, None)
for val in result:
datetime.fromisoformat(val)
def test_datetime_format_mixin_postproc_round_trip_preserves_values():
"""Output can be parsed back to the original timestamps."""
series = lazy.pd.Series(lazy.pd.to_datetime(["2024-03-15 09:30:00", "2024-11-01 18:45:00"]))
result = DatetimeFormatMixin.postproc(series, None)
round_tripped = lazy.pd.to_datetime(result)
lazy.pd.testing.assert_series_equal(round_tripped, series, check_names=False, check_dtype=False)
def test_datetime_format_mixin_validate_data_conversion_invalid_format():
with pytest.raises(ValueError, match="Invalid datetime format"):
DatetimeFormatMixin.validate_data_conversion("invalid_format")
def test_sampler_registry_register_decorator():
class TestSampler(DataSource):
pass
SamplerRegistry.register("test")(TestSampler)
assert "test" in SamplerRegistry._registry
assert SamplerRegistry._registry["test"] == TestSampler
def test_sampler_registry_get_sampler():
class TestSampler(DataSource):
pass
SamplerRegistry.register("test")(TestSampler)
result = SamplerRegistry.get_sampler("TEST")
assert result == TestSampler
def test_sampler_registry_is_registered():
class TestSampler(DataSource):
pass
SamplerRegistry.register("test")(TestSampler)
assert SamplerRegistry.is_registered("test")
assert not SamplerRegistry.is_registered("nonexistent")
def test_sampler_registry_validate_sampler_type_string():
class TestSampler(DataSource):
pass
SamplerRegistry.register("test")(TestSampler)
result = SamplerRegistry.validate_sampler_type("test")
assert result == TestSampler
def test_sampler_registry_validate_sampler_type_class():
class TestSampler(DataSource):
pass
result = SamplerRegistry.validate_sampler_type(TestSampler)
assert result == TestSampler
def test_sampler_registry_validate_sampler_type_invalid_string():
with pytest.raises(ValueError, match="Sampler type `invalid` not found"):
SamplerRegistry.validate_sampler_type("invalid")
def test_sampler_registry_validate_sampler_type_invalid_class():
class NotDataSource:
pass
with pytest.raises(ValueError, match="is not a subclass of `DataSource`"):
SamplerRegistry.validate_sampler_type(NotDataSource)
def test_subcategory_sampler_get_required_column_names():
params = SubcategorySamplerParams(category="test_col", values={"A": ["1", "2"], "B": ["3", "4"]})
sampler = SubcategorySampler(params=params)
assert sampler.get_required_column_names() == ("test_col",)
def test_subcategory_sampler_inject_data_column(stub_sample_dataframe):
params = SubcategorySamplerParams(category="category", values={"A": ["1", "2"], "B": ["3", "4"]})
sampler = SubcategorySampler(params=params)
result = sampler.inject_data_column(stub_sample_dataframe, "new_col", index=[0, 1, 2, 3])
assert "new_col" in result.columns
assert len(result) == 4
def test_category_sampler_sample():
params = CategorySamplerParams(values=["A", "B", "C"], weights=[0.5, 0.3, 0.2])
sampler = CategorySampler(params=params, random_state=42)
result = sampler.sample(10)
assert len(result) == 10
assert all(val in ["A", "B", "C"] for val in result)
def test_datetime_sampler_sample():
params = DatetimeSamplerParams(start="2023-01-01", end="2023-12-31", unit="D")
sampler = DatetimeSampler(params=params, random_state=42)
result = sampler.sample(5)
assert len(result) == 5
assert all(isinstance(val, lazy.np.datetime64) for val in result)
def test_person_sampler_setup_with_generator(stub_people_gen):
params = PersonSamplerParams()
people_gen_resource = {"en_US": stub_people_gen}
sampler = PersonSampler(params=params, people_gen_resource=people_gen_resource)
assert sampler._generator == stub_people_gen
def test_person_sampler_setup_without_generator():
params = PersonSamplerParams()
sampler = PersonSampler(params=params)
assert sampler._generator is None
def test_person_sampler_sample_with_generator(stub_people_gen):
params = PersonSamplerParams()
sampler = PersonSampler(params=params)
sampler.set_generator(stub_people_gen)
result = sampler.sample(2)
assert len(result) == 2
def test_person_sampler_sample_without_generator():
params = PersonSamplerParams()
sampler = PersonSampler(params=params)
with pytest.raises(ValueError, match="Generator not set"):
sampler.sample(2)
def test_time_delta_sampler_get_required_column_names():
params = TimeDeltaSamplerParams(reference_column_name="date_col", dt_min=1, dt_max=30, unit="D")
sampler = TimeDeltaSampler(params=params)
assert sampler.get_required_column_names() == ("date_col",)
def test_time_delta_sampler_sample():
params = TimeDeltaSamplerParams(reference_column_name="date_col", dt_min=1, dt_max=30, unit="D")
sampler = TimeDeltaSampler(params=params, random_state=42)
result = sampler.sample(5)
assert len(result) == 5
assert all(isinstance(val, lazy.np.timedelta64) for val in result)
def test_uuid_sampler_sample_basic():
params = UUIDSamplerParams(prefix="TEST", short_form=True, uppercase=True)
sampler = UUIDSampler(params=params, random_state=42)
result = sampler.sample(3)
assert len(result) == 3
assert all(isinstance(val, str) for val in result)
assert all(val.startswith("TEST") for val in result)
def test_uuid_sampler_sample_no_duplicates():
params = UUIDSamplerParams(prefix="", short_form=True, uppercase=False)
sampler = UUIDSampler(params=params, random_state=42)
result = sampler.sample(10)
assert len(result) == 10
assert len(set(result)) == 10
def test_scipy_sampler_distribution_property():
params = ScipySamplerParams(dist_name="norm", dist_params={"loc": 0, "scale": 1})
sampler = ScipySampler(params=params)
dist = sampler.distribution
assert hasattr(dist, "rvs")
def test_scipy_sampler_sample():
params = ScipySamplerParams(dist_name="norm", dist_params={"loc": 0, "scale": 1})
sampler = ScipySampler(params=params, random_state=42)
result = sampler.sample(10)
assert len(result) == 10
assert all(isinstance(val, (int, float)) for val in result)
def test_scipy_sampler_validate_invalid_distribution():
params = ScipySamplerParams(dist_name="nonexistent", dist_params={})
with pytest.raises(InvalidSamplerParamsError):
ScipySampler(params=params)
def test_bernoulli_sampler():
params = BernoulliSamplerParams(p=0.5)
sampler = BernoulliSampler(params=params, random_state=42)
result = sampler.sample(10)
assert len(result) == 10
assert all(val in [0, 1] for val in result)
def test_gaussian_sampler():
params = GaussianSamplerParams(mean=0, stddev=1)
sampler = GaussianSampler(params=params, random_state=42)
result = sampler.sample(10)
assert len(result) == 10
assert all(isinstance(val, (int, float)) for val in result)
def test_uniform_sampler():
params = UniformSamplerParams(low=0, high=10)
sampler = UniformSampler(params=params, random_state=42)
result = sampler.sample(10)
assert len(result) == 10
assert all(0 <= val <= 10 for val in result)
def test_load_sampler():
sampler = load_sampler(SamplerType.GAUSSIAN, mean=0, stddev=1)
assert isinstance(sampler, GaussianSampler)
def test_load_sampler_invalid_type():
with pytest.raises(ValueError):
load_sampler("invalid_type")