forked from JPEWdev/shacl2code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_python.py
More file actions
2911 lines (2461 loc) · 88.5 KB
/
Copy pathtest_python.py
File metadata and controls
2911 lines (2461 loc) · 88.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
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) 2024 Joshua Watt
#
# SPDX-License-Identifier: MIT
import hashlib
import importlib
import json
import os
import re
import subprocess
import sys
import textwrap
from datetime import datetime, timedelta, timezone
from pathlib import Path
import jsonschema
import pyshacl
import pytest
import rdflib
from testfixtures import jsonvalidation, timetests
THIS_FILE = Path(__file__)
THIS_DIR = THIS_FILE.parent
TOP_DIR = THIS_DIR.parent
DATA_DIR = THIS_DIR / "data"
TEST_MODEL = THIS_DIR / "data" / "model" / "test.ttl"
TEST_CONTEXT = THIS_DIR / "data" / "model" / "test-context.json"
SPDX3_CONTEXT_URL = "https://spdx.github.io/spdx-3-model/context.json"
TEST_TZ = timezone(timedelta(hours=-2), name="TST")
MODEL_VERSION = "1.0.0.alpha"
VALIDATION_ERROR = object()
ENCODE_ERROR = object()
def shacl2code_generate(args, python_args, outfile):
p = subprocess.run(
[
"shacl2code",
"generate",
]
+ args
+ ["python"]
+ python_args
+ [
"--output",
outfile,
],
check=True,
stdout=subprocess.PIPE,
encoding="utf-8",
)
# Add a py.typed file for type checking
(outfile / "py.typed").touch()
return p
@pytest.fixture(scope="module")
def python_model(tmp_path_factory, test_context_url):
tmp_directory = tmp_path_factory.mktemp("pythontestcontext")
module_name = "pymodel"
output_dir = tmp_directory / module_name
shacl2code_generate(
[
"--input",
TEST_MODEL,
"--context",
test_context_url,
"--jss-signature",
"signatures",
],
[
"--version",
MODEL_VERSION,
],
output_dir,
)
yield tmp_directory, module_name
def _env_with_pythonpath(*paths: Path) -> "dict[str, str]":
"""A copy of the current environment with `paths` appended to PYTHONPATH."""
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(
env.get("PYTHONPATH", "").split(os.pathsep) + [str(p) for p in paths]
)
return env
@pytest.fixture
def python_model_env(python_model):
module_path, module_name = python_model
env = _env_with_pythonpath(module_path)
return env, module_name
@pytest.fixture(scope="module")
def model_script(tmp_path_factory, python_model):
tmp_directory = tmp_path_factory.mktemp("pythonmodelscript")
module_path, module_name = python_model
script = tmp_directory / "script.py"
script.write_text(textwrap.dedent(f"""\
#! /usr/bin/env python3
import sys
sys.path.append("{module_path}")
import {module_name}
sys.exit({module_name}.main())
"""))
script.chmod(0o755)
yield script
@pytest.fixture(scope="function")
def model(python_model):
module_path, module_name = python_model
old_path = sys.path[:]
sys.path.append(str(module_path))
try:
# Reload all model modules
for m in list(sys.modules):
if m == module_name or m.startswith(module_name + "."):
importlib.reload(sys.modules[m])
yield importlib.import_module(module_name)
finally:
sys.path = old_path
MODEL_TESTS = (
"args,python_args",
[
pytest.param(
["--input", TEST_MODEL],
[],
id="Model",
),
pytest.param(
["--input", TEST_MODEL, "--context-url", TEST_CONTEXT, SPDX3_CONTEXT_URL],
[],
id="Context URL",
),
pytest.param(
["--input", TEST_MODEL],
["--include-main=no"],
id="No main",
),
pytest.param(["--input", TEST_MODEL], ["--version=1.0.0"], id="Version"),
pytest.param(
["--input", TEST_MODEL, "--jss-signature", "signatures"],
[],
id="JSS Signature",
),
],
)
@pytest.mark.parametrize(*MODEL_TESTS)
class TestOutput:
"""
Test syntax and formatting of the output file
"""
def test_output_syntax(self, model_script, args, python_args):
"""
Checks that the output file is valid python syntax by executing it"
"""
subprocess.run([model_script, "--help"], check=True)
def test_trailing_whitespace(self, tmp_path, args, python_args):
"""
Tests that the generated file does not have trailing whitespace
"""
output_dir = tmp_path / "output"
shacl2code_generate(args, python_args, output_dir)
for p in output_dir.iterdir():
for num, line in enumerate(p.read_text().splitlines()):
assert (
re.search(r"\s+$", line) is None
), f"{p}: Line {num + 1} has trailing whitespace"
def test_tabs(self, tmp_path, args, python_args):
"""
Tests that the output file doesn't contain tabs
"""
output_dir = tmp_path / "output"
shacl2code_generate(args, python_args, output_dir)
for p in output_dir.iterdir():
for num, line in enumerate(p.read_text().splitlines()):
assert "\t" not in line, f"{p}: Line {num + 1} has tabs"
@pytest.mark.parametrize(*MODEL_TESTS)
class TestCheckType:
"""
Static type checking tests for the generated Python code
"""
def test_mypy(self, tmp_path, args, python_args):
"""
Mypy static type checking
"""
output_dir = tmp_path / "pymodel"
shacl2code_generate(args, python_args, output_dir)
subprocess.run(
["mypy", output_dir],
encoding="utf-8",
check=True,
)
# Run again on just the .py files
subprocess.run(
["mypy"] + [f for f in output_dir.iterdir() if f.suffix == ".py"],
encoding="utf-8",
check=True,
)
def test_stubtest(self, tmp_path, args, python_args):
"""
Mypy stub checks to ensure pyi stubs are in sync with py code
"""
output_dir = tmp_path / "pymodel"
shacl2code_generate(args, python_args, output_dir)
pythonpath = os.environ.get("PYTHONPATH")
if pythonpath:
pythonpath = os.pathsep.join(str(tmp_path), pythonpath)
else:
pythonpath = str(tmp_path)
env = os.environ.copy()
env["PYTHONPATH"] = pythonpath
subprocess.run(
[
"stubtest",
"pymodel",
"--allow",
DATA_DIR / "stubtest" / "allow.txt",
"--ignore-unused-allowlist",
"--ignore-missing-stub",
],
encoding="utf-8",
check=True,
env=env,
)
def test_pyrefly(self, tmp_path, args, python_args):
"""
Pyrefly static type checking
"""
output_dir = tmp_path / "pymodel"
shacl2code_generate(args, python_args, output_dir)
subprocess.run(
["pyrefly", "check", "--search-path", tmp_path]
+ list(output_dir.iterdir()),
encoding="utf-8",
check=True,
)
def test_pyright(self, tmp_path, args, python_args):
"""
Pyright static type checking
"""
output_dir = tmp_path / "pymodel"
shacl2code_generate(args, python_args, output_dir)
subprocess.run(
["pyright"] + list(output_dir.iterdir()),
encoding="utf-8",
check=True,
)
def test_flake8(self, tmp_path, args, python_args):
"""
Flake8 linting
"""
output_dir = tmp_path / "pymodel"
shacl2code_generate(args, python_args, output_dir)
subprocess.run(
["flake8", "--config", TOP_DIR / ".flake8"] + list(output_dir.iterdir()),
encoding="utf-8",
check=True,
)
def test_bandit(self, tmp_path, args, python_args):
"""
Bandit security linting
"""
output_dir = tmp_path / "pymodel"
shacl2code_generate(args, python_args, output_dir)
subprocess.run(
["bandit", "-r", output_dir],
encoding="utf-8",
check=True,
)
@pytest.fixture
def python_usage_script(python_model_env, tmp_path):
env, module_name = python_model_env
script_path = tmp_path / "script.py"
script_path.write_text(textwrap.dedent(f"""
#! /usr/bin/env python3
from typing import ClassVar, Iterable, List, Union
import {module_name}
print({module_name}.enumType.foo)
class OERecipeExtension({module_name}.extensible_abstract_class):
TYPE: ClassVar[str] = "http://example.org/shacl2code-test/recipe-extension"
NODE_KIND: ClassVar[{module_name}.NodeKind] = {module_name}.NodeKind.BlankNodeOrIRI
PROPERTIES: ClassVar[List[{module_name}.ClassProp]] = [
{module_name}.ClassProp(
"is_native",
lambda: {module_name}.BooleanProp(),
iri="http://example.org/shacl2code-test/is-native",
max_count=1,
),
]
def test1(o: {module_name}.link_class) -> int:
return len(o.link_class_link_list_prop)
def test2(o: {module_name}.link_class) -> Iterable[Union[{module_name}.link_class, str]]:
yield from o.link_class_link_list_prop
def test3(a: {module_name}.link_class, b: {module_name}.link_class) -> bool:
return a in b.link_class_link_list_prop
def test4(lst: Iterable[{module_name}.SHACLObject]) -> List[{module_name}.SHACLObject]:
return sorted(lst)
"""))
# Validate the script runs
subprocess.run([sys.executable, script_path], env=env, check=True)
yield env, script_path
class TestUsageType:
def test_mypy(self, python_usage_script):
env, script_path = python_usage_script
subprocess.run(
["mypy", script_path],
encoding="utf-8",
env=env,
check=True,
)
def test_pyright(self, python_usage_script):
env, script_path = python_usage_script
subprocess.run(
["pyright", script_path],
encoding="utf-8",
env=env,
check=True,
)
def test_pyrefly(self, python_usage_script):
env, script_path = python_usage_script
subprocess.run(
["pyrefly", "check", script_path],
encoding="utf-8",
env=env,
check=True,
)
def check_file(p, expect, digest):
sha1 = hashlib.sha1()
with p.open("rb") as f:
while True:
d = f.read(4096)
if not d:
break
sha1.update(d)
assert sha1.hexdigest() == digest
with p.open("r") as f:
data = json.load(f)
assert data == expect
def test_roundtrip(model, tmp_path, roundtrip):
doc = model.SHACLObjectSet()
with roundtrip.open("r") as f:
d = model.JSONLDDeserializer()
d.read(f, doc)
with roundtrip.open("r") as f:
expect_data = json.load(f)
outfile = tmp_path / "out.json"
with outfile.open("wb") as f:
s = model.JSONLDSerializer()
digest = s.write(doc, f, indent=4)
check_file(outfile, expect_data, digest)
with outfile.open("wb") as f:
s = model.JSONLDInlineSerializer()
digest = s.write(doc, f)
check_file(outfile, expect_data, digest)
def test_script_roundtrip(model_script, tmp_path, roundtrip):
outpath = tmp_path / "out.json"
subprocess.run(
[model_script, roundtrip, "--outfile", outpath],
check=True,
)
with roundtrip.open("r") as f:
expect_data = json.load(f)
with outpath.open("r") as f:
data = json.load(f)
assert data == expect_data
def test_module_roundtrip(python_model_env, tmp_path, roundtrip):
env, module_name = python_model_env
outpath = tmp_path / "out.json"
subprocess.run(
[sys.executable, "-m", module_name, roundtrip, "--outfile", outpath],
check=True,
env=env,
)
with roundtrip.open("r") as f:
expect_data = json.load(f)
with outpath.open("r") as f:
data = json.load(f)
assert data == expect_data
def test_from_rdf_roundtrip(model, tmp_path, roundtrip):
with roundtrip.open("r") as f:
expect_data = json.load(f)
# Parse data using RDF
g = rdflib.Graph()
g.parse(roundtrip)
# Convert to SHACL objects
objset = model.SHACLObjectSet()
model.RDFDeserializer().read(g, objset)
# Copy context from expected roundtrip file (RDF doesn't preserve context)
model.decode_context(model.JSONLDDecoder(expect_data["@context"]), objset)
# Write out
outfile = tmp_path / "out.json"
with outfile.open("wb") as f:
digest = model.JSONLDInlineSerializer().write(objset, f)
check_file(outfile, expect_data, digest)
def test_to_rdf_roundtrip(model, tmp_path, roundtrip):
with roundtrip.open("r") as f:
expect_data = json.load(f)
# Read JSON data
objset = model.SHACLObjectSet()
with roundtrip.open("r") as f:
model.JSONLDDeserializer().read(f, objset)
# Convert to RDF
g = rdflib.Graph()
model.RDFSerializer().write(objset, g)
# Convert from RDF to new object set
objset = model.SHACLObjectSet()
model.RDFDeserializer().read(g, objset)
# Copy context from expected roundtrip file (RDF doesn't preserve context)
model.decode_context(model.JSONLDDecoder(expect_data["@context"]), objset)
# Write out
outfile = tmp_path / "out.json"
with outfile.open("wb") as f:
digest = model.JSONLDInlineSerializer().write(objset, f)
check_file(outfile, expect_data, digest)
def test_jsonschema_validation(roundtrip, test_jsonschema):
with roundtrip.open("r") as f:
data = json.load(f)
jsonschema.validate(data, schema=test_jsonschema)
@jsonvalidation.validation_tests()
def test_json_validation(passes, data, tmp_path, test_context_url, model_script):
jsonvalidation.replace_context(data, test_context_url)
data_file = tmp_path / "data.json"
data_file.write_text(json.dumps(data))
p = subprocess.run([model_script, data_file, "--outfile", os.devnull], check=False)
if passes:
assert p.returncode == 0
else:
assert p.returncode != 0
@jsonvalidation.link_tests()
def test_links(filename, name, expect_tag, model, tmp_path, test_context_url):
data_file = tmp_path / "data.json"
data_file.write_text(
filename.read_text().replace("@CONTEXT_URL@", test_context_url)
)
objset = model.SHACLObjectSet()
with data_file.open("r") as f:
deserializer = model.JSONLDDeserializer()
deserializer.read(f, objset)
c = objset.find_by_id(name)
assert isinstance(c, model.link_class)
for o in objset.foreach_type(model.link_class):
if o.link_class_tag == expect_tag:
link = o
break
else:
assert False, f"Unable to find object with tag '{expect_tag}'"
assert c.link_class_link_prop is link
assert c.link_class_link_prop_no_class is link
assert c.link_class_link_list_prop == [link, link]
@pytest.mark.parametrize(
"filename,expect,match",
[
pytest.param(
"bad-object-type-inline.json",
VALIDATION_ERROR,
"Type test-class is not valid where",
id="Bad object type for property (inline)",
),
pytest.param(
"bad-object-type-ref-before.json",
VALIDATION_ERROR,
"Value must be one of type: link_class, str. Got test_class",
id="Bad object type for property (linked by ID before)",
),
pytest.param(
"bad-object-type-ref-after.json",
VALIDATION_ERROR,
"Value must be one of type: link_class, str. Got test_class",
id="Bad object type for property (linked by ID after)",
),
],
)
def test_deserialize(filename, expect, match, model, test_context_url):
objset = model.SHACLObjectSet()
deserializer = model.JSONLDDeserializer()
with (DATA_DIR / "python" / filename).open("r") as f:
d = json.loads(f.read().replace("@CONTEXT_URL@", test_context_url))
if expect is VALIDATION_ERROR:
expect = model.ValidationError
if issubclass(expect, Exception):
with pytest.raises(expect, match=match):
deserializer.deserialize_data(d, objset)
else:
deserializer.deserialize_data(d, objset)
def test_node_kind_blank(model, test_context_url):
s = model.JSONLDSerializer()
c1 = model.link_class()
c2 = model.link_class()
c1._id = "http://example.com/c1"
c2._id = "http://example.com/c2"
ref = model.node_kind_blank()
with pytest.raises(model.ValidationError):
ref._id = "http://example.com/name"
# Blank node assignment is fine but not preserved when serializing
ref._id = "_:blank"
# No blank ID is written out for one reference (inline)
c1.link_class_link_prop = ref
result = s.serialize_data(model.SHACLObjectSet([c1, c2]))
assert result == {
"@context": test_context_url,
"@graph": [
{
"@type": "link-class",
"@id": "http://example.com/c1",
"link-class-link-prop": {
"@type": "node-kind-blank",
},
},
{
"@type": "link-class",
"@id": "http://example.com/c2",
},
],
}
# Blank node is written out for multiple references
c2.link_class_link_prop = ref
result = s.serialize_data(model.SHACLObjectSet([c1, c2]))
assert result == {
"@context": test_context_url,
"@graph": [
{
"@type": "node-kind-blank",
"@id": "_:node_kind_blank0",
},
{
"@type": "link-class",
"@id": "http://example.com/c1",
"link-class-link-prop": "_:node_kind_blank0",
},
{
"@type": "link-class",
"@id": "http://example.com/c2",
"link-class-link-prop": "_:node_kind_blank0",
},
],
}
# Listing in the root graph requires a blank node be written
result = s.serialize_data(model.SHACLObjectSet([c1, ref]))
assert result == {
"@context": test_context_url,
"@graph": [
{
"@type": "node-kind-blank",
"@id": "_:node_kind_blank0",
},
{
"@type": "link-class",
"@id": "http://example.com/c1",
"link-class-link-prop": "_:node_kind_blank0",
},
],
}
@pytest.mark.parametrize(
"cls",
["node_kind_iri", "derived_node_kind_iri"],
)
def test_node_kind_iri(model, test_context_url, cls):
TEST_ID = "http://serialize.example.com/name"
TYP = cls.replace("_", "-")
s = model.JSONLDSerializer()
c1 = model.link_class()
c2 = model.link_class()
c1._id = "http://example.com/c1"
c2._id = "http://example.com/c2"
ref = getattr(model, cls)()
with pytest.raises(model.ValidationError):
ref._id = "_:blank"
# serializing without an ID is not allowed
with pytest.raises(model.EncodeError):
s.serialize_data(model.SHACLObjectSet([ref]))
# Inlining not allowed
ref._id = TEST_ID
c1.link_class_link_prop = ref
result = s.serialize_data(model.SHACLObjectSet([c1, c2]))
assert result == {
"@context": test_context_url,
"@graph": [
{
"@type": "link-class",
"@id": "http://example.com/c1",
"link-class-link-prop": TEST_ID,
},
{
"@type": "link-class",
"@id": "http://example.com/c2",
},
{
"@type": TYP,
"@id": TEST_ID,
},
],
}
# Multiple references
c2.link_class_link_prop = ref
result = s.serialize_data(model.SHACLObjectSet([c1, c2]))
assert result == {
"@context": test_context_url,
"@graph": [
{
"@type": "link-class",
"@id": "http://example.com/c1",
"link-class-link-prop": TEST_ID,
},
{
"@type": "link-class",
"@id": "http://example.com/c2",
"link-class-link-prop": TEST_ID,
},
{
"@type": TYP,
"@id": TEST_ID,
},
],
}
# Listing in the root graph forces reference
result = s.serialize_data(model.SHACLObjectSet([c1, ref]))
assert result == {
"@context": test_context_url,
"@graph": [
{
"@type": "link-class",
"@id": "http://example.com/c1",
"link-class-link-prop": TEST_ID,
},
{
"@type": TYP,
"@id": TEST_ID,
},
],
}
@pytest.mark.parametrize(
"cls",
["id_prop_class", "inherited_id_prop_class"],
)
def test_id_name(model, test_context_url, cls):
"""
Test that alternate ID property names work correctly,
including serialization and initialization.
"""
s = model.JSONLDSerializer()
c = getattr(model, cls)()
TEST_ID = "http://serialize.example.com/name"
# Assign alternate ID
c.testid = TEST_ID
assert c.testid == TEST_ID
# alternate ID is an alias for the _id property
assert c._id == TEST_ID
# Delete id
del c.testid
assert c.testid is None
assert c._id is None
# Serialization should use the alias name
c._id = TEST_ID
result = s.serialize_data(model.SHACLObjectSet([c]))
assert result == {
"@context": test_context_url,
"@type": cls.replace("_", "-"),
"testid": TEST_ID,
}
# Test initialization using ID alias
c2 = getattr(model, cls)(testid=TEST_ID)
assert c2.get_id() == TEST_ID
assert c2.testid == TEST_ID
def test_get_id_none(model):
"""get_id returns None when no ID is set."""
c = model.test_class()
assert c.get_id() is None
def test_get_id_set(model):
"""get_id returns the assigned IRI."""
c = model.test_class()
c._id = "http://example.com/obj"
assert c.get_id() == "http://example.com/obj"
def test_set_id(model):
"""set_id assigns the IRI."""
c = model.test_class()
c.set_id("http://example.com/obj")
assert c._id == "http://example.com/obj"
assert c.get_id() == "http://example.com/obj"
def test_set_id_none(model):
"""set_id(None) clears the ID."""
c = model.test_class()
c.set_id("http://example.com/obj")
c.set_id(None)
assert c.get_id() is None
assert c._id is None
def test_set_id_roundtrip(model, test_context_url):
"""Object serialized with set_id value encodes correct @id."""
s = model.JSONLDSerializer()
c = model.test_class()
c.set_id("http://example.com/set-id-obj")
result = s.serialize_data(model.SHACLObjectSet([c]))
assert result["@id"] == "http://example.com/set-id-obj"
@pytest.mark.parametrize("cls", ["id_prop_class", "inherited_id_prop_class"])
def test_get_id_with_alias(model, cls):
"""get_id returns ID set via alias property."""
# id-prop-class is a class with an ID alias "testid"
c = getattr(model, cls)()
c.testid = "http://example.com/alias-obj"
assert c.get_id() == "http://example.com/alias-obj"
@pytest.mark.parametrize("cls", ["id_prop_class", "inherited_id_prop_class"])
def test_set_id_with_alias(model, cls):
"""set_id makes ID accessible through alias property."""
# id-prop-class is a class with an ID alias "testid"
c = getattr(model, cls)()
c.set_id("http://example.com/alias-obj")
assert c.testid == "http://example.com/alias-obj"
assert c.get_id() == "http://example.com/alias-obj"
SAME_AS_VALUE = object()
def type_tests(name, *typ):
tests = [
(name, None, VALIDATION_ERROR),
(name, [], VALIDATION_ERROR),
(name, object(), VALIDATION_ERROR),
(name, lambda model: sum, VALIDATION_ERROR),
]
if bool not in typ and int not in typ:
tests.append((name, True, VALIDATION_ERROR))
tests.append((name, False, VALIDATION_ERROR))
if int not in typ:
tests.append((name, 1, VALIDATION_ERROR))
if float not in typ:
tests.append((name, 1.0, VALIDATION_ERROR))
if datetime not in typ:
tests.append((name, datetime(2024, 3, 11, 0, 0, 0), VALIDATION_ERROR)),
if str not in typ:
tests.append((name, "foo", VALIDATION_ERROR))
return tests
@pytest.mark.parametrize(
"prop,value,expect",
[
# positive integer
("test_class_positive_integer_prop", -1, VALIDATION_ERROR),
("test_class_positive_integer_prop", 0, VALIDATION_ERROR),
("test_class_positive_integer_prop", 1, 1),
("test_class_positive_integer_prop", False, VALIDATION_ERROR),
("test_class_positive_integer_prop", True, 1),
*type_tests("test_class_positive_integer_prop", int),
# non-negative integer
("test_class_nonnegative_integer_prop", -1, VALIDATION_ERROR),
("test_class_nonnegative_integer_prop", 0, 0),
("test_class_nonnegative_integer_prop", 1, 1),
("test_class_nonnegative_integer_prop", False, 0),
("test_class_nonnegative_integer_prop", True, 1),
*type_tests("test_class_nonnegative_integer_prop", int),
# integer
("test_class_integer_prop", -1, -1),
("test_class_integer_prop", 0, 0),
("test_class_integer_prop", 1, 1),
("test_class_integer_prop", False, 0),
("test_class_integer_prop", True, 1),
*type_tests("test_class_integer_prop", int),
# float
("test_class_float_prop", -1, -1.0),
("test_class_float_prop", -1.0, -1.0),
("test_class_float_prop", 0, 0.0),
("test_class_float_prop", 0.0, 0.0),
("test_class_float_prop", 1, 1.0),
("test_class_float_prop", 1.0, 1.0),
("test_class_float_prop", False, 0.0),
("test_class_float_prop", True, 1.0),
*type_tests("test_class_float_prop", int, float),
# boolean
("test_class_boolean_prop", True, True),
("test_class_boolean_prop", False, False),
*type_tests("test_class_boolean_prop", bool),
# datetime
(
# Local time
"test_class_datetime_scalar_prop",
lambda _: datetime(2024, 3, 11, 0, 0, 0),
datetime(2024, 3, 11, 0, 0, 0, tzinfo=TEST_TZ),
),
(
# Explicit timezone
"test_class_datetime_scalar_prop",
datetime(2024, 3, 11, 0, 0, 0, tzinfo=timezone(-timedelta(hours=6))),
SAME_AS_VALUE,
),
(
# Explicit timezone
"test_class_datetime_scalar_prop",
datetime(2024, 3, 11, 0, 0, 0, tzinfo=timezone(timedelta(hours=0))),
SAME_AS_VALUE,
),
(
"test_class_datetime_scalar_prop",
# UTC
datetime(2024, 3, 11, 0, 0, 0, tzinfo=timezone.utc),
SAME_AS_VALUE,
),
(
"test_class_datetime_scalar_prop",
# Microseconds are ignored
lambda _: datetime(2024, 3, 11, 0, 0, 0, 999),
datetime(2024, 3, 11, 0, 0, 0, tzinfo=TEST_TZ),
),
(
"test_class_datetime_scalar_prop",
# Minutes timezone
datetime(
2024, 3, 11, 0, 0, 0, tzinfo=timezone(timedelta(hours=-1, minutes=21))
),
SAME_AS_VALUE,
),
(
"test_class_datetime_scalar_prop",
# Seconds from timezone are dropped
datetime(
2024,
3,
11,
0,
0,
0,
tzinfo=timezone(timedelta(hours=-1, minutes=-21, seconds=-31)),
),
datetime(
2024, 3, 11, 0, 0, 0, tzinfo=timezone(timedelta(hours=-1, minutes=-21))
),
),
*type_tests("test_class_datetime_scalar_prop", datetime),
# datetimestamp
(
# Local time
"test_class_datetimestamp_scalar_prop",
lambda _: datetime(2024, 3, 11, 0, 0, 0),
datetime(2024, 3, 11, 0, 0, 0, tzinfo=TEST_TZ),
),
(
# Explicit timezone
"test_class_datetimestamp_scalar_prop",
datetime(2024, 3, 11, 0, 0, 0, tzinfo=timezone(-timedelta(hours=6))),
SAME_AS_VALUE,
),