json-schema-utils 1.0.1__tar.gz → 1.0.3__tar.gz

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.
Files changed (37) hide show
  1. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/.github/workflows/package.yml +3 -0
  2. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/PKG-INFO +6 -4
  3. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/README.md +5 -3
  4. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/PKG-INFO +6 -4
  5. json_schema_utils-1.0.3/json_schema_utils.egg-info/scm_version.json +8 -0
  6. json_schema_utils-1.0.3/jsu.container +4 -0
  7. json_schema_utils-1.0.3/jsutils/VERSION +1 -0
  8. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/inline.py +119 -59
  9. json_schema_utils-1.0.3/jsutils/resolver.py +110 -0
  10. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/scripts.py +126 -37
  11. json_schema_utils-1.0.1/json_schema_utils.egg-info/scm_version.json +0 -8
  12. json_schema_utils-1.0.1/jsu.container +0 -2
  13. json_schema_utils-1.0.1/jsutils/VERSION +0 -1
  14. json_schema_utils-1.0.1/jsutils/resolver.py +0 -79
  15. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/.gitignore +0 -0
  16. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/LICENSE +0 -0
  17. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/MANIFEST.in +0 -0
  18. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/SOURCES.txt +0 -0
  19. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/dependency_links.txt +0 -0
  20. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/entry_points.txt +0 -0
  21. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/not-zip-safe +0 -0
  22. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/requires.txt +0 -0
  23. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/scm_file_list.json +0 -0
  24. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/json_schema_utils.egg-info/top_level.txt +0 -0
  25. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/__init__.py +0 -0
  26. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/convert.py +0 -0
  27. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/jtd.py +0 -0
  28. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/recurse.py +0 -0
  29. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/restruct.py +0 -0
  30. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/schemas.py +0 -0
  31. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/simplify.py +0 -0
  32. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/stats.py +0 -0
  33. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/types.py +0 -0
  34. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/utils.py +0 -0
  35. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/jsutils/vocab.py +0 -0
  36. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/pyproject.toml +0 -0
  37. {json_schema_utils-1.0.1 → json_schema_utils-1.0.3}/setup.cfg +0 -0
@@ -23,6 +23,9 @@ jobs:
23
23
  steps:
24
24
  - name: Checkout Project
25
25
  uses: actions/checkout@v7
26
+ # avoid shallow checkout for git versioning
27
+ with:
28
+ fetch-depth: 0
26
29
  - name: Set up Python ${{ matrix.python.version }}
27
30
  uses: actions/setup-python@v7
28
31
  with:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: json_schema_utils
3
- Version: 1.0.1
3
+ Version: 1.0.3
4
4
  Summary: JSON Schema Utils
5
5
  Author: Fabien Coelho, Claire Yannou-Medrala
6
6
  License-Expression: CC0-1.0
@@ -28,9 +28,11 @@ Dynamic: license-file
28
28
  Random utilities to analyze, manipulate, simplify, convert or compile JSON Schema.
29
29
 
