forked from RascalSoftware/python-RAT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_models.py
More file actions
391 lines (345 loc) · 13.5 KB
/
test_models.py
File metadata and controls
391 lines (345 loc) · 13.5 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
"""Test the pydantic models."""
import pathlib
import re
from typing import Callable
import numpy as np
import pydantic
import pytest
import RATapi.models
@pytest.mark.parametrize(
["model", "model_name", "model_params"],
[
(RATapi.models.Background, "Background", {}),
(RATapi.models.Contrast, "Contrast", {}),
(RATapi.models.CustomFile, "Custom File", {}),
(RATapi.models.Data, "Data", {}),
(RATapi.models.DomainContrast, "Domain Contrast", {}),
(
RATapi.models.Layer,
"Layer",
{"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"},
),
(RATapi.models.Parameter, "Parameter", {}),
(RATapi.models.Resolution, "Resolution", {}),
],
)
def test_default_names(model: Callable, model_name: str, model_params: dict) -> None:
"""When initialising multiple models without specifying a name, they should be given a default name with the
format: "New <model name> <integer>".
"""
model_1 = model(**model_params)
model_2 = model(**model_params)
model_3 = model(name="Given Name", **model_params)
model_4 = model(**model_params)
assert model_1.name == f"New {model_name} 1"
assert model_2.name == f"New {model_name} 2"
assert model_3.name == "Given Name"
assert model_4.name == f"New {model_name} 3"
@pytest.mark.parametrize(
["model", "model_params"],
[
(RATapi.models.Background, {}),
(RATapi.models.Contrast, {}),
(RATapi.models.ContrastWithRatio, {}),
(RATapi.models.CustomFile, {}),
(RATapi.models.Data, {}),
(RATapi.models.DomainContrast, {}),
(RATapi.models.Layer, {"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"}),
(
RATapi.models.AbsorptionLayer,
{
"thickness": "Test Thickness",
"SLD_real": "Test SLD",
"SLD_imaginary": "Test SLD",
"roughness": "Test Roughness",
},
),
(RATapi.models.Parameter, {}),
(RATapi.models.Resolution, {}),
],
)
class TestModels:
def test_initialise_with_wrong_type(self, model: Callable, model_params: dict) -> None:
"""When initialising a model with the wrong type for the "name" field, we should raise a ValidationError."""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for {model.__name__}\nname\n Input should be a valid string",
):
model(name=1, **model_params)
def test_assignment_with_wrong_type(self, model: Callable, model_params: dict) -> None:
"""When assigning the "name" field of a model with the wrong type, we should raise a ValidationError."""
test_model = model(**model_params)
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for {model.__name__}\nname\n Input should be a valid string",
):
test_model.name = 1
def test_initialise_with_zero_length_name(self, model: Callable, model_params: dict) -> None:
"""When initialising a model with a zero length name, we should raise a ValidationError."""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for {model.__name__}\nname\n String should have at least 1 character",
):
model(name="", **model_params)
def test_initialise_with_extra_fields(self, model: Callable, model_params: dict) -> None:
"""When initialising a model with unspecified fields, we should raise a ValidationError."""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for {model.__name__}\nnew_field\n Extra inputs are not permitted",
):
model(new_field=1, **model_params)
def test_custom_file_path_is_absolute() -> None:
"""If we use provide a relative path to the custom file model, it should be converted to an absolute path."""
relative_path = pathlib.Path("./relative_path")
custom_file = RATapi.models.CustomFile(path=relative_path)
assert custom_file.path.is_absolute()
def test_data_eq() -> None:
"""If we use the Data.__eq__ method with an object that is not a pydantic BaseModel, we should return
"NotImplemented".
"""
assert RATapi.models.Data().__eq__("data") == NotImplemented
@pytest.mark.parametrize(
"input_data",
[
(np.array([[1.0, 1.0, 1.0]])),
],
)
def test_data_dimension(input_data: np.ndarray[float]) -> None:
"""The "data" field of the "Data" model should be a two-dimensional numpy array with at least three values in the
second dimension.
"""
test_data = RATapi.models.Data(data=input_data)
assert (test_data.data == input_data).all()
@pytest.mark.parametrize(
"input_data",
[
(np.array([])),
(np.array([1.0, 1.0])),
],
)
def test_data_too_few_dimensions(input_data: np.ndarray[float]) -> None:
"""If the "data" field of the "Data" model is not a two-dimensional numpy array we should raise a
ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match='1 validation error for Data\ndata\n Value error, "data" must have at least two dimensions',
):
RATapi.models.Data(data=input_data)
@pytest.mark.parametrize(
"input_data",
[
(np.array([[]])),
(np.array([[1.0]])),
(np.array([[1.0, 1.0]])),
],
)
def test_data_too_few_values(input_data: np.ndarray[float]) -> None:
"""If the second dimension of the array in the "data" field of the "Data" model has fewer than three values we
should raise a ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match='1 validation error for Data\ndata\n Value error, "data" must have at least three columns',
):
RATapi.models.Data(data=input_data)
@pytest.mark.parametrize(
"input_range",
[
([1.0, 2.0]),
],
)
def test_data_ranges(input_range: list[float]) -> None:
"""The "data_range" and "simulation_range" fields of the "Data" model should contain exactly two values."""
assert RATapi.models.Data(data_range=input_range).data_range == input_range
assert RATapi.models.Data(simulation_range=input_range).simulation_range == input_range
@pytest.mark.parametrize(
"input_range",
[
([]),
([1.0]),
([1.0, 2.0, 3.0]),
],
)
def test_two_values_in_data_range(input_range: list[float]) -> None:
"""If the "data_range" field of the "Data" model contains more or less than two values, we should raise a
ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Data\ndata_range\n List should have "
f"at {'least' if len(input_range) < 2 else 'most'} 2 items "
f"after validation, not {len(input_range)}",
):
RATapi.models.Data(data_range=input_range)
@pytest.mark.parametrize(
"input_range",
[
([]),
([1.0]),
([1.0, 2.0, 3.0]),
],
)
def test_two_values_in_simulation_range(input_range: list[float]) -> None:
"""If the "simulation_range" field of the "Data" model contains more or less than two values, we should raise a
ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Data\nsimulation_range\n List should "
f"have at {'least' if len(input_range) < 2 else 'most'} 2 items "
f"after validation, not {len(input_range)}",
):
RATapi.models.Data(simulation_range=input_range)
@pytest.mark.parametrize(
"field",
[
"data_range",
"simulation_range",
],
)
def test_min_max_in_range(field: str) -> None:
"""If the maximum value of the "data_range" or "simulation_range" fields of the "Data" model is greater than the
minimum value, we should raise a ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Data\n{field}\n Value error, {field} "
f'"min" value is greater than the "max" value',
):
RATapi.models.Data(**{field: [1.0, 0.0]})
def test_default_ranges() -> None:
"""If "data" is specified but either the "data_range" or "simulation_range" fields are not, we set the ranges to
the minimum and maximum values of the first column of the data.
"""
test_data = RATapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]]))
assert test_data.data_range == [1.0, 3.0]
assert test_data.simulation_range == [1.0, 3.0]
@pytest.mark.parametrize(
"test_range",
[
[0.0, 2.0],
[2.0, 4.0],
[0.0, 4.0],
],
)
def test_data_range(test_range) -> None:
"""If "data" is specified but the "data_range" lies outside of the limits of the data we should raise a
ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=re.escape(
f"1 validation error for Data\n Value error, The "
f"data_range value of: {test_range} must lie within "
f"the min/max values of the data: [1.0, 3.0]",
),
):
RATapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]]), data_range=test_range)
@pytest.mark.parametrize(
"test_range",
[
[0.0, 2.0],
[2.0, 4.0],
[1.5, 2.5],
],
)
def test_simulation_range(test_range) -> None:
"""If "data" is specified but the "simulation_range" lies within the limits of the data we should raise a
ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=re.escape(
f"1 validation error for Data\n Value error, The "
f"simulation_range value of: {test_range} must lie "
f"outside of the min/max values of the data: "
f"[1.0, 3.0]",
),
):
RATapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]]), simulation_range=test_range)
@pytest.mark.parametrize(
["minimum", "value", "maximum"],
[
(0.0, 2.0, 1.0),
(0, 1, 0),
(1, -1, 1),
],
)
def test_parameter_range(minimum: float, value: float, maximum: float) -> None:
"""For the "Parameter" model, if the value of the "value" field does not lie with the values given in the "min" and
"max" fields, we should raise a ValidationError.
"""
with pytest.raises(
pydantic.ValidationError,
match=f"1 validation error for Parameter\n Value error, value "
f"{float(value)} is not within the defined range: "
f"{float(minimum)} <= value <= {float(maximum)}",
):
RATapi.models.Parameter(min=minimum, value=value, max=maximum)
def test_layer_bad_imaginary_SLD():
"""If 'SLD_imaginary' is given to a Layer, it should raise a descriptive ValidationError."""
with pytest.raises(
pydantic.ValidationError,
match=(
"1 validation error for Layer\n"
" Value error, The Layer class does not support imaginary SLD."
" Use the AbsorptionLayer class instead."
),
):
RATapi.models.Layer(name="My Layer", SLD_imaginary="bad sld")
def test_contrast_bad_ratio():
"""If 'domain_ratios' is given to a Contrast, it should raise a descriptive ValidationError."""
with pytest.raises(
pydantic.ValidationError,
match=(
"1 validation error for Contrast\n"
" Value error, The Contrast class does not support domain ratios."
" Use the ContrastWithRatio class instead."
),
):
RATapi.models.Contrast(name="My Contrast", domain_ratio="bad ratio")
@pytest.mark.parametrize(
["model", "type", "values"],
[
(RATapi.models.Background, "function", ["val1", "val2", "val3", "val4", "val5"]),
(RATapi.models.Resolution, "constant", ["", "", "", "", ""]),
],
)
def test_type_change_clear(model, type, values):
"""If the type of a background or resolution is changed, it should wipe the other fields and warn the user."""
model_instance = model(
name="Test",
type=type,
source="src",
value_1=values[0],
value_2=values[1],
value_3=values[2],
value_4=values[3],
value_5=values[4],
)
with pytest.warns(UserWarning, match="Changing the type of Test clears its source and value fields."):
model_instance.type = "data"
for attr in ["source", "value_1", "value_2", "value_3", "value_4", "value_5"]:
assert getattr(model_instance, attr) == ""
@pytest.mark.parametrize(
["model", "signal_type", "values"],
[
(RATapi.models.Background, "constant", ["value_1", "value_2", "value_3", "value_4", "value_5"]),
(RATapi.models.Background, "data", ["value_2", "value_3", "value_4", "value_5"]),
(RATapi.models.Resolution, "constant", ["value_1", "value_2", "value_3", "value_4", "value_5"]),
(RATapi.models.Resolution, "data", ["value_1", "value_2", "value_3", "value_4", "value_5"]),
],
)
def test_unsupported_parameters_error(model, signal_type, values):
"""If a value is inputted for an unsupported field for a particular type of background or resolution then we should
raise an error."""
for value in values:
with pytest.raises(
pydantic.ValidationError,
match=(
f"1 validation error for {model.__name__}\n Value error, The following values are not supported"
f' by the "{signal_type}" {model.__name__} type: {value}'
),
):
model(**{"type": signal_type, value: "unsupported"})