SciFile-Core 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scifile_core/__init__.py +111 -0
- scifile_core/_content.py +490 -0
- scifile_core/_diagnostic.py +322 -0
- scifile_core/_exception.py +221 -0
- scifile_core/_io.py +705 -0
- scifile_core/_mapping.py +139 -0
- scifile_core/_model.py +1056 -0
- scifile_core/_number.py +41 -0
- scifile_core/_optional.py +40 -0
- scifile_core/py.typed +0 -0
- scifile_core/testing.py +653 -0
- scifile_core/wording.py +454 -0
- scifile_core-0.0.1.dist-info/METADATA +6 -0
- scifile_core-0.0.1.dist-info/RECORD +16 -0
- scifile_core-0.0.1.dist-info/WHEEL +5 -0
- scifile_core-0.0.1.dist-info/top_level.txt +1 -0
scifile_core/testing.py
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
"""A kit that tests a package against the SciFile contract.
|
|
2
|
+
|
|
3
|
+
A package calls these checks from its own tests, on its module and on its
|
|
4
|
+
sample files:
|
|
5
|
+
|
|
6
|
+
.. code-block:: python
|
|
7
|
+
|
|
8
|
+
import scifile_map
|
|
9
|
+
from scifile_core import testing
|
|
10
|
+
def test_contract() -> None:
|
|
11
|
+
testing.check_package(scifile_map)
|
|
12
|
+
def test_round_trip(sample: Path) -> None:
|
|
13
|
+
testing.check_round_trip(scifile_map, sample)
|
|
14
|
+
|
|
15
|
+
The checks test what the names of a package do, rather than how they are
|
|
16
|
+
built. Only what the contract prescribes as classes is tested as classes:
|
|
17
|
+
the hierarchy of the exceptions, `~scifile_core.Diagnostic`,
|
|
18
|
+
`~scifile_core.Diagnostics` and `~scifile_core.DiagnosticSeverity`,
|
|
19
|
+
``DiagnosticType`` as an enumeration, and the field types as frozen, slotted,
|
|
20
|
+
keyword-only dataclasses of `~scifile_core.FieldModel`. Each check raises
|
|
21
|
+
`AssertionError` with a message that names what the package breaks, and
|
|
22
|
+
works under any test runner.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import dataclasses
|
|
28
|
+
import enum
|
|
29
|
+
import pickle
|
|
30
|
+
import tempfile
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import TYPE_CHECKING, Any, NoReturn, SupportsBytes, cast
|
|
33
|
+
|
|
34
|
+
from scifile_core._content import arrays
|
|
35
|
+
from scifile_core._diagnostic import (
|
|
36
|
+
Diagnostic,
|
|
37
|
+
Diagnostics,
|
|
38
|
+
DiagnosticSeverity,
|
|
39
|
+
SharedDiagnosticType,
|
|
40
|
+
)
|
|
41
|
+
from scifile_core._exception import Error, InputError, ReadError
|
|
42
|
+
from scifile_core._model import (
|
|
43
|
+
FieldModel,
|
|
44
|
+
FileModel,
|
|
45
|
+
WriteConfig,
|
|
46
|
+
_option_names,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
if TYPE_CHECKING:
|
|
50
|
+
from collections.abc import Callable
|
|
51
|
+
from types import ModuleType
|
|
52
|
+
|
|
53
|
+
from _typeshed import DataclassInstance
|
|
54
|
+
from fileex.typing import FileLike
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
_VERBS = ("read", "create", "write")
|
|
58
|
+
"""Functions that every package exports."""
|
|
59
|
+
|
|
60
|
+
_EXPORTS = (
|
|
61
|
+
*_VERBS,
|
|
62
|
+
"File",
|
|
63
|
+
"WriteConfig",
|
|
64
|
+
"Error",
|
|
65
|
+
"InputError",
|
|
66
|
+
"ReadError",
|
|
67
|
+
"DiagnosticType",
|
|
68
|
+
"Diagnostic",
|
|
69
|
+
"Diagnostics",
|
|
70
|
+
"DiagnosticSeverity",
|
|
71
|
+
"__version__",
|
|
72
|
+
)
|
|
73
|
+
"""Names that the `__all__` of every package holds."""
|
|
74
|
+
|
|
75
|
+
_NO_FIELD_TYPES = frozenset({*_EXPORTS, "BinaryWriteConfig"})
|
|
76
|
+
"""Names of the contract that are no field types, though some are
|
|
77
|
+
dataclasses."""
|
|
78
|
+
|
|
79
|
+
_MODEL_MEMBERS = ("diagnostics", "write", "replace", "to_dict")
|
|
80
|
+
"""Members that the model of every package has."""
|
|
81
|
+
|
|
82
|
+
_UNKNOWN = "no_such_name"
|
|
83
|
+
"""A name that is neither a field nor a write option of any package."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def check_package(package: ModuleType) -> None:
|
|
87
|
+
"""Check that a package exports the names of the contract.
|
|
88
|
+
|
|
89
|
+
Parameters
|
|
90
|
+
----------
|
|
91
|
+
package
|
|
92
|
+
The package's module, such as ``scifile_map``.
|
|
93
|
+
|
|
94
|
+
Raises
|
|
95
|
+
------
|
|
96
|
+
AssertionError
|
|
97
|
+
If a name is missing or does not fit the contract, an exception does
|
|
98
|
+
not subclass those that the contract names, ``Diagnostic`` or
|
|
99
|
+
``Diagnostics`` is neither that of SciFile-Core nor a subclass of it,
|
|
100
|
+
``DiagnosticSeverity`` is not that of SciFile-Core, a member of
|
|
101
|
+
``DiagnosticType`` has the severity
|
|
102
|
+
`~scifile_core.DiagnosticSeverity.NONE`, an exported dataclass other
|
|
103
|
+
than those of the contract is no field type of the package, or
|
|
104
|
+
``read`` does not reject an input of no supported type with the
|
|
105
|
+
package's ``InputError``.
|
|
106
|
+
"""
|
|
107
|
+
exported = set(getattr(package, "__all__", None) or ())
|
|
108
|
+
lacking = sorted(set(_EXPORTS) - exported)
|
|
109
|
+
if lacking:
|
|
110
|
+
_fail(f"__all__ lacks {lacking}")
|
|
111
|
+
missing = sorted(name for name in exported if not hasattr(package, name))
|
|
112
|
+
if missing:
|
|
113
|
+
_fail(f"__all__ names {missing}, which do not exist")
|
|
114
|
+
if not isinstance(package.__version__, str):
|
|
115
|
+
_fail("__version__ is no string")
|
|
116
|
+
for verb in _VERBS:
|
|
117
|
+
if not callable(getattr(package, verb)):
|
|
118
|
+
_fail(f"{verb} is not callable")
|
|
119
|
+
_check_exceptions(package)
|
|
120
|
+
_check_diagnostic_types(package.DiagnosticType)
|
|
121
|
+
_check_diagnostic_classes(package)
|
|
122
|
+
if not isinstance(package.File, type):
|
|
123
|
+
_fail("File is no class")
|
|
124
|
+
absent = [
|
|
125
|
+
name for name in _MODEL_MEMBERS if not hasattr(package.File, name)
|
|
126
|
+
]
|
|
127
|
+
if absent:
|
|
128
|
+
_fail(f"File lacks the members {absent}")
|
|
129
|
+
_check_classes(package, exported)
|
|
130
|
+
_expect_raise(
|
|
131
|
+
package.InputError,
|
|
132
|
+
lambda: package.read(object()),
|
|
133
|
+
"read does not reject an input of no supported type with InputError",
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def check_model(model: FileModel) -> None:
|
|
138
|
+
"""Check that a model behaves as the contract requires.
|
|
139
|
+
|
|
140
|
+
Parameters
|
|
141
|
+
----------
|
|
142
|
+
model
|
|
143
|
+
A model of the package, such as one that ``read`` returned.
|
|
144
|
+
|
|
145
|
+
Raises
|
|
146
|
+
------
|
|
147
|
+
AssertionError
|
|
148
|
+
If the model or one of its arrays can be changed, it does not equal
|
|
149
|
+
a copy of itself, its hash disagrees with its equality, its
|
|
150
|
+
diagnostics do not behave as the contract requires, or a value of
|
|
151
|
+
its fields is a dataclass that does not behave as a
|
|
152
|
+
`~scifile_core.FieldModel`.
|
|
153
|
+
"""
|
|
154
|
+
_check_immutable(model)
|
|
155
|
+
for field, value in _field_values(model):
|
|
156
|
+
_check_field_value(field, value)
|
|
157
|
+
_check_copies(model)
|
|
158
|
+
_check_diagnostics(model)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def check_round_trip(package: ModuleType, file: FileLike) -> FileModel:
|
|
162
|
+
"""Check that a file reads back as written, through every write target.
|
|
163
|
+
|
|
164
|
+
The model that ``read`` returns is also checked with `check_model`, its
|
|
165
|
+
field types as `check_package` checks those that it exports, and with
|
|
166
|
+
the package's ``InputError`` for a name that is no field or option and
|
|
167
|
+
a target of no supported type.
|
|
168
|
+
|
|
169
|
+
Parameters
|
|
170
|
+
----------
|
|
171
|
+
package
|
|
172
|
+
The package's module, such as ``scifile_map``.
|
|
173
|
+
file
|
|
174
|
+
A sample file, as ``read`` takes it.
|
|
175
|
+
|
|
176
|
+
Returns
|
|
177
|
+
-------
|
|
178
|
+
The model that ``read`` returned.
|
|
179
|
+
|
|
180
|
+
Raises
|
|
181
|
+
------
|
|
182
|
+
AssertionError
|
|
183
|
+
If the written file reads as another model, writing is not
|
|
184
|
+
deterministic, a write target receives other output, a field type
|
|
185
|
+
of the model is not exported, or the model, its field types or the
|
|
186
|
+
exceptions do not behave as the contract requires.
|
|
187
|
+
"""
|
|
188
|
+
model: FileModel = package.read(file)
|
|
189
|
+
output = package.write(model)
|
|
190
|
+
binary = isinstance(output, bytes)
|
|
191
|
+
if not (binary or isinstance(output, str)):
|
|
192
|
+
_fail(f"write returns {type(output).__name__}")
|
|
193
|
+
again = (
|
|
194
|
+
package.read(output)
|
|
195
|
+
if binary
|
|
196
|
+
else package.read(output, path_can_be_str=False)
|
|
197
|
+
)
|
|
198
|
+
if not _equal(again, model):
|
|
199
|
+
_fail("the written file reads as another model")
|
|
200
|
+
if package.write(again) != output:
|
|
201
|
+
_fail("writing again gives another file")
|
|
202
|
+
_check_targets(package, model, output)
|
|
203
|
+
check_model(model)
|
|
204
|
+
_check_field_classes(package, model)
|
|
205
|
+
_check_raised(package, model)
|
|
206
|
+
return model
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _check_immutable(model: FileModel | FieldModel) -> None:
|
|
210
|
+
"""Check that no field and no array of a model or field type can change.
|
|
211
|
+
|
|
212
|
+
A field of a field type is named with its class.
|
|
213
|
+
"""
|
|
214
|
+
fields = model.to_dict()
|
|
215
|
+
if not fields:
|
|
216
|
+
_fail(f"{type(model).__name__} has no fields")
|
|
217
|
+
of = "" if isinstance(model, FileModel) else f" of {type(model).__name__}"
|
|
218
|
+
for name, value in fields.items():
|
|
219
|
+
try:
|
|
220
|
+
setattr(model, name, value)
|
|
221
|
+
except AttributeError:
|
|
222
|
+
pass
|
|
223
|
+
else:
|
|
224
|
+
_fail(f"the field {name}{of} can be set")
|
|
225
|
+
if any(array.flags.writeable for array in arrays(value)):
|
|
226
|
+
_fail(f"an array of the field {name}{of} can be changed")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _check_copies(model: FileModel) -> None:
|
|
230
|
+
"""Check that the copies of a model equal it, and have its diagnostics.
|
|
231
|
+
|
|
232
|
+
A copy hashes as the model does, and that of `replace` without changes
|
|
233
|
+
and of pickle has the same diagnostics.
|
|
234
|
+
"""
|
|
235
|
+
_check_rebuilt(model, "the model")
|
|
236
|
+
replaced = model.replace()
|
|
237
|
+
if not _equal(replaced, model):
|
|
238
|
+
_fail("replace() without changes differs")
|
|
239
|
+
if replaced.diagnostics != model.diagnostics:
|
|
240
|
+
_fail("replace() changes the diagnostics")
|
|
241
|
+
_check_unknown_name(model, "the model")
|
|
242
|
+
unpickled = pickle.loads(pickle.dumps(model)) # noqa: S301 - its own output
|
|
243
|
+
if not _equal(unpickled, model) or _hash(unpickled) != _hash(model):
|
|
244
|
+
_fail("the model differs after pickling")
|
|
245
|
+
if unpickled.diagnostics != model.diagnostics:
|
|
246
|
+
_fail("pickling changes the diagnostics")
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _check_rebuilt(value: FileModel | FieldModel, subject: str) -> None:
|
|
250
|
+
"""Check that a copy built from `to_dict` equals a value, and its hash."""
|
|
251
|
+
constructor: Callable[..., FileModel | FieldModel] = type(value)
|
|
252
|
+
try:
|
|
253
|
+
rebuilt = constructor(**value.to_dict())
|
|
254
|
+
except InputError as error:
|
|
255
|
+
_fail(f"{subject} does not take back what to_dict gives: {error}")
|
|
256
|
+
if not _equal(rebuilt, value):
|
|
257
|
+
_fail(f"{subject} differs from a copy built from to_dict")
|
|
258
|
+
if _hash(rebuilt) != _hash(value):
|
|
259
|
+
_fail(f"a copy of {subject} has another hash")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _check_unknown_name(value: FileModel | FieldModel, subject: str) -> None:
|
|
263
|
+
"""Check that `replace` rejects a name that is no field."""
|
|
264
|
+
_expect_raise(
|
|
265
|
+
InputError,
|
|
266
|
+
lambda: value.replace(**{_UNKNOWN: None}),
|
|
267
|
+
f"replace of {subject} accepts a name that is no field",
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _field_values(model: FileModel) -> list[tuple[str, object]]:
|
|
272
|
+
"""Return the dataclasses that the fields of a model hold, each once.
|
|
273
|
+
|
|
274
|
+
Tuples and the fields of field types are searched as well, so that a
|
|
275
|
+
field type inside another one is found. Each value comes with the field
|
|
276
|
+
of the model that holds it first.
|
|
277
|
+
"""
|
|
278
|
+
found: dict[int, tuple[str, object]] = {}
|
|
279
|
+
|
|
280
|
+
def search(field: str, value: object) -> None:
|
|
281
|
+
if isinstance(value, tuple):
|
|
282
|
+
for item in value:
|
|
283
|
+
search(field, item)
|
|
284
|
+
elif (
|
|
285
|
+
dataclasses.is_dataclass(value)
|
|
286
|
+
and not isinstance(value, type)
|
|
287
|
+
and id(value) not in found
|
|
288
|
+
):
|
|
289
|
+
found[id(value)] = (field, value)
|
|
290
|
+
if isinstance(value, FieldModel):
|
|
291
|
+
for item in value.to_dict().values():
|
|
292
|
+
search(field, item)
|
|
293
|
+
|
|
294
|
+
for field, value in model.to_dict().items():
|
|
295
|
+
search(field, value)
|
|
296
|
+
return list(found.values())
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _check_field_value(field: str, value: object) -> None:
|
|
300
|
+
"""Check a value of a field type, as `check_model` checks a model."""
|
|
301
|
+
name = type(value).__name__
|
|
302
|
+
if not isinstance(value, FieldModel):
|
|
303
|
+
_fail(
|
|
304
|
+
f"the field {field} holds {name}, a dataclass that is no FieldModel"
|
|
305
|
+
)
|
|
306
|
+
_check_immutable(value)
|
|
307
|
+
_check_rebuilt(value, name)
|
|
308
|
+
_check_unknown_name(value, name)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _check_field_classes(package: ModuleType, model: FileModel) -> None:
|
|
312
|
+
"""Check that the field types of a model are those of its package."""
|
|
313
|
+
exported = [
|
|
314
|
+
getattr(package, name, None)
|
|
315
|
+
for name in getattr(package, "__all__", None) or ()
|
|
316
|
+
]
|
|
317
|
+
for field, value in _field_values(model):
|
|
318
|
+
cls = type(value)
|
|
319
|
+
if not any(cls is item for item in exported):
|
|
320
|
+
_fail(
|
|
321
|
+
f"the field {field} holds {cls.__name__}, a field type that"
|
|
322
|
+
" the package does not export"
|
|
323
|
+
)
|
|
324
|
+
_check_field_type(package, cls)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _check_classes(package: ModuleType, exported: set[str]) -> None:
|
|
328
|
+
"""Check the write options and the field types that a package exports."""
|
|
329
|
+
_check_writer(package.WriteConfig, "WriteConfig")
|
|
330
|
+
if "BinaryWriteConfig" in exported:
|
|
331
|
+
_check_writer(package.BinaryWriteConfig, "BinaryWriteConfig")
|
|
332
|
+
for name in sorted(exported - _NO_FIELD_TYPES):
|
|
333
|
+
_check_field_type(package, getattr(package, name))
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _check_field_type(package: ModuleType, cls: object) -> None:
|
|
337
|
+
"""Check that an exported class, if a dataclass, is a field type.
|
|
338
|
+
|
|
339
|
+
A field type subclasses `FieldModel` as a frozen, slotted, keyword-only
|
|
340
|
+
dataclass, keeps its validation, equality and hash, and raises the
|
|
341
|
+
package's `InputError`. A model or write options under another name
|
|
342
|
+
than those of the contract fail as well; any other export is left
|
|
343
|
+
alone.
|
|
344
|
+
"""
|
|
345
|
+
if not isinstance(cls, type):
|
|
346
|
+
return
|
|
347
|
+
name = cls.__name__
|
|
348
|
+
if issubclass(cls, FileModel):
|
|
349
|
+
_fail(
|
|
350
|
+
f"{name} is a model, which a package exports only as File; the"
|
|
351
|
+
" type of a field is a FieldModel"
|
|
352
|
+
)
|
|
353
|
+
if issubclass(cls, WriteConfig):
|
|
354
|
+
_fail(
|
|
355
|
+
f"{name} is write options, which a package exports only as"
|
|
356
|
+
" WriteConfig or BinaryWriteConfig"
|
|
357
|
+
)
|
|
358
|
+
if not dataclasses.is_dataclass(cls):
|
|
359
|
+
if issubclass(cls, FieldModel):
|
|
360
|
+
_fail(f"{name} is a FieldModel, but no dataclass")
|
|
361
|
+
return
|
|
362
|
+
if not issubclass(cls, FieldModel):
|
|
363
|
+
_fail(
|
|
364
|
+
f"{name} is a dataclass, but no FieldModel; a field type"
|
|
365
|
+
" subclasses scifile_core.FieldModel with eq=False"
|
|
366
|
+
)
|
|
367
|
+
_check_declaration(package, cls)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _check_declaration(package: ModuleType, cls: type[FieldModel]) -> None:
|
|
371
|
+
"""Check how a field type is declared, and the error that it raises."""
|
|
372
|
+
name = cls.__name__
|
|
373
|
+
kept = (
|
|
374
|
+
cls.__eq__ is FieldModel.__eq__ and cls.__hash__ is FieldModel.__hash__
|
|
375
|
+
)
|
|
376
|
+
if not kept:
|
|
377
|
+
_fail(
|
|
378
|
+
f"{name} does not keep the equality and the hash of FieldModel;"
|
|
379
|
+
" declare it with eq=False, and define no __eq__ or __hash__"
|
|
380
|
+
)
|
|
381
|
+
if cls.__post_init__ is not FieldModel.__post_init__:
|
|
382
|
+
_fail(
|
|
383
|
+
f"{name} defines its own __post_init__, which skips the"
|
|
384
|
+
" validation and the frozen arrays of FieldModel; validate in"
|
|
385
|
+
" _validate, and define no __post_init__"
|
|
386
|
+
)
|
|
387
|
+
if not cast("Any", cls).__dataclass_params__.frozen:
|
|
388
|
+
_fail(f"{name} is not frozen")
|
|
389
|
+
if cls.__dictoffset__:
|
|
390
|
+
_fail(f"{name} is not slotted")
|
|
391
|
+
positional = [
|
|
392
|
+
field.name
|
|
393
|
+
for field in dataclasses.fields(cast("type[DataclassInstance]", cls))
|
|
394
|
+
if field.init and not field.kw_only
|
|
395
|
+
]
|
|
396
|
+
if positional:
|
|
397
|
+
_fail(f"{name} takes the fields {positional} by position")
|
|
398
|
+
error: object = cls._input_error
|
|
399
|
+
if not isinstance(error, type):
|
|
400
|
+
_fail(
|
|
401
|
+
f"{name} has {error!r} as _input_error, which is no exception class"
|
|
402
|
+
)
|
|
403
|
+
if not issubclass(error, package.InputError):
|
|
404
|
+
_fail(
|
|
405
|
+
f"{name} raises {_qualified(error)}, not the package's InputError"
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _check_diagnostics(model: FileModel) -> None:
|
|
410
|
+
"""Check the diagnostics of a model, and those that `replace` keeps.
|
|
411
|
+
|
|
412
|
+
A diagnostic of the parser stays on a copy whose change of one field,
|
|
413
|
+
to its own value, does not touch it, as ``_fields_of`` says.
|
|
414
|
+
"""
|
|
415
|
+
diagnostics = model.diagnostics
|
|
416
|
+
if not isinstance(diagnostics, Diagnostics) or not all(
|
|
417
|
+
isinstance(diagnostic, Diagnostic) for diagnostic in diagnostics
|
|
418
|
+
):
|
|
419
|
+
_fail("diagnostics is no Diagnostics of Diagnostic")
|
|
420
|
+
if model.diagnostics is not diagnostics:
|
|
421
|
+
_fail("diagnostics is computed again on a second access")
|
|
422
|
+
parsed = _parsed(model)
|
|
423
|
+
if diagnostics[: len(parsed)] != parsed:
|
|
424
|
+
_fail("diagnostics does not start with those of the parser")
|
|
425
|
+
highest = max(
|
|
426
|
+
(diagnostic.severity for diagnostic in diagnostics),
|
|
427
|
+
default=DiagnosticSeverity.NONE,
|
|
428
|
+
)
|
|
429
|
+
if diagnostics.max_severity != highest:
|
|
430
|
+
_fail("max_severity is wrong")
|
|
431
|
+
_check_field_keys(model)
|
|
432
|
+
fields_of = model._fields_of # noqa: SLF001 - a hook between core and a package
|
|
433
|
+
for name, value in model.to_dict().items():
|
|
434
|
+
expected = tuple(
|
|
435
|
+
diagnostic
|
|
436
|
+
for diagnostic in parsed
|
|
437
|
+
if (fields := fields_of(diagnostic)) is None or name not in fields
|
|
438
|
+
)
|
|
439
|
+
if _parsed(model.replace(**{name: value})) != expected:
|
|
440
|
+
_fail(
|
|
441
|
+
f"replace of the field {name} keeps other diagnostics of the"
|
|
442
|
+
" parser than those that _fields_of says it does not touch"
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _check_field_keys(model: FileModel) -> None:
|
|
447
|
+
"""Check that ``_field_keys`` names fields of a model."""
|
|
448
|
+
fields = set(model.to_dict())
|
|
449
|
+
keys = type(model)._field_keys # noqa: SLF001 - a hook between core and a package
|
|
450
|
+
for key, names in keys.items():
|
|
451
|
+
unknown = sorted(set(names) - fields)
|
|
452
|
+
if unknown:
|
|
453
|
+
_fail(
|
|
454
|
+
f"_field_keys maps {key!r} to {unknown}, which are no fields"
|
|
455
|
+
" of the model"
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _parsed(model: FileModel) -> tuple[Diagnostic, ...]:
|
|
460
|
+
"""Return the diagnostics of the parser of a model."""
|
|
461
|
+
return model._parsed # noqa: SLF001 - a hook between core and a package
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _check_targets(
|
|
465
|
+
package: ModuleType, model: FileModel, output: str | bytes
|
|
466
|
+
) -> None:
|
|
467
|
+
"""Check that every target of `write` receives the same output."""
|
|
468
|
+
binary = isinstance(output, bytes)
|
|
469
|
+
chunks: list[Any] = []
|
|
470
|
+
if package.write(model, chunks.append) is not None:
|
|
471
|
+
_fail("write to a callable returns something")
|
|
472
|
+
if not all(chunks):
|
|
473
|
+
_fail("write gives an empty chunk to a callable")
|
|
474
|
+
joined = b"".join(chunks) if binary else "".join(chunks)
|
|
475
|
+
if joined != output:
|
|
476
|
+
_fail("the chunks of a callable differ from the output")
|
|
477
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
478
|
+
path = Path(directory) / "file"
|
|
479
|
+
if package.write(model, path) is not None:
|
|
480
|
+
_fail("write to a path returns something")
|
|
481
|
+
expected = output if isinstance(output, bytes) else output.encode()
|
|
482
|
+
if path.read_bytes() != expected:
|
|
483
|
+
_fail("the file of a path differs from the output")
|
|
484
|
+
if not _equal(package.read(path), model):
|
|
485
|
+
_fail("the written path reads differently")
|
|
486
|
+
plain = bytes(cast("SupportsBytes", model)) if binary else str(model)
|
|
487
|
+
if plain != output:
|
|
488
|
+
_fail("bytes() or str() differs from write()")
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _check_exceptions(package: ModuleType) -> None:
|
|
492
|
+
"""Check that the exceptions of a package subclass those of the contract."""
|
|
493
|
+
error = package.Error
|
|
494
|
+
hierarchy = (
|
|
495
|
+
("Error", error, (Error,)),
|
|
496
|
+
("InputError", package.InputError, (error, InputError)),
|
|
497
|
+
("ReadError", package.ReadError, (error, ReadError)),
|
|
498
|
+
)
|
|
499
|
+
for name, cls, bases in hierarchy:
|
|
500
|
+
if cls is bases[-1]:
|
|
501
|
+
_fail(f"{name} is that of scifile_core, not the package's own")
|
|
502
|
+
for base in bases:
|
|
503
|
+
if not _subclasses(cls, base):
|
|
504
|
+
_fail(f"{name} does not subclass {_qualified(base)}")
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _check_diagnostic_classes(package: ModuleType) -> None:
|
|
508
|
+
"""Check that the classes of diagnostics are those of SciFile-Core."""
|
|
509
|
+
if not _subclasses(package.Diagnostic, Diagnostic):
|
|
510
|
+
_fail("Diagnostic is neither that of scifile_core nor a subclass")
|
|
511
|
+
if not _subclasses(package.Diagnostics, Diagnostics):
|
|
512
|
+
_fail("Diagnostics is neither that of scifile_core nor a subclass")
|
|
513
|
+
if package.DiagnosticSeverity is not DiagnosticSeverity:
|
|
514
|
+
_fail("DiagnosticSeverity is not that of scifile_core")
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _check_diagnostic_types(diagnostic_types: object) -> None:
|
|
518
|
+
"""Check a package's diagnostic types against the shared vocabulary.
|
|
519
|
+
|
|
520
|
+
A member that has the name or the label of a shared type repeats its
|
|
521
|
+
name, label and severity; a diagnostic of another severity gives it.
|
|
522
|
+
"""
|
|
523
|
+
if not _subclasses(diagnostic_types, enum.Enum):
|
|
524
|
+
_fail("DiagnosticType is no enumeration")
|
|
525
|
+
members: list[Any] = list(cast("type[enum.Enum]", diagnostic_types))
|
|
526
|
+
if not members:
|
|
527
|
+
_fail("DiagnosticType has no members")
|
|
528
|
+
for member in members:
|
|
529
|
+
if not (
|
|
530
|
+
isinstance(getattr(member, "label", None), str)
|
|
531
|
+
and isinstance(
|
|
532
|
+
getattr(member, "severity", None), DiagnosticSeverity
|
|
533
|
+
)
|
|
534
|
+
):
|
|
535
|
+
_fail(f"DiagnosticType.{member.name} has no label and severity")
|
|
536
|
+
if member.severity is DiagnosticSeverity.NONE:
|
|
537
|
+
_fail(
|
|
538
|
+
f"DiagnosticType.{member.name} has the severity NONE, which no"
|
|
539
|
+
" diagnostic has"
|
|
540
|
+
)
|
|
541
|
+
labels = [member.label for member in members]
|
|
542
|
+
repeated = sorted({label for label in labels if labels.count(label) > 1})
|
|
543
|
+
if repeated:
|
|
544
|
+
_fail(f"DiagnosticType repeats the labels {repeated}")
|
|
545
|
+
by_label = {member.label: member for member in SharedDiagnosticType}
|
|
546
|
+
by_name = {member.name: member for member in SharedDiagnosticType}
|
|
547
|
+
for member in members:
|
|
548
|
+
common = by_name.get(member.name) or by_label.get(member.label)
|
|
549
|
+
if common is not None and (
|
|
550
|
+
(member.name, member.label, member.severity)
|
|
551
|
+
!= (common.name, common.label, common.severity)
|
|
552
|
+
):
|
|
553
|
+
_fail(
|
|
554
|
+
f"DiagnosticType.{member.name} differs from"
|
|
555
|
+
f" SharedDiagnosticType.{common.name} in its name, label or"
|
|
556
|
+
" severity; a diagnostic of another severity gives it"
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _check_writer(writer: object, name: str) -> None:
|
|
561
|
+
"""Check that write options build with their defaults alone."""
|
|
562
|
+
if not callable(writer):
|
|
563
|
+
_fail(f"{name} is no class")
|
|
564
|
+
try:
|
|
565
|
+
options = writer()
|
|
566
|
+
except TypeError:
|
|
567
|
+
_fail(f"{name} does not build without arguments")
|
|
568
|
+
try:
|
|
569
|
+
list(_option_names(options))
|
|
570
|
+
except TypeError:
|
|
571
|
+
_fail(f"{name} is no dataclass, and has no replace and FIELD_NAMES")
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _check_raised(package: ModuleType, model: FileModel) -> None:
|
|
575
|
+
"""Check that a model and its package raise the package's `InputError`."""
|
|
576
|
+
_expect_raise(
|
|
577
|
+
package.InputError,
|
|
578
|
+
lambda: model.replace(**{_UNKNOWN: None}),
|
|
579
|
+
"replace does not raise the package's InputError",
|
|
580
|
+
)
|
|
581
|
+
_expect_raise(
|
|
582
|
+
package.InputError,
|
|
583
|
+
lambda: package.write(model, **{_UNKNOWN: None}),
|
|
584
|
+
"write does not reject an unknown option with InputError",
|
|
585
|
+
)
|
|
586
|
+
_expect_raise(
|
|
587
|
+
package.InputError,
|
|
588
|
+
lambda: package.write(model, 42),
|
|
589
|
+
"write does not reject a target of no supported type with InputError",
|
|
590
|
+
)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _expect_raise(
|
|
594
|
+
exception: type[BaseException], call: Callable[[], object], message: str
|
|
595
|
+
) -> None:
|
|
596
|
+
"""Fail with a message unless a call raises an exception.
|
|
597
|
+
|
|
598
|
+
Another exception of the SciFile packages fails with the message too;
|
|
599
|
+
any other propagates, and fails the test with its own message.
|
|
600
|
+
"""
|
|
601
|
+
try:
|
|
602
|
+
call()
|
|
603
|
+
except exception:
|
|
604
|
+
return
|
|
605
|
+
except Error as error:
|
|
606
|
+
_fail(f"{message}, but {_qualified(type(error))}: {error}")
|
|
607
|
+
_fail(message)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _equal(left: object, right: object) -> bool:
|
|
611
|
+
"""Return whether two models or field values are equal.
|
|
612
|
+
|
|
613
|
+
Values that cannot compare fail.
|
|
614
|
+
"""
|
|
615
|
+
try:
|
|
616
|
+
return bool(left == right)
|
|
617
|
+
except (TypeError, ValueError) as error:
|
|
618
|
+
_fail(_uncomparable(left, error))
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _hash(model: object) -> int:
|
|
622
|
+
"""Return the hash of a model or field value, or fail if it has none."""
|
|
623
|
+
try:
|
|
624
|
+
return hash(model)
|
|
625
|
+
except (TypeError, ValueError) as error:
|
|
626
|
+
_fail(_uncomparable(model, error))
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _uncomparable(model: object, error: Exception) -> str:
|
|
630
|
+
"""Return the message of a model or field value that cannot compare."""
|
|
631
|
+
message = (
|
|
632
|
+
f"comparing or hashing {type(model).__name__} raises"
|
|
633
|
+
f" {type(error).__name__}: {error}"
|
|
634
|
+
)
|
|
635
|
+
if type(model).__eq__ not in (FileModel.__eq__, FieldModel.__eq__):
|
|
636
|
+
message += f"; {type(model).__name__} defines its own __eq__, so"
|
|
637
|
+
message += " declare the dataclass with eq=False"
|
|
638
|
+
return message
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _subclasses(cls: object, base: type) -> bool:
|
|
642
|
+
"""Return whether something is a class that subclasses another."""
|
|
643
|
+
return isinstance(cls, type) and issubclass(cls, base)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def _qualified(cls: type) -> str:
|
|
647
|
+
"""Return the name of a class with its package."""
|
|
648
|
+
return f"{cls.__module__.split('.')[0]}.{cls.__name__}"
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _fail(message: str) -> NoReturn:
|
|
652
|
+
"""Raise `AssertionError` with a message."""
|
|
653
|
+
raise AssertionError(message)
|