-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathtest_jsonld.py
More file actions
1693 lines (1497 loc) · 58.8 KB
/
Copy pathtest_jsonld.py
File metadata and controls
1693 lines (1497 loc) · 58.8 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
import pytest
from rdflib import Dataset
import pyld.jsonld as jsonld
def raise_this(value):
raise ValueError(value)
class TestExpand:
# Issue 50 - PR: https://github.com/digitalbazaar/pyld/pull/51
def test_silently_ignored(self):
"""
Simple example with keys not in the context should silently ignore
dropped keys during expansion when no on_property_dropped handler was
passed.
"""
input = {"fooo": "bar"}
context = {"foo": {"@id": "http://example.com/foo"}}
got = jsonld.expand(input, {"expandContext": context, "base": None})
assert got == []
def test_silently_ignored_complex(self):
"""
Complex example with keys not in the context should silently ignore
dropped keys during expansion when no on_property_dropped handler was
passed.
"""
input = {
"@id": "foo",
"foo": "bar",
"fooo": "baz",
"http://example.com/other": "blah",
}
expected = [
{
"@id": "foo",
"http://example.com/foo": [{"@value": "bar"}],
"http://example.com/other": [{"@value": "blah"}],
}
]
context = {"foo": {"@id": "http://example.com/foo"}}
got = jsonld.expand(input, {"expandContext": context, "base": None})
assert got == expected
def test_dropped_keys_fails(self):
"""
Simple example with keys not in the context should fail during
expansion when on_property_dropped handler raises error.
"""
input = {"fooo": "bar"}
context = {"foo": {"@id": "http://example.com/foo"}}
with pytest.raises(ValueError):
jsonld.expand(
input,
{"expandContext": context, "base": None},
on_property_dropped=raise_this,
)
def test_dropped_keys_fails_complex(self):
"""
Complex example with keys not in the context should fail during
expansion when on_property_dropped handler raises error.
"""
input = {
"@id": "foo",
"foo": "bar",
"fooo": "baz",
"http://example.com/other": "blah",
}
context = {"foo": {"@id": "http://example.com/foo"}}
with pytest.raises(ValueError):
jsonld.expand(
input,
{"expandContext": context, "base": None},
on_property_dropped=raise_this,
)
def test_dropped_keys(self):
"""
Simple example with keys not in the context should correctly store
dropped keys during expansion using the on_property_dropped handler.
"""
input = {"fooo": "bar"}
context = {"foo": {"@id": "http://example.com/foo"}}
dropped_keys = set()
got = jsonld.expand(
input,
{"expandContext": context, "base": None},
on_property_dropped=dropped_keys.add,
)
assert got == []
assert dropped_keys == {"fooo"}
def test_value_object_type_array_fails(self):
"""
Value objects must not allow array values for @type during expansion.
"""
input = {
"@context": {"ex": "http://example.com/"},
"ex:prop": {"@value": "value", "@type": ["ex:a", "ex:b"]},
}
with pytest.raises(jsonld.JsonLdError) as exc:
jsonld.expand(input)
assert exc.value.code == 'invalid typed value'
def test_value_object_type_null_expands(self):
"""
Value objects with @type set to null should expand without @type.
"""
input = {
"@context": {"ex": "http://example.com/"},
"ex:prop": {"@value": "value", "@type": None},
}
assert jsonld.expand(input) == [
{"http://example.com/prop": [{"@value": "value"}]}
]
def test_context_keyword_redefinition_fails(self):
"""
A local context must not define @context as a term.
"""
input = {
"@context": {
"@context": {
"p": "ex:p",
},
},
"@id": "ex:1",
"p": "value",
}
with pytest.raises(jsonld.JsonLdError) as exc:
jsonld.expand(input)
assert exc.value.code == 'keyword redefinition'
def test_dropped_keys_complex(self):
"""
Complex example with keys not in the context should correctly store
dropped keys during expansion using the on_property_dropped handler.
"""
input = {
"@id": "foo",
"foo": "bar",
"fooo": "baz",
"http://example.com/other": "blah",
}
expected = [
{
"@id": "foo",
"http://example.com/foo": [{"@value": "bar"}],
"http://example.com/other": [{"@value": "blah"}],
}
]
context = {"foo": {"@id": "http://example.com/foo"}}
dropped_keys = set()
got = jsonld.expand(
input,
{"expandContext": context, "base": None},
on_property_dropped=dropped_keys.add,
)
assert got == expected
assert dropped_keys == {"fooo"}
# Issue 187
def test_missing_base(self):
"""
Document where `@base` is absent or explicitely set to `null` should
use the default base IRI 'http://example.org/base/'
when no base parameter is set during expansion .
"""
input = {
"@context": {"property": "http://example.com/vocab#property"},
"@id": "../document-relative",
"@type": "#document-relative",
"property": {
"@context": {"@base": "http://example.org/test/"},
"@id": "../document-base-overwritten",
"@type": "#document-base-overwritten",
"property": [
{
"@context": None,
"@id": "../document-relative",
"@type": "#document-relative",
"property": "context completely reset, drops property",
},
{
"@context": {"@base": None},
"@id": "../document-relative",
"@type": "#document-relative",
"property": "only @base is cleared",
},
],
},
}
expected = [
{
"@id": "http://example.org/document-relative",
"@type": ["http://example.org/base/#document-relative"],
"http://example.com/vocab#property": [
{
"@id": "http://example.org/document-base-overwritten",
"@type": ["http://example.org/test/#document-base-overwritten"],
"http://example.com/vocab#property": [
{
"@id": "http://example.org/document-relative",
"@type": ["http://example.org/base/#document-relative"],
},
{
"@id": "../document-relative",
"@type": ["#document-relative"],
"http://example.com/vocab#property": [
{"@value": "only @base is cleared"}
],
},
],
}
],
}
]
got = jsonld.expand(input)
assert got == expected
def test_base_does_not_expand_property_terms(self):
"""
Regression test: @base must not be used to expand property keys.
Property names are expanded vocabulary-relative: @vocab, term
definitions, compact IRIs with a defined prefix, etc. The active
context's @base is for document-relative IRI resolution where the
algorithms pass that flag (e.g. certain @id and @type values), not
for turning arbitrary keys into absolute IRIs. Here the context sets
only @base; `name` has no term definition and no @vocab, so it
cannot become an absolute property IRI and must be dropped.
See: https://www.w3.org/TR/json-ld11-api/#iri-expansion
"""
doc = {
'@context': {'@base': 'https://schema.org/'},
'@id': 'https://w3.org/yaml-ld/',
'@type': 'WebContent',
'name': 'YAML-LD',
}
result = jsonld.expand(doc)
# `name` has no vocabulary-relative mapping (@vocab or term
# definition); @base must not supply one. The key is dropped.
assert result == [
{
'@id': 'https://w3.org/yaml-ld/',
'@type': ['https://schema.org/WebContent'],
}
]
# Issue 143
def test_expand_with_base_from_context(self):
"""Expand with set or not should rely upon @base inside its @context."""
input = {
"@context": {
"name": "https://www.exmaple.com/name",
"@base": "https://www.example.com/",
},
"@id": "c/123",
"name": "alice",
}
expected = [
{
"@id": "https://www.example.com/c/123",
"https://www.exmaple.com/name": [{"@value": "alice"}],
}
]
assert jsonld.expand(input, options={'base': ''}) == expected
assert jsonld.expand(input) == expected
assert jsonld.expand(input, options={'base': 'abc'}) == expected
def _make_context(self, num_terms):
"""Build a context with `num_terms` @type:@vocab terms sharing a scoped context."""
ctx = {"ex": "https://example.org/"}
# A context with multiple terms sharing the same scoped @context.
# This triggers the bug: the first scoped context pre-validation caches
# a result with partial mappings, and subsequent expansion-time lookups
# get a stale cache hit.
shared_scoped_ctx = {
"@vocab": "https://example.org/",
"text": "http://www.w3.org/2004/02/skos/core#notation",
"description": "http://www.w3.org/2004/02/skos/core#prefLabel",
"meaning": "@id",
}
for i in range(num_terms):
ctx[f"EnumProp{i}"] = {
"@id": f"ex:EnumProp{i}",
"@type": "@vocab",
"@context": dict(shared_scoped_ctx),
}
# Add some plain string terms to increase context size
for i in range(80):
ctx[f"prop{i}"] = f"ex:prop{i}"
return ctx
def test_single_vocab_term_expands_correctly(self):
"""Single @type:@vocab term should expand bare string to @id."""
ctx = {
"ex": "https://example.org/",
"Color": {
"@id": "ex:Color",
"@type": "@vocab",
"@context": {"@vocab": "https://example.org/"},
},
}
doc = {"@context": ctx, "Color": "Red"}
result = jsonld.expand(doc)
assert result[0]["https://example.org/Color"] == [
{"@id": "https://example.org/Red"}
]
def test_many_shared_scoped_contexts_expand_correctly(self):
"""
Regression test for scoped context cache pollution during context processing.
When a JSON-LD context has multiple terms that share the same scoped @context
(e.g., enum-typed properties using @type: @vocab with a scoped @vocab), the
pre-validation of scoped contexts during _process_context would cache the
processed result keyed by rval['_uuid']. Since rval is mutated (mappings added)
during the loop, later expansion-time lookups of the same scoped context would
get a stale cache hit with incomplete mappings, causing @type coercion to fail.
The fix regenerates rval['_uuid'] after all term definitions are created,
ensuring expansion-time lookups miss the pre-validation cache.
Multiple @type:@vocab terms with identical scoped contexts should all expand.
"""
ctx = self._make_context(num_terms=30)
doc = {"@context": ctx}
# Set a value for each enum property
for i in range(30):
doc[f"EnumProp{i}"] = f"Value{i}"
result = jsonld.expand(doc)
expanded = result[0]
for i in range(30):
prop_iri = f"https://example.org/EnumProp{i}"
assert prop_iri in expanded, f"EnumProp{i} not in expanded result"
assert expanded[prop_iri] == [{"@id": f"https://example.org/Value{i}"}], (
f"EnumProp{i} did not expand to @id"
)
def test_last_vocab_term_expands_with_large_context(self):
"""The LAST @type:@vocab term in a large context must also expand correctly.
This is the most likely to fail because all prior scoped context
pre-validations have already populated the cache.
"""
ctx = self._make_context(num_terms=27)
# Only test the last term
doc = {"@context": ctx, "EnumProp26": "TestValue"}
result = jsonld.expand(doc)
assert result[0]["https://example.org/EnumProp26"] == [
{"@id": "https://example.org/TestValue"}
]
def test_structured_value_still_works_with_scoped_context(self):
"""Structured values (objects) should still use the scoped context mappings."""
ctx = self._make_context(num_terms=10)
doc = {
"@context": ctx,
"EnumProp5": {
"text": "MyLabel",
"description": "A description",
"meaning": "https://example.org/SomeValue",
},
}
result = jsonld.expand(doc)
prop_val = result[0]["https://example.org/EnumProp5"][0]
# text -> skos:notation
assert "http://www.w3.org/2004/02/skos/core#notation" in prop_val
# meaning -> @id
assert "@id" in prop_val
# Issue 204
def test_scoped_context_on_nest_term_expands_nested_properties(self):
"""A scoped context on a @nest term should apply to nested properties."""
input = {
"@context": {
"@vocab": "http://example.org/vocab#",
"p1": {
"@id": "@nest",
"@context": {"p2": "http://example.org/ns#P2"},
},
},
"p1": {"p2": "foo"},
}
expected = [
{
"http://example.org/ns#P2": [
{
"@value": "foo",
}
],
}
]
result = jsonld.expand(input)
assert result == expected
# Issue 204
def test_scoped_context_on_nest_term_expands_nested_type_scoped_context(self):
"""
A scoped context on a @nest term should be in effect when expanding the
nested node, including when processing any type-scoped contexts found on
that node.
"""
input = {
"@context": {
"@vocab": "http://example.org/outer#",
# p1 is an @nest term with a property-scoped context. That context defines
# Type and gives Type its own type-scoped context.
"p1": {
"@id": "@nest",
"@context": {
# The nested node uses Type and then uses p2 from Type's scoped context.
"Type": {
"@id": "http://example.org/ns#Type",
"@context": {
"p2": "http://example.org/ns#P2",
},
},
},
},
},
"p1": {
"@type": "Type",
"p2": "foo",
},
}
# The @nest term context is active before @type is expanded and before Type's scoped
# context is applied.
expected = [
{
# If nested values are expanded by directly walking their keys instead of
# running the normal expansion setup for the nested node, Type and p2 fall
# back to the outer @vocab.
"@type": ["http://example.org/ns#Type"],
"http://example.org/ns#P2": [
{
"@value": "foo",
}
],
}
]
result = jsonld.expand(input)
assert result == expected
def test_mixed_plain_and_vocab_terms(self):
"""Contexts with both plain and @type:@vocab terms should work correctly."""
ctx = {
"ex": "https://example.org/",
"name": "ex:name",
"Color": {
"@id": "ex:Color",
"@type": "@vocab",
"@context": {"@vocab": "https://example.org/"},
},
"Shape": {
"@id": "ex:Shape",
"@type": "@vocab",
"@context": {"@vocab": "https://example.org/"},
},
}
# Add many plain terms to make context large enough to trigger caching
for i in range(100):
ctx[f"field{i}"] = f"ex:field{i}"
doc = {
"@context": ctx,
"name": "test",
"Color": "Blue",
"Shape": "Circle",
}
result = jsonld.expand(doc)
expanded = result[0]
assert expanded["https://example.org/Color"] == [
{"@id": "https://example.org/Blue"}
]
assert expanded["https://example.org/Shape"] == [
{"@id": "https://example.org/Circle"}
]
assert expanded["https://example.org/name"] == [{"@value": "test"}]
# Issue 145
def test_context_contained_with_propagate(self):
"""
The same context object contained under the node with @propagate
should properly expand.
"""
input = {
"@context": {
"@propagate": False,
"a": {
"@id": "http://abc/a",
"@context": {"b": "http://abc/b", "c": "http://abc/c"},
},
"d": {
"@id": "http://abc/d",
"@context": {"b": "http://abc/b", "c": "http://abc/c"},
},
},
"a": {"b": "bb", "c": "cc"},
"d": {"b": "bbb", "c": "ccc"},
}
expected = [
{
"http://abc/a": [
{
"http://abc/b": [{"@value": "bb"}],
"http://abc/c": [{"@value": "cc"}],
}
],
"http://abc/d": [
{
"http://abc/b": [{"@value": "bbb"}],
"http://abc/c": [{"@value": "ccc"}],
}
],
}
]
expanded = jsonld.expand(input)
assert expanded == expected
def test_expand_stringifies_datetime_date_values(self):
"""
Non-JSON scalar objects such as datetime.date should get stringified.
"""
from datetime import date
expanded = jsonld.expand({
'@context': {'@vocab': 'https://schema.org/'},
'@id': 'https://example.blog/post',
'publicationDate': date(2021, 1, 11),
})
assert expanded == [{
'@id': 'https://example.blog/post',
'https://schema.org/publicationDate': [{'@value': '2021-01-11'}],
}]
# Issue 167
def test_blank_node_prefixes(self):
"""
Blank nodes as prefix should be used in IRI expansion.
"""
input = {"@context": {"t": "_:b"}, "@type": "t:x"}
expected = [{"@type": ["_:bx"]}]
expanded = jsonld.expand(input)
assert expanded == expected
class TestFrame:
# Issue 11 - PR: https://github.com/digitalbazaar/pyld/issues/149
"""
Example with @id alias in an inner context should not change when framing.
"""
def test_processing_id_in_inner_context(self):
input = {
"@type": "Package",
"system": [
{
"namespace": "http://purl.obolibrary.org/obo/",
"contents": [{"uri": "ncit:C147557", "label": "Stuff"}],
}
],
}
context = {
"@context": {
"skos": "http://www.w3.org/2004/02/skos/core#",
"obo": "https://purl.obolibrary.org/obo/",
"termci": "https://hotecosystem.org/termci/",
"ncit": {"@id": "http://purl.obolibrary.org/obo/NCI_", "@prefix": True},
"system": {
"@type": "@id",
"@id": "termci:system",
"@container": "@set",
"@context": {
"@id": "skos:ConceptScheme",
"@context": {
"namespace": "@id",
"contents": {
"@type": "@id",
"@id": "skos:hasConcept",
"@container": "@set",
"@context": {"uri": "@id", "label": "skos:label"},
},
},
},
},
},
"@type": "https://hotecosystem.org/termci/Package",
}
# Convert the RDF back into vanilla JSON
output_json = jsonld.frame(
input,
context,
options={
"expandContext": context,
"base": "https://hotecosystem.org/termci/",
},
)
# Observe that system.contents.uri did not change to system.contents.namespace
assert "namespace" in output_json["system"][0]
assert "uri" in output_json["system"][0]["contents"][0]
# PR: https://github.com/digitalbazaar/pyld/pull/31
FRAME_0001_IN = {
"@context": {
"dc": "http://purl.org/dc/elements/1.1/",
"ex": "http://example.org/vocab#",
"ex:contains": {"@type": "@id"},
},
"@graph": [
{
"@id": "http://example.org/test/#library",
"@type": "ex:Library",
"ex:contains": "http://example.org/test#book",
},
{
"@id": "http://example.org/test#book",
"@type": "ex:Book",
"dc:contributor": "Writer",
"dc:title": "My Book",
"ex:contains": "http://example.org/test#chapter",
},
{
"@id": "http://example.org/test#chapter",
"@type": "ex:Chapter",
"dc:description": "Fun",
"dc:title": "Chapter One",
},
],
}
FRAME_0001_FRAME = {
"@context": {
"dc": "http://purl.org/dc/elements/1.1/",
"ex": "http://example.org/vocab#",
},
"@type": "ex:Library",
"ex:contains": {"@type": "ex:Book", "ex:contains": {"@type": "ex:Chapter"}},
}
FRAME_0001_FRAME_WITHOUT_CONTEXT = {
"@type": "ex:Library",
"ex:contains": {"@type": "ex:Book", "ex:contains": {"@type": "ex:Chapter"}},
}
FRAME_0001_FRAME_WITH_PARTIAL_CONTEXT = {
"@context": {"dc": "http://purl.org/dc/elements/1.1/"},
"@type": "ex:Library",
"ex:contains": {"@type": "ex:Book", "ex:contains": {"@type": "ex:Chapter"}},
}
FRAME_0001_FRAME_CONTEXT = {
"@context": {
"dc": "http://purl.org/dc/elements/1.1/",
"ex": "http://example.org/vocab#",
}
}
FRAME_0001_FRAME_PARTIAL_CONTEXT = {"@context": {"ex": "http://example.org/vocab#"}}
def _frame_with_remote_context(self, input, frame, context):
def fake_loader(url, options):
if url == "http://example.com/frame.json":
return {
"contextUrl": "http://example.com/frame-context.json",
"document": frame,
"documentUrl": url,
"contentType": "application/json+ld",
}
elif url == "http://example.com/frame-context.json":
return {
"contextUrl": None,
"document": context,
"documentUrl": url,
"contentType": "application/json+ld",
}
else:
raise Exception(f"Unknown URL: {url}")
options = {"documentLoader": fake_loader, "omitGraph": False}
return jsonld.frame(input, "http://example.com/frame.json", options=options)
def test_remote_context_local_and_remote_context_equal(self):
"""
Example with both local and remote context should combine both contexts
correctly when framing.
"""
expected = {
"@context": [
{
"dc": "http://purl.org/dc/elements/1.1/",
"ex": "http://example.org/vocab#",
},
"http://example.com/frame-context.json",
],
"@graph": [
{
"@id": "http://example.org/test/#library",
"@type": "ex:Library",
"ex:contains": {
"@id": "http://example.org/test#book",
"@type": "ex:Book",
"dc:contributor": "Writer",
"dc:title": "My Book",
"ex:contains": {
"@id": "http://example.org/test#chapter",
"@type": "ex:Chapter",
"dc:description": "Fun",
"dc:title": "Chapter One",
},
},
}
],
}
framed = self._frame_with_remote_context(
self.FRAME_0001_IN, self.FRAME_0001_FRAME, self.FRAME_0001_FRAME_CONTEXT
)
assert framed == expected
def test_remote_context_remote_context_only(self):
"""
Example with only remote context should use remote context correctly
when framing.
"""
expected = {
"@context": "http://example.com/frame-context.json",
"@graph": [
{
"@id": "http://example.org/test/#library",
"@type": "ex:Library",
"ex:contains": {
"@id": "http://example.org/test#book",
"@type": "ex:Book",
"dc:contributor": "Writer",
"dc:title": "My Book",
"ex:contains": {
"@id": "http://example.org/test#chapter",
"@type": "ex:Chapter",
"dc:description": "Fun",
"dc:title": "Chapter One",
},
},
}
],
}
framed = self._frame_with_remote_context(
self.FRAME_0001_IN,
self.FRAME_0001_FRAME_WITHOUT_CONTEXT,
self.FRAME_0001_FRAME_CONTEXT,
)
assert framed == expected
def test_remote_context_half_context_local_and_half_remote(self):
"""
Example with partial local and partial remote context should combine both contexts
correctly when framing.
"""
expected = {
"@context": [
{"dc": "http://purl.org/dc/elements/1.1/"},
"http://example.com/frame-context.json",
],
"@graph": [
{
"@id": "http://example.org/test/#library",
"@type": "ex:Library",
"ex:contains": {
"@id": "http://example.org/test#book",
"@type": "ex:Book",
"dc:contributor": "Writer",
"dc:title": "My Book",
"ex:contains": {
"@id": "http://example.org/test#chapter",
"@type": "ex:Chapter",
"dc:description": "Fun",
"dc:title": "Chapter One",
},
},
}
],
}
framed = self._frame_with_remote_context(
self.FRAME_0001_IN,
self.FRAME_0001_FRAME_WITH_PARTIAL_CONTEXT,
self.FRAME_0001_FRAME_PARTIAL_CONTEXT,
)
assert framed == expected
# Issue 59 - PR: https://github.com/digitalbazaar/pyld/pull/60
@pytest.mark.network
def test_do_not_compact_dates_without_datatype(self):
"""
Dates without explicit datatype should not be compacted during framing,
"""
input = {
"http://schema.org/name": "Buster the Cat",
"http://schema.org/birthDate": "2012",
"http://schema.org/deathDate": "2015-02-25",
}
frame = {"@context": "https://schema.org/"}
expected = {
"@context": "https://schema.org/",
"name": "Buster the Cat",
"schema:birthDate": "2012",
"schema:deathDate": "2015-02-25",
}
framed = jsonld.frame(input, frame)
assert framed == expected
@pytest.mark.network
def test_compact_dates_with_datatype(self):
"""
Dates with explicit datatype should be compacted during framing.
"""
input = {
"http://schema.org/name": "Buster the Cat",
"http://schema.org/birthDate": {
"@value": "2012",
"@type": "http://schema.org/Date",
},
"http://schema.org/deathDate": {
"@value": "2015-02-25",
"@type": "http://schema.org/Date",
},
}
frame = {"@context": "https://schema.org/"}
expected = {
"@context": "https://schema.org/",
"name": "Buster the Cat",
"birthDate": "2012",
"deathDate": "2015-02-25",
}
framed = jsonld.frame(input, frame)
assert framed == expected
def test_circular_references_link_and_embed(self):
input = {
"@context": "http://schema.org/",
"@type": "Person",
"name": "Jane Doe",
"jobTitle": "Professor",
"telephone": "(425) 123-4567",
"@id": "http://www.janedoe.com",
"knows": {
"name": "John Smith",
"@type": "Person",
"@id": "http://www.johnsmith.me",
"knows": {"@id": "http://www.janedoe.com"},
},
}
expected = {
"@context": "http://schema.org",
"@graph": [
{
"id": "http://www.janedoe.com",
"type": "Person",
"jobTitle": "Professor",
"knows": {
"id": "http://www.johnsmith.me",
"type": "Person",
"knows": {"id": "http://www.janedoe.com"},
"name": "John Smith",
},
"name": "Jane Doe",
"telephone": "(425) 123-4567",
},
{
"id": "http://www.johnsmith.me",
"type": "Person",
"knows": {
"id": "http://www.janedoe.com",
"type": "Person",
"jobTitle": "Professor",
"knows": {"id": "http://www.johnsmith.me"},
"name": "Jane Doe",
"telephone": "(425) 123-4567",
},
"name": "John Smith",
},
],
}
frame = {'@context': 'http://schema.org', '@embed': '@once'}
assert expected == jsonld.frame(input, frame)
# this should result in a RuntimeError for exceeding recursion depth
frame = {'@context': 'http://schema.org', '@embed': '@link'}
with pytest.raises(RecursionError):
jsonld.frame(input, frame)
class TestToRdf:
# PR: https://github.com/digitalbazaar/pyld/pull/202
def test_double_and_float_values(self):
"""
String values with @type: "xsd:double" should be converted to float value during to_rdf.
"""
input = {
"@context": {"xsd": "http://www.w3.org/2001/XMLSchema#"},
"@graph": [
{"@id": "ex:1", "ex:p": {"@type": "xsd:double", "@value": "45"}}
],
}
expected = (
'<ex:1> <ex:p> "4.5E1"'
"^^<http://www.w3.org/2001/XMLSchema#double> .\n\n"
)
result = jsonld.to_rdf(input, {"format": "application/n-quads"})
assert result == expected
def test_legacy_mode(self):
"""
legacyMode should return the PyLD 3.x RDF.js-like dataset dict.
"""
input = {
"@context": {"xsd": "http://www.w3.org/2001/XMLSchema#"},
"@graph": [
{"@id": "ex:1", "ex:p": {"@type": "xsd:double", "@value": "45"}}
],
}
expected = {
"@default": [
{
"subject": {"type": "IRI", "value": "ex:1"},
"predicate": {"type": "IRI", "value": "ex:p"},
"object": {
"type": "literal",
"value": "4.5E1",
"datatype": "http://www.w3.org/2001/XMLSchema#double",
},
}
]
}
assert isinstance(jsonld.to_rdf(input), Dataset)
assert jsonld.to_rdf(input, {"legacyMode": True}) == expected
def test_format_takes_precedence_over_legacy_mode(self):
"""
N-Quads format output should still be returned when legacyMode is true.
"""
input = {
"@context": {"xsd": "http://www.w3.org/2001/XMLSchema#"},
"@graph": [
{"@id": "ex:1", "ex:p": {"@type": "xsd:double", "@value": "45"}}
],
}
assert jsonld.to_rdf(
input,
{"format": "application/n-quads", "legacyMode": True},
) == (
'<ex:1> <ex:p> "4.5E1"'
"^^<http://www.w3.org/2001/XMLSchema#double> .\n\n"