30
30
  ![Status](https://github.com/zx80/json-schema-utils/actions/workflows/package.yml/badge.svg?branch=post&style=flat)
31
- ![Python](https://img.shields.io/badge/python-3-informational)
31
+ ![Tests](https://img.shields.io/badge/tests-304%20✓-success)
32
+ ![Issues](https://img.shields.io/github/issues/zx80/json-schema-utils?style=flat)
32
33
  ![Version](https://img.shields.io/pypi/v/json-schema-utils)
33
- ![Badges](https://img.shields.io/badge/badges-5-informational)
34
+ ![Python](https://img.shields.io/badge/python-3-informational)
35
+ ![Badges](https://img.shields.io/badge/badges-7-informational)
34
36
  ![License](https://img.shields.io/pypi/l/json-schema-utils?style=flat)
35
37
 
36
38
  ## Installation
@@ -48,7 +50,7 @@ pip install json_schema_utils
48
50
  pip install git+https://github.com/zx80/json-schema-utils.git
49
51
  ```
50
52
 
51
- A [docker image](https://hub.docker.com/repository/docker/zx80/jsu) is also available:
53
+ A [docker image](https://hub.docker.com/r/zx80/jsu) is also available:
52
54
 
53
55
  ```sh
54
56
  docker run --rm -v .:/app/workspace docker.io/zx80/jsu:latest --version
@@ -3,9 +3,11 @@
3
3
  Random utilities to analyze, manipulate, simplify, convert or compile JSON Schema.
4
4
 
5
5
  ![Status](https://github.com/zx80/json-schema-utils/actions/workflows/package.yml/badge.svg?branch=post&style=flat)
6
- ![Python](https://img.shields.io/badge/python-3-informational)
6
+ ![Tests](https://img.shields.io/badge/tests-304%20✓-success)
7
+ ![Issues](https://img.shields.io/github/issues/zx80/json-schema-utils?style=flat)
7
8
  ![Version](https://img.shields.io/pypi/v/json-schema-utils)
8
- ![Badges](https://img.shields.io/badge/badges-5-informational)
9
+ ![Python](https://img.shields.io/badge/python-3-informational)
10
+ ![Badges](https://img.shields.io/badge/badges-7-informational)
9
11
  ![License](https://img.shields.io/pypi/l/json-schema-utils?style=flat)
10
12
 
11
13
  ## Installation
@@ -23,7 +25,7 @@ pip install json_schema_utils
23
25
  pip install git+https://github.com/zx80/json-schema-utils.git
24
26
  ```
25
27
 
26
- A [docker image](https://hub.docker.com/repository/docker/zx80/jsu) is also available:
28
+ A [docker image](https://hub.docker.com/r/zx80/jsu) is also available:
27
29
 
28
30
  ```sh
29
31
  docker run --rm -v .:/app/workspace docker.io/zx80/jsu:latest --version
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: json_schema_utils
3
- Version: 1.0.1
3
+ Version: 1.0.3
4
4
  Summary: JSON Schema Utils
5
5
  Author: Fabien Coelho, Claire Yannou-Medrala
6
6
  License-Expression: CC0-1.0
@@ -28,9 +28,11 @@ Dynamic: license-file
28
28
  Random utilities to analyze, manipulate, simplify, convert or compile JSON Schema.
29
29
 
30
30
  ![Status](https://github.com/zx80/json-schema-utils/actions/workflows/package.yml/badge.svg?branch=post&style=flat)
31
- ![Python](https://img.shields.io/badge/python-3-informational)
31
+ ![Tests](https://img.shields.io/badge/tests-304%20✓-success)
32
+ ![Issues](https://img.shields.io/github/issues/zx80/json-schema-utils?style=flat)
32
33
  ![Version](https://img.shields.io/pypi/v/json-schema-utils)
33
- ![Badges](https://img.shields.io/badge/badges-5-informational)
34
+ ![Python](https://img.shields.io/badge/python-3-informational)
35
+ ![Badges](https://img.shields.io/badge/badges-7-informational)
34
36
  ![License](https://img.shields.io/pypi/l/json-schema-utils?style=flat)
35
37
 
36
38
  ## Installation
@@ -48,7 +50,7 @@ pip install json_schema_utils
48
50
  pip install git+https://github.com/zx80/json-schema-utils.git
49
51
  ```
50
52
 
51
- A [docker image](https://hub.docker.com/repository/docker/zx80/jsu) is also available:
53
+ A [docker image](https://hub.docker.com/r/zx80/jsu) is also available:
52
54
 
53
55
  ```sh
54
56
  docker run --rm -v .:/app/workspace docker.io/zx80/jsu:latest --version
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "1.0.3",
3
+ "distance": 0,
4
+ "node": "g1bdbe0360a08bb41fb52fe937596113f14f339e3",
5
+ "dirty": false,
6
+ "branch": "dev",
7
+ "node_date": "2026-11-28"
8
+ }
@@ -0,0 +1,4 @@
1
+ # use internal "jsu" from "jmc" docker image
2
+ FROM docker.io/zx80/jmc
3
+ LABEL description="JSON Schema Utils"
4
+ ENTRYPOINT ["/app/venv/bin/jsu"]
@@ -0,0 +1 @@
1
+ 1.0.3
@@ -1,4 +1,5 @@
1
1
  from typing import Any
2
+ from dataclasses import dataclass
2
3
  import copy
3
4
  import math
4
5
  import re
@@ -481,6 +482,15 @@ def inlineRefs(schema: JsonSchema, url: str, schemas: Schemas) -> JsonSchema:
481
482
 
482
483
  return recurseSchema(schema, url, rwt=rwtRef)
483
484
 
485
+ #
486
+ # EXTERNAL REFERENCES HANDLING
487
+ #
488
+
489
+ @dataclass
490
+ class Id:
491
+ url: str
492
+ path: SchemaPath
493
+
484
494
  def resolveExternalRefs(
485
495
  schema: JsonSchema, *,
486
496
  url: str = ".",
@@ -534,6 +544,7 @@ def resolveExternalRefs(
534
544
  if modernize:
535
545
  modernizeOldDraft(schema, version=version, level=level)
536
546
 
547
+ # local definitions
537
548
  defs = ("$defs" if "$defs" in schema else
538
549
  "definitions" if "definitions" in schema else
539
550
  "$defs" if version and version >= 8 else
@@ -541,27 +552,28 @@ def resolveExternalRefs(
541
552
  if defs not in schema:
542
553
  schema[defs] = {}
543
554
  else:
544
- assert isinstance(schema[defs], dict)
555
+ assert isinstance(schema[defs], dict), "$defs is an object"
545
556
 
557
+ # id at the root is a check, possibly override
546
558
  if "$id" in schema:
547
559
  assert isinstance(schema["$id"], str), "schema $id must be a string"
548
560
  if url and schema["$id"] != url:
549
561
  log.warning(f"inconsistent $id: {schema['$id']} vs {url}")
550
562
  url = schema["$id"]
551
563
 
552
- # url -> local name in outer scope
564
+ # we will have to re-scope internal references
565
+ # url -> name in outer scope
553
566
  resolved: dict[str, str] = {}
554
- # url -> path in outer scope
567
+ # url -> path in global outer scope
555
568
  url_path: dict[str, str] = {}
556
569
 
557
- # counter when creating new names
570
+ # counter when creating new names for inlining
558
571
  externs: int = 0
559
572
 
560
573
  # url $id stack
561
- pushed: list[tuple] = [ () ]
562
- urls: list[str] = [ url ]
574
+ id_stack = [ Id(url=url, path=()) ]
563
575
 
564
- # whether to cleanup ids
576
+ # whether to cleanup ids on this phase
565
577
  keep_id: bool = True
566
578
 
567
579
  # defs already processed
@@ -587,27 +599,31 @@ def resolveExternalRefs(
587
599
  if re.match(r"#[^/]", url): # local identifier case ???
588
600
  # FIXME is this actually the case
589
601
  pass
590
- elif not is_abs_url(url):
591
- url = urljoin(urls[-1], url)
602
+ elif not is_abs_url(url): # not http/file/urn…
603
+ # FIXME stack url may be a urn:... which is ignored by urljoin
604
+ url = urljoin(id_stack[-1].url, url)
605
+ # else kept as is
592
606
  if anchor is not None: # one more step…
593
607
  url = urljoin(url, "#" + anchor)
594
608
  # else url kept as-is
595
- pushed.append(tuple(p))
596
- urls.append(url)
597
609
  # BTW this may be a local resolution in passing!
598
610
  # FIXME this is not true
599
611
  # resolved[url] = urls[0] + "#/" + schemapath_to_urlpath(p)
600
612
  url_path[url] = "#/" + schemapath_to_urlpath(p)
601
613
  if url.endswith("#"):
602
- rurl = url[:-1]
603
- urls.append(rurl)
604
- url_path[rurl] = "#/" + schemapath_to_urlpath(p)
614
+ nurl = url[:-1]
615
+ url_path[nurl] = url_path[url]
616
+ else:
617
+ nurl = url
618
+ # log.debug(f"id_stack push {p}")
619
+ id_stack.append(Id(url=nurl, path=p))
605
620
  return True
606
621
 
607
622
  def rwtScanPop(local: JsonSchema, p: SchemaPath) -> JsonSchema:
608
- if isinstance(local, dict) and pushed and tuple(p) == pushed[-1]:
609
- pushed.pop()
610
- urls.pop()
623
+ # NOTE do not pop the root which was manually set
624
+ if isinstance(local, dict) and p and p == id_stack[-1].path:
625
+ # log.debug(f"id_stack pop {p} [{id_stack}]")
626
+ id_stack.pop()
611
627
  if not keep_id:
612
628
  if level == logging.DEBUG:
613
629
  local["$comment"] = local["$id"]
@@ -624,41 +640,57 @@ def resolveExternalRefs(
624
640
  return local
625
641
  assert isinstance(local, dict)
626
642
 
627
- # handle a $ref
628
- # TODO ref
643
+ # extract $ref value
629
644
  if "$ref" in local:
645
+
646
+ # get reference destination
630
647
  dest = local["$ref"]
631
- assert isinstance(dest, str) and dest
632
- log.debug(f"$ref={dest} ({urls} / {resolved} / {url_path})")
648
+ assert isinstance(dest, str) and dest, "non empty $ref"
649
+ log.debug(f"$ref={dest} ({id_stack} / {resolved} / {url_path})")
633
650
 
651
+ # normalize to root
634
652
  if dest.endswith("#"):
635
653
  dest += "/"
636
654
 
637
- # reference patterns:
655
+ # reference patterns, with path = /...:
638
656
  # { "$ref": "<full-url>" }
639
- # { "$ref": "<full-url>#<path>" } # path = /xxx/yyy
657
+ # { "$ref": "<full-url>#<path>" }
640
658
  # { "$ref": "<partial-url>" }
641
659
  # { "$ref": "<partial-url>#<path>" }
642
660
  # { "$ref": "#<path>" }
643
661
  # { "$ref": "#<name>" }
644
662
 
645
- if is_abs_url(dest): # full url with optional json path
663
+ if is_abs_url(dest): # full url (http, file, urn) with optional json path
664
+ # log.debug("absolute url")
646
665
  pass
647
666
  elif "#/" in dest or "#" not in dest: # relative url with optional json path
648
- # this is kind of strange, if there is a $id it is for subschemas only,
649
- # not for here, so we have to skip it ?!
650
- # NOTE wtf, it seems to depend on the version :-(
651
- if urls:
652
- if version and version >= 8:
653
- idx = -1
654
- else:
655
- idx = -2 if "$id" in local else -1
656
- dest = urljoin(urls[idx], dest)
667
+ # Oops, what a mess
668
+ # if $id and $ref are together, $ref is NOT relative to this $id up to 7?
669
+ # however the stack is with the local id...
670
+ if version and version <= 7 and "$id" in local:
671
+ idx = -2
672
+ else:
673
+ idx = -1
674
+ # switch to full url
675
+ # log.debug("switching to full url")
676
+ base = id_stack[idx]
677
+ if base.url.startswith(("http:", "https:", "file:")):
678
+ dest = urljoin(base.url, dest)
679
+ elif dest.startswith("#/"):
680
+ # eg base is urn:...
681
+ if base.path:
682
+ dest = "#/" + schemapath_to_urlpath(base.path) + dest[1:]
683
+ url_path[dest] = dest
684
+ # else this is the root, dest is fine
685
+ else:
686
+ log.error(f"cannot handle $ref {dest} at {p}")
657
687
  # log.debug(f"join: {local['$ref']} -> {dest}")
658
688
  elif dest and dest[0] == "#": # name? maybe with a path??
689
+ # log.debug("name?")
659
690
  pass
660
691
  else:
661
692
  log.error(f"cannot handle $ref: {dest}")
693
+ # log.debug(f"$ref is now {dest}")
662
694
  else:
663
695
  dest = None
664
696
 
@@ -666,27 +698,30 @@ def resolveExternalRefs(
666
698
  if not dest:
667
699
  pass
668
700
  elif dest in url_path:
701
+ # substitute with a path
669
702
  local["$ref"] = url_path[dest]
670
- else:
671
- if is_abs_url(dest):
672
- if "#" in dest:
673
- url, path = dest.split("#", 1)
674
- else:
675
- url, path = dest, None
703
+ elif is_abs_url(dest):
704
+ # split as url + path
705
+ # TODO path -> anchor
706
+ if "#" in dest:
707
+ url, path = dest.split("#", 1)
676
708
  else:
677
- url, path = None, None
678
- init_url = url
709
+ url, path = dest, None
679
710
 
680
711
  log.debug(f"url={url} path={path}")
681
712
 
713
+ # this is the real url part of the reference, without anchor stuff
714
+ init_url = url
715
+
682
716
  if url is not None:
717
+ assert isinstance(init_url, str)
683
718
 
684
719
  # local url mapping for some JSTS tests
685
720
  if url in url_path:
686
721
  dest = url_path[url]
687
722
  elif url in resolved: # retrieve local name or path
688
723
  dest = f"#/{defs}/{resolved[url]}"
689
- else: # or create one
724
+ else: # or create a new name for the remote
690
725
  js = resolver.get(url)
691
726
  assert isinstance(js, dict) # pyright
692
727
 
@@ -694,32 +729,34 @@ def resolveExternalRefs(
694
729
  while (name := f"_extern_{externs}_") in schema[defs]: # type: ignore
695
730
  externs += 1
696
731
 
697
- # upgrade schema for later processing
732
+ assert isinstance(name, str)
733
+
734
+ # upgrade schema for later processing, eg id -> $id
698
735
  if modernize:
699
736
  modernizeOldDraft(js, version=version, level=level)
700
737
 
701
738
  # ensure that hierarchical relative urls are consistent in the target
702
739
  if "$id" not in js:
703
740
  js["$id"] = init_url
741
+ elif js["$id"] != init_url:
742
+ log.warning(f"overriding $id in {init_url}")
743
+ # NOTE should it be #/$defs/name instead?
744
+ js["$id"] = init_url
704
745
  else:
705
- if js["$id"] != init_url:
706
- log.warning(f"overriding $id in {init_url}")
707
- # NOTE should it be #/$defs/name instead?
708
- js["$id"] = init_url
709
- else:
710
- # consistent
711
- pass
712
-
713
- assert isinstance(name, str) and isinstance(init_url, str)
746
+ # consistent
747
+ pass
714
748
 
715
- # dest = urls[0] + f"#{defs}/{name}"
749
+ # dest = urls[0] + f"#/{defs}/{name}"
750
+ # store retrieved url as a local definition
716
751
  resolved[init_url] = name
717
- dest = f"#/{defs}/{name}"
718
752
  schema[defs][name] = js # type: ignore
753
+
754
+ dest = f"#/{defs}/{name}"
719
755
  log.warning(f"url_path: {init_url} -> {dest}")
720
- url_path[init_url] = str(dest)
756
+ url_path[init_url] = dest
721
757
 
722
758
  # update external reference to local destination
759
+ # FIXME is this is a local id from the imported schema we do not know it yet!
723
760
  if path:
724
761
  log.debug(f"adding path {path} to dest {dest}")
725
762
  if dest in ("#", "#/"):
@@ -730,7 +767,7 @@ def resolveExternalRefs(
730
767
  if spath in url_path:
731
768
  dest = url_path[spath]
732
769
  else:
733
- log.warning(f"undefined anchor #{path}")
770
+ log.warning(f"undefined path #{path}")
734
771
  dest = "#" + path
735
772
  elif dest[0] == "#":
736
773
  if path[0] == "/":
@@ -742,16 +779,39 @@ def resolveExternalRefs(
742
779
  if spath in url_path:
743
780
  dest = url_path[spath]
744
781
  else:
745
- log.warning(f"undefined anchor #{path}")
746
782
  dest = "#" + path
747
- # else ignore
783
+ jpath = None
784
+
785
+ # fish from within js
786
+ # FIXME maybe the recursion should stop on absolute $id?
787
+ # we look for mere equality, but should be based on the full url
788
+ def collectFlt(j, p) -> bool:
789
+ nonlocal jpath
790
+ if isinstance(j, dict) and "$id" in j:
791
+ if j["$id"] == dest:
792
+ jpath = p
793
+ return False
794
+ else:
795
+ return True
796
+ # shortcut once done
797
+ return jpath is None
798
+
799
+ recurseSchema(js, init_url, path=(defs, name), flt=collectFlt)
800
+
801
+ if jpath is None:
802
+ log.warning(f"undefined $id {dest}")
803
+ else:
804
+ dest = "#/" + schemapath_to_urlpath(jpath)
748
805
  else:
749
806
  dest = urljoin(dest, "#" + path)
807
+
750
808
  local["$ref"] = dest
809
+ else:
810
+ log.error(f"cannot handle $ref to {dest}")
751
811
 
752
812
  return rwtScanPop(local, p)
753
813
 
754
- log.debug("initial scan")
814
+ # root
755
815
  # first pass to populate url_path
756
816
  keep_id = True
757
817
  schema = recurseSchema(schema, ".", flt=fltExtRef, rwt=rwtScanPop, def_first=True)
@@ -0,0 +1,110 @@
1
+ from pathlib import Path
2
+ import hashlib
3
+ import copy
4
+ import json
5
+ import requests
6
+
7
+ from .utils import JsonSchema, log
8
+
9
+ FILE_URL = "file://"
10
+ HTTP_URL = "http://"
11
+ HTTPS_URL = "https://"
12
+
13
+ class Resolver:
14
+
15
+ def __init__(
16
+ self,
17
+ cache: str|None = None,
18
+ mapping: list[str] = [],
19
+ local_only: bool = False):
20
+ self._cache_mem: dict[str, JsonSchema] = {}
21
+ self._cache_dir = cache
22
+ if cache is not None:
23
+ Path(cache).mkdir(parents=True, exist_ok=True)
24
+ # url to local file mapping
25
+ self._mapping = {}
26
+ for m in mapping:
27
+ src, dst = m.split("=", 1)
28
+ self._mapping[src] = dst
29
+
30
+ def _urlHash(self, url: str) -> str:
31
+ return hashlib.sha3_256(url.encode()).hexdigest()[:16]
32
+
33
+ def put(self, url: str, schema: JsonSchema, *, in_file: bool = True):
34
+ """Store url resolution in cache."""
35
+ if url in self._cache_mem:
36
+ log.warning(f"overriding cached {url}")
37
+ self._cache_mem[url] = copy.deepcopy(schema)
38
+ if in_file and self._cache_dir:
39
+ uh = self._urlHash(url)
40
+ cfn = f"{self._cache_dir}/{uh}.json"
41
+ with open(cfn, "w") as f:
42
+ f.write(json.dumps(schema))
43
+
44
+ def delete(self, url: str):
45
+ """Delete from cache."""
46
+ if url in self._cache_mem:
47
+ del self._cache_mem[url]
48
+ if self._cache_dir:
49
+ uh = self._urlHash(url)
50
+ Path(f"{self._cache_dir}/{uh}.json").unlink(missing_ok=True)
51
+
52
+ def get(self, url: str) -> JsonSchema:
53
+ """Download JSON from URL."""
54
+
55
+ init_url = url
56
+ js, loaded, cfn = None, False, None
57
+
58
+ # try loading from caches
59
+ if url in self._cache_mem:
60
+ log.info(f"# loaded from cache mem: {url}")
61
+ return self._cache_mem[url]
62
+ else:
63
+ log.debug(f"not found in cache mem: {url}")
64
+
65
+ if self._cache_dir is not None: # we cache the **initial** url only
66
+ uh = self._urlHash(url)
67
+ cfn = f"{self._cache_dir}/{uh}.json"
68
+ try:
69
+ with open(cfn) as f:
70
+ js = json.load(f)
71
+ log.info(f"# loaded from cache dir: {url}")
72
+ # update memory cache
73
+ if url not in self._cache_mem:
74
+ self._cache_mem[url] = copy.deepcopy(js)
75
+ loaded = True
76
+ except FileNotFoundError:
77
+ log.debug(f"not found in cache dir: {url}")
78
+ except Exception as e:
79
+ log.error(f"ignoring invalid cached file dir: {url} ({e})")
80
+
81
+ # handle mapping
82
+ if not loaded and self._mapping:
83
+ for src, dst in self._mapping.items():
84
+ if url.startswith(src):
85
+ url = dst + url[len(src):]
86
+ log.info(f"remapping {init_url} to {url}")
87
+ break # stop on first match
88
+
89
+ # load file
90
+ if not loaded and not url.startswith((HTTP_URL, HTTPS_URL)):
91
+ fn = url.removeprefix(FILE_URL)
92
+ for suffix in ("", ".json", ".schema.json"):
93
+ fns = fn + suffix
94
+ if Path(fns).exists():
95
+ with open(fns) as f:
96
+ js = json.load(f)
97
+ log.info(f"# loaded from file: {url}")
98
+ loaded = True
99
+ break
100
+
101
+ # actual url resolution
102
+ if not loaded:
103
+ res = requests.get(url)
104
+ log.info(f"# loaded from net: {url!r}")
105
+ js, loaded = res.json(), True
106
+ self.put(init_url, js)
107
+
108
+ # sanity check
109
+ assert isinstance(js, (bool, dict)), "JSON Schema is boolean or object"
110
+ return js
@@ -713,8 +713,7 @@ def json_schema_to_python_checker(
713
713
  typer: bool = True,
714
714
  simpler: bool = True,
715
715
  resilient: bool = True,
716
- cache: str|None = None,
717
- mapping: dict[str, str] = {},
716
+ resolver: Resolver|None = None,
718
717
  level: int = logging.INFO,
719
718
  loose_int: bool = True,
720
719
  loose_float: bool = True,
@@ -723,7 +722,6 @@ def json_schema_to_python_checker(
723
722
  caps: bool = False) -> Callable[[Jsonable], bool]:
724
723
  """Build a dynamic python checker function from a schema."""
725
724
  try:
726
- resolver = Resolver(cache=cache, mapping=mapping)
727
725
  # build the intermediate model
728
726
  model = schema_to_model(
729
727
  schema, name, strict=strict, fix=fix, modernize=modernize, typer=typer,
@@ -747,6 +745,29 @@ def json_schema_to_python_checker(
747
745
  log.warning(f"using all-pass checker for {name} (resilient mode)")
748
746
  return lambda _: True
749
747
 
748
+
749
+ VERSIONS = { 8: 2019, 9: 2020, 10: 9999 }
750
+
751
+ # schema version check for tests, with an ugly semantics
752
+ def is_compatible(version: int, compatibility: str) -> bool:
753
+ compatible: bool|None = None
754
+ version = VERSIONS.get(version, version)
755
+ # process in order
756
+ for item in compatibility.split(","):
757
+ if item.startswith("="):
758
+ if version == int(item[1:]):
759
+ return True
760
+ elif item.startswith("<="): # section end
761
+ if compatible is None or compatible:
762
+ compatible = version <= int(item[2:])
763
+ if compatible:
764
+ return compatible
765
+ else: # proceed to another section
766
+ compatible = None
767
+ else: # section start
768
+ compatible = version >= int(item)
769
+ return compatible if isinstance(compatible, bool) else False
770
+
750
771
  def jsu_runner(xargs: list[str]|None = None) -> int:
751
772
 
752
773
  ap = argparse.ArgumentParser(
@@ -797,18 +818,26 @@ def jsu_runner(xargs: list[str]|None = None) -> int:
797
818
  arg("--no-resilient", dest="resilient", default=False, action="store_true",
798
819
  help="disable model conversion resilience (*)")
799
820
 
800
- arg("--schema-version", "-V", dest="sversion", type=int, default=0,
801
- help="set JSON Schema version")
821
+ # runner selection
822
+ arg("--schema-version", "-V", dest="sversion", type=int, default=9,
823
+ help="set JSON Schema version (3, 4, 6, 7, 8=2019, 9=2020, 10=next)")
824
+ arg("--tagged-only", action="store_true", default=False,
825
+ help="only check format tagged entries")
826
+
802
827
  arg("cases", nargs="*", help="test cases to process")
803
828
  args = ap.parse_args(xargs)
804
829
 
805
830
  ap_common_action(args)
806
831
 
832
+ # see https://json-model.org/models/json-schema-tests-validation#TestCase
807
833
  CASES_MODEL = [
808
834
  {
809
- "description": "",
810
- "schema": "$ANY",
811
- "tests": [
835
+ "_description": "",
836
+ "_schema": "$ANY",
837
+ "?compatibility": "/^(<?=)?\\d+(,(<?=)?\\d+)*$/",
838
+ "?externalSchemas": { "$URL": "$ANY" },
839
+ "?tags": [ { "|": [ "_format-assertion", "_format-annotation" ] } ],
840
+ "_tests": [
812
841
  {
813
842
  "description": "",
814
843
  "data": "$ANY",
@@ -824,43 +853,89 @@ def jsu_runner(xargs: list[str]|None = None) -> int:
824
853
  check_cases = json_model.model_checker_from_json(CASES_MODEL)
825
854
 
826
855
  # stats counters
827
- n_cases, n_cases_passed, n_tests, n_tests_passed, n_errors, n_unsafe = 0, 0, 0, 0, 0, 0
856
+ n_files, n_files_skip = 0, 0
857
+ n_cases, n_cases_passed, n_cases_skip = 0, 0, 0
858
+ n_tests_raw, n_tests_passed, n_tests_skip = 0, 0, 0
859
+ n_errors, n_unsafe = 0, 0
828
860
 
829
- n_args = 0
830
861
  for fname in args.cases:
831
- n_args += 1
862
+ n_files += 1
832
863
  try:
833
864
  # load and sanity check
834
- cases = json.loads(open(fname).read())
835
- # accept a single test for resilience
836
- if isinstance(cases, dict):
837
- cases = [ cases ]
838
- assert check_cases(cases)
865
+ holder = json.loads(open(fname).read())
839
866
 
867
+ # promote simple case as a file
868
+ if "schema" in holder and "description" in holder and "tests" in holder:
869
+ holder = {
870
+ "description": "inlined case",
871
+ "tests": [ holder ]
872
+ }
873
+
874
+ cases = holder["tests"]
875
+ issues = []
876
+ assert check_cases(cases, "", issues), f"oops: {issues}"
877
+
878
+ n_file_cases = 0
840
879
  for ic, case in enumerate(cases):
841
880
 
842
881
  scase = f"{fname}[{ic}]"
843
882
 
844
- n_cases += 1
845
- n_tests += len(case["tests"])
883
+ # FIXME what is the default compatibility?
884
+ compat = case.get("compatibility", "3")
885
+ if not is_compatible(args.sversion, compat):
886
+ log.info(f"skipping {scase} on compatibility {compat}")
887
+ n_cases_skip += 1
888
+ continue
889
+
890
+ # format related tests may be skipped
891
+ if "tags" in case:
892
+ # NOTE no tags means both assertion and format
893
+ fmt_assert = "format-assertion" in case["tags"]
894
+ fmt_annote = "format-annotation" in case["tags"]
895
+ if fmt_assert and not args.format or fmt_annote and args.format or \
896
+ args.tagged_only and fmt_assert and fmt_annote:
897
+ log.info(f"skipping {scase} on tags content")
898
+ n_cases_skip += 1
899
+ continue
900
+ elif args.tagged_only:
901
+ log.info(f"skipping {scase} on tags")
902
+ n_cases_skip += 1
903
+ continue
904
+
905
+ assert "tests" in case and "description" in case, f"check {scase} mandatory props"
906
+ n_tests_raw += len(case["tests"])
846
907
  description = case["description"]
908
+ n_cases += 1
909
+ n_file_cases += 1
847
910
 
848
911
  log.info(f"considering {scase}: {description}")
849
912
 
850
913
  try:
914
+ resolver = Resolver(cache=args.cache, mapping=args.map)
915
+
916
+ # TODO remove?
917
+ if "externalSchemas" in case:
918
+ schemas = case["externalSchemas"]
919
+ for url, schema in schemas.items():
920
+ resolver.put(url, schema)
921
+
922
+ # get checker for case schema
851
923
  checker = json_schema_to_python_checker(
852
924
  case["schema"], scase, strict=args.strict, fix=False,
853
925
  vocabularize=args.vocab, modernize=args.modernize, typer=args.type,
854
926
  simpler=args.simple, predef=args.format,
855
927
  version=args.sversion, resilient=args.resilient,
856
- cache=args.cache, mapping=args.map,
857
- level=args.level,
928
+ resolver=resolver, level=args.level,
858
929
  # hardcoded expectations
859
930
  loose_int=True, loose_float=True, extend=True, caps=False,
860
931
  )
861
932
 
862
- n_case_tests_ok = 0
933
+ n_case_tests_ok, n_case_tests_skip = 0, 0
934
+
863
935
  for it, test in enumerate(case["tests"]):
936
+
937
+ desc = test["description"]
938
+
864
939
  try:
865
940
  valid = checker(test["data"])
866
941
  if valid == test["valid"]:
@@ -870,39 +945,51 @@ def jsu_runner(xargs: list[str]|None = None) -> int:
870
945
  # count wrong rejects as unsafe false negative
871
946
  if not valid:
872
947
  n_unsafe += 1
873
- desc = test["description"]
874
948
  log.error(f"unexpected result on {scase}[{it}]: {desc}")
875
- except BaseException as e:
949
+ except BaseException as e: # checker failed
876
950
  n_errors += 1
877
951
  if args.level == logging.DEBUG:
878
952
  log.error(e, exc_info=True)
879
- log.error(f"case {description}/{test['description']}: FAILED")
953
+ log.error(f"case {description}/{desc}: FAILED")
880
954
 
881
- if n_case_tests_ok == len(case["tests"]):
955
+ # case level summary
956
+ if n_case_tests_ok + n_case_tests_skip == len(case["tests"]):
882
957
  n_cases_passed += 1
883
958
 
884
- except BaseException as e:
959
+ except BaseException as e: # checker failed
885
960
  n_errors += 1
886
961
  if args.level == logging.DEBUG:
887
962
  log.error(e, exc_info=True)
888
963
  log.error(f"case {scase} ({description}): FAILED")
889
964
 
890
- except BaseException as e:
965
+ if n_file_cases == 0:
966
+ n_files_skip += 1
967
+
968
+ except BaseException as e: # invalid case file
891
969
  n_errors += 1
892
970
  if args.level == logging.DEBUG:
893
971
  log.error(e, exc_info=True)
894
972
  log.error(f"cases {fname}: BAD case file {e}")
895
973
 
896
974
  # final report
897
- n_tests_failed = n_tests - n_tests_passed
898
- report = f"files={n_args} errors={n_errors} cases={n_cases_passed}/{n_cases}"
899
- report += f" ({100.0 * n_cases_passed / max(n_cases, 1):.1f}%)"
900
- report += f" tests={n_tests_passed}/{n_tests}"
901
- report += f" ({100.0 * n_tests_passed / max(n_tests, 1):.1f}%, {n_tests_failed} fails)"
902
- print(report)
975
+ n_tests_failed = n_tests_raw - n_tests_passed - n_tests_skip
976
+
977
+ report = (
978
+ f"files={n_files - n_files_skip} errors={n_errors}"
979
+ f" cases={n_cases_passed}/{n_cases} skipped={n_cases_skip}"
980
+ f" ({100.0 * n_cases_passed / max(n_cases, 1):.1f}%)"
981
+ f" tests={n_tests_passed}/{n_tests_raw - n_tests_skip}"
982
+ f" ({100.0 * n_tests_passed / max(n_tests_raw - n_tests_skip, 1):.1f}%,"
983
+ f" {n_tests_failed} fails, {n_tests_skip} skips)"
984
+ )
985
+
986
+ if not args.tagged_only and n_cases != 0 or args.tagged_only and n_tests_raw > n_tests_skip:
987
+ print(report)
988
+ else:
989
+ log.debug(report)
903
990
 
904
991
  # tell whether all was well
905
- return 2 if n_unsafe else 1 if n_tests_failed else 0
992
+ return 2 if n_unsafe else 1 if n_tests_failed or n_errors else 0
906
993
 
907
994
  def jsu_jtd(xargs: list[str]|None = None) -> int:
908
995
 
@@ -955,18 +1042,21 @@ def jsu_jtd(xargs: list[str]|None = None) -> int:
955
1042
 
956
1043
 
957
1044
  #
958
- # master jsu command
1045
+ # main jsu command
959
1046
  #
960
1047
 
961
1048
  _COMMANDS: dict[str, Callable[[list[str]|None], int]]
962
1049
 
963
1050
  def jsu_help(xargs: list[str]) -> int:
1051
+
1052
+ # defaults
964
1053
  if xargs:
965
1054
  cmd, xargs = xargs[0], xargs[1:]
966
1055
  msg = "help " if cmd == "help" else ""
967
1056
  else:
968
1057
  cmd, msg = "help", ""
969
1058
 
1059
+ # help, errors or actual commands
970
1060
  if cmd == "help" or cmd not in _COMMANDS:
971
1061
  print(f"Usage: jsu {msg}[ {' | '.join(_COMMANDS)} ]")
972
1062
  return 0 if cmd == "help" or cmd in _COMMANDS else 1
@@ -990,8 +1080,7 @@ _COMMANDS = {
990
1080
  def jsu_command(xargs: list[str]|None = None) -> int:
991
1081
  if xargs is None:
992
1082
  xargs = sys.argv
993
- if len(xargs) < 2 or xargs[1] in ("-h", "--help"):
994
- # global help
1083
+ if len(xargs) < 2 or xargs[1] in ("-h", "--help"): # global help
995
1084
  jsu_help([""])
996
1085
  return 0
997
1086
  elif xargs[1] in ("--version", "-v"):
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "1.0.1",
3
- "distance": 0,
4
- "node": "g6b2baf9c9e3e04e99771e9a5083540af1ba59f35",
5
- "dirty": false,
6
- "branch": "main",
7
- "node_date": "2026-11-24"
8
- }
@@ -1,2 +0,0 @@
1
- FROM docker.io/zx80/jmc
2
- ENTRYPOINT ["/app/venv/bin/jsu"]
@@ -1 +0,0 @@
1
- 1.0.1
@@ -1,79 +0,0 @@
1
- from pathlib import Path
2
- import hashlib
3
- import json
4
- import requests
5
-
6
- from .utils import JsonSchema, log
7
-
8
- FILE_URL = "file://"
9
- HTTP_URL = "http://"
10
- HTTPS_URL = "https://"
11
-
12
- class Resolver:
13
-
14
- def __init__(
15
- self,
16
- cache: str|None = None,
17
- mapping: list[str] = [],
18
- local_only: bool = False):
19
- self._cache = cache
20
- if cache is not None:
21
- Path(cache).mkdir(parents=True, exist_ok=True)
22
- self._mapping = {}
23
- for m in mapping:
24
- src, dst = m.split("=", 1)
25
- self._mapping[src] = dst
26
-
27
- def _urlHash(self, url: str) -> str:
28
- return hashlib.sha3_256(url.encode()).hexdigest()[:16]
29
-
30
- def get(self, url: str) -> JsonSchema:
31
- """Download JSON from URL."""
32
-
33
- js, loaded, cached, cfn = None, False, False, None
34
-
35
- if self._cache is not None: # we cache the **initial** url only
36
- uh = self._urlHash(url)
37
- cfn = f"{self._cache}/{uh}.json"
38
- try:
39
- with open(cfn) as f:
40
- js = json.load(f)
41
- log.info(f"# loaded from cache: {url}")
42
- loaded, cached = True, True
43
- except Exception:
44
- log.debug(f"not found in cache: {url}")
45
- else:
46
- uh = None
47
-
48
- if not loaded and self._mapping:
49
- for src, dst in self._mapping.items():
50
- if url.startswith(src):
51
- init_url = url
52
- url = dst + url[len(src):]
53
- log.info(f"remapping {init_url} to {url}")
54
- break # stop on first match
55
-
56
- if not loaded and (not url.startswith(HTTP_URL) and not url.startswith(HTTPS_URL)):
57
- fn = url.removeprefix(FILE_URL)
58
- for suffix in ("", ".json", ".schema.json"):
59
- fns = fn + suffix
60
- if Path(fns).exists():
61
- with open(fns) as f:
62
- js = json.load(f)
63
- log.info(f"# loaded from file: {url}")
64
- loaded = True
65
- break
66
-
67
- if not loaded:
68
- res = requests.get(url)
69
- log.info(f"# loaded from net: {url!r}")
70
- js, loaded = res.json(), True
71
-
72
- # store in cache
73
- if self._cache is not None and not cached:
74
- assert isinstance(cfn, str) # pyright
75
- with open(cfn, "w") as f:
76
- f.write(res.text)
77
-
78
- assert isinstance(js, (bool, dict)), "JSON Schema is boolean or object"
79
- return js