Script 'mail_helper' called by obssrc Hello community, here is the log from the commit of package python-genson for openSUSE:Factory checked in at 2026-11-30 14:27:32 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-genson (Old) and /work/SRC/openSUSE:Factory/.python-genson.new.1340718 (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-genson" Mon Nov 30 14:27:32 2026 rev:4 rq:1401500 version:1.4.0 Changes: -------- --- /work/SRC/openSUSE:Factory/python-genson/python-genson.changes 2025-03-03 16:05:16.587619510 +0100 +++ /work/SRC/openSUSE:Factory/.python-genson.new.1340718/python-genson.changes 2026-11-30 14:30:24.872085827 +0100 @@ -1,0 +2,34 @@ +Sun Nov 29 21:40:24 UTC 2026 - Dirk Müller <[email protected]> + +- update to 1.4.0: + * add enum support, activated per node by seed schemas (PR #82 + — thanks @tokarenko; closes #46, #81) + * Performance: strategy deduplication when defining custom + SchemaBuilder classes is now O(n) instead of O(n²) (PR #91 — + thanks @Bitshifter-9; fixes #90) + * include the complete, runnable test suite in the source + distribution (PR #94 — thanks @mgorny) + * Bugfix: fix "noting to do" typo in the CLI error message and + remove dead code (PR #93 — thanks @est) + * Docs: document the required-dropping behavior and the + builder-merge gotcha (#78, #25); explain why same-type inputs + merge rather than producing anyOf; add a NoRequiredObject + example for suppressing required + * declare python_requires >= 3.10, matching the tested Python + versions + * Bugfix: include the genson.schema subpackage in the package + build; installing v1.3.0 from a wheel failed with + ModuleNotFoundError (fixes #80, #92) + * Bugfix: call super().add_object() in the Number strategy so + subclass hooks run (PR #79) + * add Python 3.13 and 3.14 to the test matrix and classifiers; + drop EOL Python 3.7–3.9 (the package itself is unchanged and + older Pythons may still work, but they are no longer tested) + * migrate CI from Travis to GitHub Actions; releases are now + published via PyPI trusted publishing + * Tests: CLI integration tests use sys.executable (PR #84) and + no longer depend on the test runner having an interactive + stdin +- drop use-sys-executable.patch (upstream) + +------------------------------------------------------------------- Old: ---- genson-1.3.0.tar.gz use-sys-executable.patch New: ---- genson-1.4.0.tar.gz ----------(Old B)---------- Old: stdin - drop use-sys-executable.patch (upstream) ----------(Old E)---------- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-genson.spec ++++++ --- /var/tmp/diff_new_pack.Nn0niw/_old 2026-11-30 14:30:26.308146153 +0100 +++ /var/tmp/diff_new_pack.Nn0niw/_new 2026-11-30 14:30:26.310146237 +0100 @@ -1,7 +1,7 @@ # # spec file for package python-genson # -# Copyright (c) 2025 SUSE LLC +# Copyright (c) 2026 SUSE LLC and contributors # # All modifications and additions to the file contributed by third parties # remain the property of their copyright owners, unless otherwise agreed @@ -17,17 +17,16 @@ Name: python-genson -Version: 1.3.0 +Version: 1.4.0 Release: 0 Summary: Python JSON Schema generator License: MIT URL: https://github.com/wolverdude/genson/ Source: https://files.pythonhosted.org/packages/source/g/genson/genson-%{version}.tar.gz -# PATCH-FIX-UPSTREAM gh#wolverdude/GenSON#84 -Patch0: use-sys-executable.patch -BuildRequires: %{python_module base >= 3.7} +BuildRequires: %{python_module base >= 3.10} BuildRequires: %{python_module pip} -BuildRequires: %{python_module setuptools} +BuildRequires: %{python_module setuptools >= 44} +BuildRequires: %{python_module wheel} BuildRequires: fdupes BuildRequires: python-rpm-macros BuildArch: noarch @@ -66,7 +65,7 @@ %python_uninstall_alternative genson %files %{python_files} -%doc AUTHORS.rst README.rst HISTORY.rst +%doc README.rst HISTORY.rst %license LICENSE %python_alternative %{_bindir}/genson %{python_sitelib}/genson ++++++ genson-1.3.0.tar.gz -> genson-1.4.0.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/.gitignore new/genson-1.4.0/.gitignore --- old/genson-1.3.0/.gitignore 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/.gitignore 1970-01-01 01:00:00.000000000 +0100 @@ -1,16 +0,0 @@ -# See: github.com/github/gitignore/blob/master/Python.gitignore - -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] - -# Distribution / packaging -build/ -dist/ -*.egg-info/ -*.egg -*.eggs - -# Testing / CI -.coverage -.tox diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/.travis.yml new/genson-1.4.0/.travis.yml --- old/genson-1.3.0/.travis.yml 2024-05-14 04:46:14.000000000 +0200 +++ new/genson-1.4.0/.travis.yml 1970-01-01 01:00:00.000000000 +0100 @@ -1,21 +0,0 @@ -language: python - -# run tests for all envs -python: - - 3.7 - - 3.8 - - 3.9 - - 3.10 - - 3.11 - - 3.12 -env: ISOLATED=false -install: pip install tox tox-travis -script: tox - -# lint only needs run once -jobs: - include: - - python: 3.9 - env: ISOLATED=false - install: pip install flake8 - script: flake8 diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/HISTORY.rst new/genson-1.4.0/HISTORY.rst --- old/genson-1.3.0/HISTORY.rst 2024-05-15 22:32:20.000000000 +0200 +++ new/genson-1.4.0/HISTORY.rst 2026-07-06 10:21:13.000000000 +0200 @@ -1,6 +1,25 @@ History ======= +1.4.0 +----- + +* add ``enum`` support, activated per node by seed schemas (PR #82 — thanks @tokarenko; closes #46, #81) +* **Performance**: strategy deduplication when defining custom ``SchemaBuilder`` classes is now O(n) instead of O(n²) (PR #91 — thanks @Bitshifter-9; fixes #90) +* include the complete, runnable test suite in the source distribution (PR #94 — thanks @mgorny) +* **Bugfix**: fix "noting to do" typo in the CLI error message and remove dead code (PR #93 — thanks @est) +* **Docs**: document the ``required``-dropping behavior and the builder-merge gotcha (#78, #25); explain why same-type inputs merge rather than producing ``anyOf``; add a ``NoRequiredObject`` example for suppressing ``required`` (#37, #60) +* declare ``python_requires >= 3.10``, matching the tested Python versions + +1.3.1 +----- + +* **Bugfix**: include the ``genson.schema`` subpackage in the package build; installing v1.3.0 from a wheel failed with ``ModuleNotFoundError`` (fixes #80, #92) +* **Bugfix**: call ``super().add_object()`` in the ``Number`` strategy so subclass hooks run (PR #79) +* add Python 3.13 and 3.14 to the test matrix and classifiers; drop EOL Python 3.7–3.9 (the package itself is unchanged and older Pythons may still work, but they are no longer tested) +* migrate CI from Travis to GitHub Actions; releases are now published via PyPI trusted publishing +* **Tests**: CLI integration tests use ``sys.executable`` (PR #84) and no longer depend on the test runner having an interactive stdin + 1.3.0 ----- diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/MANIFEST.in new/genson-1.4.0/MANIFEST.in --- old/genson-1.3.0/MANIFEST.in 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/MANIFEST.in 2026-07-06 10:21:13.000000000 +0200 @@ -1,3 +1,3 @@ include *.rst include LICENSE -recursive-include test *.json +recursive-include test *.json *.py *.txt diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/PKG-INFO new/genson-1.4.0/PKG-INFO --- old/genson-1.3.0/PKG-INFO 2024-05-15 23:58:38.928374300 +0200 +++ new/genson-1.4.0/PKG-INFO 2026-07-06 10:21:23.741861300 +0200 @@ -1,9 +1,8 @@ -Metadata-Version: 2.1 +Metadata-Version: 2.4 Name: genson -Version: 1.3.0 +Version: 1.4.0 Summary: GenSON is a powerful, user-friendly JSON Schema generator. Home-page: https://github.com/wolverdude/genson/ -Download-URL: https://github.com/wolverdude/GenSON/tarball/v0.2s.0 Author: Jon Wolverton Author-email: [email protected] License: MIT @@ -16,18 +15,20 @@ Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: File Formats :: JSON :: JSON Schema Classifier: Topic :: Software Development :: Code Generators Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Utilities +Requires-Python: >=3.10 Description-Content-Type: text/x-rst License-File: LICENSE License-File: AUTHORS.rst +Dynamic: license-file GenSON ====== @@ -39,12 +40,20 @@ GenSON's core function is to take JSON objects and generate schemas that describe them, but it is unique in its ability to *merge* schemas. It was originally built to describe the common structure of a large number of JSON objects, and it uses its merging ability to generate a single schema from any number of JSON objects and/or schemas. + +GenSON's Guiding Rules +---------------------- + GenSON's schema builder follows these three rules: 1. *Every* object it is given must validate under the generated schema. 2. *Any* object that is valid under *any* schema it is given must also validate under the generated schema. (there is one glaring exception to this, detailed `below`_) 3. The generated schema should be as strict as possible given the first 2 rules. +There are of course a number of gotchas and edge-cases that GenSON tries to resolve, but doesn't always do it the way that you want. For example, inputs of the same broad type always *merge* into a single schema: two object inputs become one object schema with the union of their properties, never an ``anyOf`` of the two. GenSON only reaches for ``anyOf`` when it encounters fundamentally different structures, like an object and an array. + +GenSON is extensible, making it possible for you to make a different choice in many of these cases. In the case above, if you want alternatives kept separate, generate a schema per shape using separate builders and combine them yourself with ``{"anyOf": [...]}``. + JSON Schema Implementation -------------------------- @@ -62,6 +71,7 @@ * ``"patternProperties"`` * ``"required"`` * ``"anyOf"`` +* ``"enum"`` (only with a `seed schema <#seeding-enums>`__) You should be aware that this limited vocabulary could cause GenSON to violate rules 1 and 2. If you feed it schemas with advanced keywords, it will just blindly pass them on to the final schema. Note that ``"$ref"`` and ``id`` are also not supported, so GenSON will not dereference linked nodes when building a schema. @@ -133,10 +143,12 @@ >>> from genson import SchemaBuilder >>> builder = SchemaBuilder() - >>> builder.add_schema({"type": "object", "properties": {}}) + + >>> # Add some objects to infer their schema. >>> builder.add_object({"hi": "there"}) >>> builder.add_object({"hi": 5}) + >>> # Export the schema as a Python dict. >>> builder.to_schema() {'$schema': 'http://json-schema.org/schema#', 'type': 'object', @@ -144,6 +156,15 @@ 'hi': {'type': ['integer', 'string']}}, 'required': ['hi']} + >>> # Merge in another schema. + >>> builder.add_schema({ + "type": "object", + "properties": { + "hi": {"type": "boolean"} + } + }) + + >>> # Export the schema as a JSON string. >>> print(builder.to_json(indent=2)) { "$schema": "http://json-schema.org/schema#", @@ -151,6 +172,7 @@ "properties": { "hi": { "type": [ + "boolean", "integer", "string" ] @@ -321,6 +343,42 @@ * If a key matches multiple patterns, there is *no guarantee* of which one will be updated. * The patternProperties_ docs themselves have some more useful pointers that can save you time. +Seeding required +++++++++++++++++ + +GenSON sets ``required`` to the keys that have appeared in *every* object it has seen, and once that intersection is empty, it drops ``required`` from the output entirely rather than emitting an empty list. To force an empty ``required`` into the output, seed the builder with one: ``{"type": "object", "required": []}``. + +.. warning:: + This matters when merging one ``SchemaBuilder`` into another, because the hand-off goes through ``to_schema()``. An unseeded builder whose ``required`` has *become* empty serializes without ``required``, so the receiving builder can diverge from the original as more schemas are added. Seeding both builders with ``"required": []`` prevents this. See issues `#78`_ and `#25`_ for the full story. + +Seeding enums ++++++++++++++ + +Support for enum_ is new in version 1.4. GenSON never infers an ``enum`` on its own; you activate it per node by seeding that node with a schema containing the ``enum`` keyword (an empty list is fine). Once activated, the node records every value it encounters — deduplicated — instead of inferring a type. + +.. code-block:: python + + >>> from genson import SchemaBuilder + + >>> builder = SchemaBuilder() + >>> builder.add_schema({'type': 'object', 'properties': { + ... 'status': {'enum': []}}}) + >>> builder.add_object({'status': 'active'}) + >>> builder.add_object({'status': 'inactive'}) + >>> builder.add_object({'status': 'active'}) + >>> builder.to_schema() + {'$schema': 'http://json-schema.org/schema#', + 'type': 'object', + 'properties': {'status': {'enum': ['inactive', 'active']}}, + 'required': ['status']} + +Some things to be aware of: + +* Values are merged as a set, so the order of the output list is *not* guaranteed. +* Only scalar values (strings, numbers, booleans, and ``null``) are supported. Feeding a list or object to an enum node raises a ``TypeError``. (The JSON-Schema spec technically allows non-scalar enum values, but this is a rare use-case; if you need it, extend the ``Enum`` strategy.) +* An activated enum node captures *all* values it sees, taking precedence over the typed strategies. +* There is no direct support for const_, but it's easy to get there from here: seed the node with ``enum``, and if exactly one value comes back, replace ``{"enum": [value]}`` with ``{"const": value}`` yourself. + Typeless Schemas ++++++++++++++++ @@ -525,6 +583,29 @@ >>> picky_builder.add_object(None) # this fails genson.schema.node.SchemaGenerationError: Could not find matching schema type for object: None +Example: ``NoRequiredObject`` ++++++++++++++++++++++++++++++ + +Custom strategies can also *remove* keywords. A common request is to leave ``required`` out of generated schemas entirely, so that objects with missing keys still validate: + +.. code-block:: python + + from genson import SchemaBuilder + from genson.schema.strategies import Object + + class NoRequiredObject(Object): + # drop 'required' from the list of handled keywords + KEYWORDS = tuple(kw for kw in Object.KEYWORDS if kw != 'required') + + def to_schema(self): + schema = super().to_schema() + schema.pop('required', None) + return schema + + class NoRequiredSchemaBuilder(SchemaBuilder): + """ generates schemas without the 'required' keyword """ + EXTRA_STRATEGIES = (NoRequiredObject,) + Contributing ------------ @@ -536,7 +617,7 @@ 3. Lint your code with `Flake8`_. 4. Run `tox`_ to make sure the test suite passes. 5. Ensure the docs are accurate. -6. Add your name to the list of contributers. +6. Add your name to the list of contributors. 7. Submit a Pull Request. Tests @@ -585,6 +666,10 @@ .. _below: #typeless-schemas .. _array validation here: https://spacetelescope.github.io/understanding-json-schema/reference/array.html#items .. _patternProperties: https://spacetelescope.github.io/understanding-json-schema/reference/object.html#pattern-properties +.. _enum: https://json-schema.org/understanding-json-schema/reference/enum +.. _const: https://json-schema.org/understanding-json-schema/reference/const +.. _#78: https://github.com/wolverdude/GenSON/issues/78 +.. _#25: https://github.com/wolverdude/GenSON/issues/25 .. _Python flavor of RegEx: https://docs.python.org/3.6/library/re.html .. _the code: https://github.com/wolverdude/GenSON/tree/master/genson/schema/strategies .. _minimum number: https://json-schema.org/understanding-json-schema/reference/numeric.html#range @@ -596,6 +681,25 @@ History ======= +1.4.0 +----- + +* add ``enum`` support, activated per node by seed schemas (PR #82 — thanks @tokarenko; closes #46, #81) +* **Performance**: strategy deduplication when defining custom ``SchemaBuilder`` classes is now O(n) instead of O(n²) (PR #91 — thanks @Bitshifter-9; fixes #90) +* include the complete, runnable test suite in the source distribution (PR #94 — thanks @mgorny) +* **Bugfix**: fix "noting to do" typo in the CLI error message and remove dead code (PR #93 — thanks @est) +* **Docs**: document the ``required``-dropping behavior and the builder-merge gotcha (#78, #25); explain why same-type inputs merge rather than producing ``anyOf``; add a ``NoRequiredObject`` example for suppressing ``required`` (#37, #60) +* declare ``python_requires >= 3.10``, matching the tested Python versions + +1.3.1 +----- + +* **Bugfix**: include the ``genson.schema`` subpackage in the package build; installing v1.3.0 from a wheel failed with ``ModuleNotFoundError`` (fixes #80, #92) +* **Bugfix**: call ``super().add_object()`` in the ``Number`` strategy so subclass hooks run (PR #79) +* add Python 3.13 and 3.14 to the test matrix and classifiers; drop EOL Python 3.7–3.9 (the package itself is unchanged and older Pythons may still work, but they are no longer tested) +* migrate CI from Travis to GitHub Actions; releases are now published via PyPI trusted publishing +* **Tests**: CLI integration tests use ``sys.executable`` (PR #84) and no longer depend on the test runner having an interactive stdin + 1.3.0 ----- diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/README.rst new/genson-1.4.0/README.rst --- old/genson-1.3.0/README.rst 2024-05-15 23:52:05.000000000 +0200 +++ new/genson-1.4.0/README.rst 2026-07-06 10:21:13.000000000 +0200 @@ -8,12 +8,20 @@ GenSON's core function is to take JSON objects and generate schemas that describe them, but it is unique in its ability to *merge* schemas. It was originally built to describe the common structure of a large number of JSON objects, and it uses its merging ability to generate a single schema from any number of JSON objects and/or schemas. + +GenSON's Guiding Rules +---------------------- + GenSON's schema builder follows these three rules: 1. *Every* object it is given must validate under the generated schema. 2. *Any* object that is valid under *any* schema it is given must also validate under the generated schema. (there is one glaring exception to this, detailed `below`_) 3. The generated schema should be as strict as possible given the first 2 rules. +There are of course a number of gotchas and edge-cases that GenSON tries to resolve, but doesn't always do it the way that you want. For example, inputs of the same broad type always *merge* into a single schema: two object inputs become one object schema with the union of their properties, never an ``anyOf`` of the two. GenSON only reaches for ``anyOf`` when it encounters fundamentally different structures, like an object and an array. + +GenSON is extensible, making it possible for you to make a different choice in many of these cases. In the case above, if you want alternatives kept separate, generate a schema per shape using separate builders and combine them yourself with ``{"anyOf": [...]}``. + JSON Schema Implementation -------------------------- @@ -31,6 +39,7 @@ * ``"patternProperties"`` * ``"required"`` * ``"anyOf"`` +* ``"enum"`` (only with a `seed schema <#seeding-enums>`__) You should be aware that this limited vocabulary could cause GenSON to violate rules 1 and 2. If you feed it schemas with advanced keywords, it will just blindly pass them on to the final schema. Note that ``"$ref"`` and ``id`` are also not supported, so GenSON will not dereference linked nodes when building a schema. @@ -102,10 +111,12 @@ >>> from genson import SchemaBuilder >>> builder = SchemaBuilder() - >>> builder.add_schema({"type": "object", "properties": {}}) + + >>> # Add some objects to infer their schema. >>> builder.add_object({"hi": "there"}) >>> builder.add_object({"hi": 5}) + >>> # Export the schema as a Python dict. >>> builder.to_schema() {'$schema': 'http://json-schema.org/schema#', 'type': 'object', @@ -113,6 +124,15 @@ 'hi': {'type': ['integer', 'string']}}, 'required': ['hi']} + >>> # Merge in another schema. + >>> builder.add_schema({ + "type": "object", + "properties": { + "hi": {"type": "boolean"} + } + }) + + >>> # Export the schema as a JSON string. >>> print(builder.to_json(indent=2)) { "$schema": "http://json-schema.org/schema#", @@ -120,6 +140,7 @@ "properties": { "hi": { "type": [ + "boolean", "integer", "string" ] @@ -290,6 +311,42 @@ * If a key matches multiple patterns, there is *no guarantee* of which one will be updated. * The patternProperties_ docs themselves have some more useful pointers that can save you time. +Seeding required +++++++++++++++++ + +GenSON sets ``required`` to the keys that have appeared in *every* object it has seen, and once that intersection is empty, it drops ``required`` from the output entirely rather than emitting an empty list. To force an empty ``required`` into the output, seed the builder with one: ``{"type": "object", "required": []}``. + +.. warning:: + This matters when merging one ``SchemaBuilder`` into another, because the hand-off goes through ``to_schema()``. An unseeded builder whose ``required`` has *become* empty serializes without ``required``, so the receiving builder can diverge from the original as more schemas are added. Seeding both builders with ``"required": []`` prevents this. See issues `#78`_ and `#25`_ for the full story. + +Seeding enums ++++++++++++++ + +Support for enum_ is new in version 1.4. GenSON never infers an ``enum`` on its own; you activate it per node by seeding that node with a schema containing the ``enum`` keyword (an empty list is fine). Once activated, the node records every value it encounters — deduplicated — instead of inferring a type. + +.. code-block:: python + + >>> from genson import SchemaBuilder + + >>> builder = SchemaBuilder() + >>> builder.add_schema({'type': 'object', 'properties': { + ... 'status': {'enum': []}}}) + >>> builder.add_object({'status': 'active'}) + >>> builder.add_object({'status': 'inactive'}) + >>> builder.add_object({'status': 'active'}) + >>> builder.to_schema() + {'$schema': 'http://json-schema.org/schema#', + 'type': 'object', + 'properties': {'status': {'enum': ['inactive', 'active']}}, + 'required': ['status']} + +Some things to be aware of: + +* Values are merged as a set, so the order of the output list is *not* guaranteed. +* Only scalar values (strings, numbers, booleans, and ``null``) are supported. Feeding a list or object to an enum node raises a ``TypeError``. (The JSON-Schema spec technically allows non-scalar enum values, but this is a rare use-case; if you need it, extend the ``Enum`` strategy.) +* An activated enum node captures *all* values it sees, taking precedence over the typed strategies. +* There is no direct support for const_, but it's easy to get there from here: seed the node with ``enum``, and if exactly one value comes back, replace ``{"enum": [value]}`` with ``{"const": value}`` yourself. + Typeless Schemas ++++++++++++++++ @@ -494,6 +551,29 @@ >>> picky_builder.add_object(None) # this fails genson.schema.node.SchemaGenerationError: Could not find matching schema type for object: None +Example: ``NoRequiredObject`` ++++++++++++++++++++++++++++++ + +Custom strategies can also *remove* keywords. A common request is to leave ``required`` out of generated schemas entirely, so that objects with missing keys still validate: + +.. code-block:: python + + from genson import SchemaBuilder + from genson.schema.strategies import Object + + class NoRequiredObject(Object): + # drop 'required' from the list of handled keywords + KEYWORDS = tuple(kw for kw in Object.KEYWORDS if kw != 'required') + + def to_schema(self): + schema = super().to_schema() + schema.pop('required', None) + return schema + + class NoRequiredSchemaBuilder(SchemaBuilder): + """ generates schemas without the 'required' keyword """ + EXTRA_STRATEGIES = (NoRequiredObject,) + Contributing ------------ @@ -505,7 +585,7 @@ 3. Lint your code with `Flake8`_. 4. Run `tox`_ to make sure the test suite passes. 5. Ensure the docs are accurate. -6. Add your name to the list of contributers. +6. Add your name to the list of contributors. 7. Submit a Pull Request. Tests @@ -554,6 +634,10 @@ .. _below: #typeless-schemas .. _array validation here: https://spacetelescope.github.io/understanding-json-schema/reference/array.html#items .. _patternProperties: https://spacetelescope.github.io/understanding-json-schema/reference/object.html#pattern-properties +.. _enum: https://json-schema.org/understanding-json-schema/reference/enum +.. _const: https://json-schema.org/understanding-json-schema/reference/const +.. _#78: https://github.com/wolverdude/GenSON/issues/78 +.. _#25: https://github.com/wolverdude/GenSON/issues/25 .. _Python flavor of RegEx: https://docs.python.org/3.6/library/re.html .. _the code: https://github.com/wolverdude/GenSON/tree/master/genson/schema/strategies .. _minimum number: https://json-schema.org/understanding-json-schema/reference/numeric.html#range diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson/__init__.py new/genson-1.4.0/genson/__init__.py --- old/genson-1.3.0/genson/__init__.py 2024-05-15 23:58:17.000000000 +0200 +++ new/genson-1.4.0/genson/__init__.py 2026-07-06 10:21:13.000000000 +0200 @@ -2,7 +2,7 @@ from .schema.node import SchemaNode, SchemaGenerationError from .schema.strategies.base import SchemaStrategy, TypedSchemaStrategy -__version__ = '1.3.0' +__version__ = '1.4.0' __all__ = [ 'SchemaBuilder', 'SchemaNode', diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson/__main__.py new/genson-1.4.0/genson/__main__.py --- old/genson-1.3.0/genson/__main__.py 2024-05-15 02:52:06.000000000 +0200 +++ new/genson-1.4.0/genson/__main__.py 2026-07-06 10:21:13.000000000 +0200 @@ -13,7 +13,7 @@ def run(self): if not self.args.schema and not self.args.object: - self.fail('noting to do - no schemas or objects given') + self.fail('nothing to do - no schemas or objects given') self.add_schemas() self.add_objects() self.print_output() diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson/schema/builder.py new/genson-1.4.0/genson/schema/builder.py --- old/genson-1.3.0/genson/schema/builder.py 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/genson/schema/builder.py 2026-07-06 10:21:13.000000000 +0200 @@ -14,10 +14,8 @@ for base in bases: schema_strategies += list(getattr(base, 'STRATEGIES', [])) - unique_schema_strategies = [] - for schema_strategy in schema_strategies: - if schema_strategy not in unique_schema_strategies: - unique_schema_strategies.append(schema_strategy) + # dict.fromkeys() dedupes in O(n) while preserving order + unique_schema_strategies = list(dict.fromkeys(schema_strategies)) cls.STRATEGIES = tuple(unique_schema_strategies) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson/schema/strategies/__init__.py new/genson-1.4.0/genson/schema/strategies/__init__.py --- old/genson-1.3.0/genson/schema/strategies/__init__.py 2021-04-18 17:30:13.000000000 +0200 +++ new/genson-1.4.0/genson/schema/strategies/__init__.py 2026-07-06 10:21:13.000000000 +0200 @@ -10,6 +10,7 @@ String ) from .array import List, Tuple +from .enum import Enum from .object import Object BASIC_SCHEMA_STRATEGIES = ( @@ -19,7 +20,8 @@ String, List, Tuple, - Object + Object, + Enum, ) __all__ = ( @@ -33,5 +35,6 @@ 'Tuple', 'Object', 'Typeless', + 'Enum', 'BASIC_SCHEMA_STRATEGIES' ) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson/schema/strategies/enum.py new/genson-1.4.0/genson/schema/strategies/enum.py --- old/genson-1.3.0/genson/schema/strategies/enum.py 1970-01-01 01:00:00.000000000 +0100 +++ new/genson-1.4.0/genson/schema/strategies/enum.py 2026-07-06 10:21:13.000000000 +0200 @@ -0,0 +1,60 @@ +from .base import SchemaStrategy + + +class Enum(SchemaStrategy): + """ + strategy for 'enum' schemas. Merges the 'enum' types into one set and then + returns a schema with 'enum' set to the corresponding list. + """ + + KEYWORDS = ("enum",) + + def __init__(self, node_class): + super().__init__(node_class) + # Use set to easily merge 'enum's from different schemas. + self._enum = set() + # Apply different matching logic depending on whether schema exists or + # not. Give the Enum strategy preference over other strategies. So + # there's no way the Enum will get created unless it was explicitly + # asked for by a schema, and this behavior is not order- or + # type-dependent. + self.match_object = self._instance_match_object + + @staticmethod + def match_object(obj): + # Exclude the strategy from the basic object matching. It must be + # explicitly selected by a schema. + return False + + def _instance_match_object(self, obj): + # The strategy is selected by a schema. Give the Enum strategy + # preference over all other strategies. + return True + + @staticmethod + def match_schema(schema): + return "enum" in schema + + def add_schema(self, schema): + super().add_schema(schema) + if self._enum == set(): + self._enum = set(schema.get("enum")) + elif "enum" in schema: + self._enum.update(schema["enum"]) + + def add_object(self, obj): + super().add_object(obj) + # Add only scalar types. Technically, the JSON-Schema spec allows + # any type in an enum list, but using objects and lists is a very + # rare use-case. + if not isinstance(obj, (bool, str, int, float, type(None))): + raise TypeError(f"Unsupported enum type of {type(obj)}. " + "Scalar type is expected.") + # Convert to list to unify processing of string and other types. + self._enum.update([obj]) + + def to_schema(self): + schema = super().to_schema() + # Revert set back to list + schema["enum"] = list(self._enum) + return schema diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson/schema/strategies/object.py new/genson-1.4.0/genson/schema/strategies/object.py --- old/genson-1.3.0/genson/schema/strategies/object.py 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/genson/schema/strategies/object.py 2026-07-06 10:21:13.000000000 +0200 @@ -70,13 +70,6 @@ if search(pattern, prop): return pattern - def _add(self, items, func): - while len(self._items) < len(items): - self._items.append(self._schema_node_class()) - - for subschema, item in zip(self._items, items): - getattr(subschema, func)(item) - def to_schema(self): schema = super().to_schema() schema['type'] = 'object' diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson/schema/strategies/scalar.py new/genson-1.4.0/genson/schema/strategies/scalar.py --- old/genson-1.3.0/genson/schema/strategies/scalar.py 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/genson/schema/strategies/scalar.py 2026-07-06 10:21:13.000000000 +0200 @@ -69,6 +69,7 @@ self._type = 'number' def add_object(self, obj): + super().add_object(obj) if isinstance(obj, float): self._type = 'number' diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson.egg-info/PKG-INFO new/genson-1.4.0/genson.egg-info/PKG-INFO --- old/genson-1.3.0/genson.egg-info/PKG-INFO 2024-05-15 23:58:38.000000000 +0200 +++ new/genson-1.4.0/genson.egg-info/PKG-INFO 2026-07-06 10:21:23.000000000 +0200 @@ -1,9 +1,8 @@ -Metadata-Version: 2.1 +Metadata-Version: 2.4 Name: genson -Version: 1.3.0 +Version: 1.4.0 Summary: GenSON is a powerful, user-friendly JSON Schema generator. Home-page: https://github.com/wolverdude/genson/ -Download-URL: https://github.com/wolverdude/GenSON/tarball/v0.2s.0 Author: Jon Wolverton Author-email: [email protected] License: MIT @@ -16,18 +15,20 @@ Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: File Formats :: JSON :: JSON Schema Classifier: Topic :: Software Development :: Code Generators Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Utilities +Requires-Python: >=3.10 Description-Content-Type: text/x-rst License-File: LICENSE License-File: AUTHORS.rst +Dynamic: license-file GenSON ====== @@ -39,12 +40,20 @@ GenSON's core function is to take JSON objects and generate schemas that describe them, but it is unique in its ability to *merge* schemas. It was originally built to describe the common structure of a large number of JSON objects, and it uses its merging ability to generate a single schema from any number of JSON objects and/or schemas. + +GenSON's Guiding Rules +---------------------- + GenSON's schema builder follows these three rules: 1. *Every* object it is given must validate under the generated schema. 2. *Any* object that is valid under *any* schema it is given must also validate under the generated schema. (there is one glaring exception to this, detailed `below`_) 3. The generated schema should be as strict as possible given the first 2 rules. +There are of course a number of gotchas and edge-cases that GenSON tries to resolve, but doesn't always do it the way that you want. For example, inputs of the same broad type always *merge* into a single schema: two object inputs become one object schema with the union of their properties, never an ``anyOf`` of the two. GenSON only reaches for ``anyOf`` when it encounters fundamentally different structures, like an object and an array. + +GenSON is extensible, making it possible for you to make a different choice in many of these cases. In the case above, if you want alternatives kept separate, generate a schema per shape using separate builders and combine them yourself with ``{"anyOf": [...]}``. + JSON Schema Implementation -------------------------- @@ -62,6 +71,7 @@ * ``"patternProperties"`` * ``"required"`` * ``"anyOf"`` +* ``"enum"`` (only with a `seed schema <#seeding-enums>`__) You should be aware that this limited vocabulary could cause GenSON to violate rules 1 and 2. If you feed it schemas with advanced keywords, it will just blindly pass them on to the final schema. Note that ``"$ref"`` and ``id`` are also not supported, so GenSON will not dereference linked nodes when building a schema. @@ -133,10 +143,12 @@ >>> from genson import SchemaBuilder >>> builder = SchemaBuilder() - >>> builder.add_schema({"type": "object", "properties": {}}) + + >>> # Add some objects to infer their schema. >>> builder.add_object({"hi": "there"}) >>> builder.add_object({"hi": 5}) + >>> # Export the schema as a Python dict. >>> builder.to_schema() {'$schema': 'http://json-schema.org/schema#', 'type': 'object', @@ -144,6 +156,15 @@ 'hi': {'type': ['integer', 'string']}}, 'required': ['hi']} + >>> # Merge in another schema. + >>> builder.add_schema({ + "type": "object", + "properties": { + "hi": {"type": "boolean"} + } + }) + + >>> # Export the schema as a JSON string. >>> print(builder.to_json(indent=2)) { "$schema": "http://json-schema.org/schema#", @@ -151,6 +172,7 @@ "properties": { "hi": { "type": [ + "boolean", "integer", "string" ] @@ -321,6 +343,42 @@ * If a key matches multiple patterns, there is *no guarantee* of which one will be updated. * The patternProperties_ docs themselves have some more useful pointers that can save you time. +Seeding required +++++++++++++++++ + +GenSON sets ``required`` to the keys that have appeared in *every* object it has seen, and once that intersection is empty, it drops ``required`` from the output entirely rather than emitting an empty list. To force an empty ``required`` into the output, seed the builder with one: ``{"type": "object", "required": []}``. + +.. warning:: + This matters when merging one ``SchemaBuilder`` into another, because the hand-off goes through ``to_schema()``. An unseeded builder whose ``required`` has *become* empty serializes without ``required``, so the receiving builder can diverge from the original as more schemas are added. Seeding both builders with ``"required": []`` prevents this. See issues `#78`_ and `#25`_ for the full story. + +Seeding enums ++++++++++++++ + +Support for enum_ is new in version 1.4. GenSON never infers an ``enum`` on its own; you activate it per node by seeding that node with a schema containing the ``enum`` keyword (an empty list is fine). Once activated, the node records every value it encounters — deduplicated — instead of inferring a type. + +.. code-block:: python + + >>> from genson import SchemaBuilder + + >>> builder = SchemaBuilder() + >>> builder.add_schema({'type': 'object', 'properties': { + ... 'status': {'enum': []}}}) + >>> builder.add_object({'status': 'active'}) + >>> builder.add_object({'status': 'inactive'}) + >>> builder.add_object({'status': 'active'}) + >>> builder.to_schema() + {'$schema': 'http://json-schema.org/schema#', + 'type': 'object', + 'properties': {'status': {'enum': ['inactive', 'active']}}, + 'required': ['status']} + +Some things to be aware of: + +* Values are merged as a set, so the order of the output list is *not* guaranteed. +* Only scalar values (strings, numbers, booleans, and ``null``) are supported. Feeding a list or object to an enum node raises a ``TypeError``. (The JSON-Schema spec technically allows non-scalar enum values, but this is a rare use-case; if you need it, extend the ``Enum`` strategy.) +* An activated enum node captures *all* values it sees, taking precedence over the typed strategies. +* There is no direct support for const_, but it's easy to get there from here: seed the node with ``enum``, and if exactly one value comes back, replace ``{"enum": [value]}`` with ``{"const": value}`` yourself. + Typeless Schemas ++++++++++++++++ @@ -525,6 +583,29 @@ >>> picky_builder.add_object(None) # this fails genson.schema.node.SchemaGenerationError: Could not find matching schema type for object: None +Example: ``NoRequiredObject`` ++++++++++++++++++++++++++++++ + +Custom strategies can also *remove* keywords. A common request is to leave ``required`` out of generated schemas entirely, so that objects with missing keys still validate: + +.. code-block:: python + + from genson import SchemaBuilder + from genson.schema.strategies import Object + + class NoRequiredObject(Object): + # drop 'required' from the list of handled keywords + KEYWORDS = tuple(kw for kw in Object.KEYWORDS if kw != 'required') + + def to_schema(self): + schema = super().to_schema() + schema.pop('required', None) + return schema + + class NoRequiredSchemaBuilder(SchemaBuilder): + """ generates schemas without the 'required' keyword """ + EXTRA_STRATEGIES = (NoRequiredObject,) + Contributing ------------ @@ -536,7 +617,7 @@ 3. Lint your code with `Flake8`_. 4. Run `tox`_ to make sure the test suite passes. 5. Ensure the docs are accurate. -6. Add your name to the list of contributers. +6. Add your name to the list of contributors. 7. Submit a Pull Request. Tests @@ -585,6 +666,10 @@ .. _below: #typeless-schemas .. _array validation here: https://spacetelescope.github.io/understanding-json-schema/reference/array.html#items .. _patternProperties: https://spacetelescope.github.io/understanding-json-schema/reference/object.html#pattern-properties +.. _enum: https://json-schema.org/understanding-json-schema/reference/enum +.. _const: https://json-schema.org/understanding-json-schema/reference/const +.. _#78: https://github.com/wolverdude/GenSON/issues/78 +.. _#25: https://github.com/wolverdude/GenSON/issues/25 .. _Python flavor of RegEx: https://docs.python.org/3.6/library/re.html .. _the code: https://github.com/wolverdude/GenSON/tree/master/genson/schema/strategies .. _minimum number: https://json-schema.org/understanding-json-schema/reference/numeric.html#range @@ -596,6 +681,25 @@ History ======= +1.4.0 +----- + +* add ``enum`` support, activated per node by seed schemas (PR #82 — thanks @tokarenko; closes #46, #81) +* **Performance**: strategy deduplication when defining custom ``SchemaBuilder`` classes is now O(n) instead of O(n²) (PR #91 — thanks @Bitshifter-9; fixes #90) +* include the complete, runnable test suite in the source distribution (PR #94 — thanks @mgorny) +* **Bugfix**: fix "noting to do" typo in the CLI error message and remove dead code (PR #93 — thanks @est) +* **Docs**: document the ``required``-dropping behavior and the builder-merge gotcha (#78, #25); explain why same-type inputs merge rather than producing ``anyOf``; add a ``NoRequiredObject`` example for suppressing ``required`` (#37, #60) +* declare ``python_requires >= 3.10``, matching the tested Python versions + +1.3.1 +----- + +* **Bugfix**: include the ``genson.schema`` subpackage in the package build; installing v1.3.0 from a wheel failed with ``ModuleNotFoundError`` (fixes #80, #92) +* **Bugfix**: call ``super().add_object()`` in the ``Number`` strategy so subclass hooks run (PR #79) +* add Python 3.13 and 3.14 to the test matrix and classifiers; drop EOL Python 3.7–3.9 (the package itself is unchanged and older Pythons may still work, but they are no longer tested) +* migrate CI from Travis to GitHub Actions; releases are now published via PyPI trusted publishing +* **Tests**: CLI integration tests use ``sys.executable`` (PR #84) and no longer depend on the test runner having an interactive stdin + 1.3.0 ----- diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/genson.egg-info/SOURCES.txt new/genson-1.4.0/genson.egg-info/SOURCES.txt --- old/genson-1.3.0/genson.egg-info/SOURCES.txt 2024-05-15 23:58:38.000000000 +0200 +++ new/genson-1.4.0/genson.egg-info/SOURCES.txt 2026-07-06 10:21:23.000000000 +0200 @@ -1,5 +1,3 @@ -.gitignore -.travis.yml AUTHORS.rst HISTORY.rst LICENSE @@ -8,7 +6,6 @@ pyproject.toml setup.cfg setup.py -tox.ini genson/__init__.py genson/__main__.py genson.egg-info/PKG-INFO @@ -23,10 +20,12 @@ genson/schema/strategies/__init__.py genson/schema/strategies/array.py genson/schema/strategies/base.py +genson/schema/strategies/enum.py genson/schema/strategies/object.py genson/schema/strategies/scalar.py test/__init__.py test/base.py +test/sort.py test/test_add_multi.py test/test_add_single.py test/test_bin.py diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/setup.cfg new/genson-1.4.0/setup.cfg --- old/genson-1.3.0/setup.cfg 2024-05-15 23:58:38.929251000 +0200 +++ new/genson-1.4.0/setup.cfg 2026-07-06 10:21:23.742352200 +0200 @@ -11,7 +11,6 @@ json, schema, json-schema, jsonschema, object, generate generator, builder, merge, draft 7, validate, validation url = https://github.com/wolverdude/genson/ -download_url = https://github.com/wolverdude/GenSON/tarball/v0.2s.0 classifiers = Development Status :: 5 - Production/Stable Environment :: Console @@ -21,21 +20,25 @@ Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 3 - Programming Language :: Python :: 3.7 - Programming Language :: Python :: 3.8 - Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Programming Language :: Python :: 3.12 + Programming Language :: Python :: 3.13 + Programming Language :: Python :: 3.14 + Topic :: File Formats :: JSON :: JSON Schema Topic :: Software Development :: Code Generators Topic :: Software Development :: Libraries :: Python Modules Topic :: Utilities [options] -packages = genson +packages = find: +python_requires = >=3.10 zip_safe = True include_package_data = True +[options.packages.find] +include = genson* + [options.entry_points] console_scripts = genson = genson.__main__:main diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/test/base.py new/genson-1.4.0/test/base.py --- old/genson-1.3.0/test/base.py 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/test/base.py 2026-07-06 10:21:13.000000000 +0200 @@ -2,6 +2,7 @@ import unittest import jsonschema from genson import SchemaNode, SchemaBuilder +from .sort import sort_lists_in_schema PYTHON_VERSION = sys.version[:sys.version.find(' ')] @@ -31,9 +32,14 @@ with self.assertRaises(jsonschema.exceptions.ValidationError): jsonschema.Draft7Validator(self.builder.to_schema()).validate(obj) - def assertResult(self, expected, enforceUserContract=True): + def assertResult(self, expected, enforceUserContract=True, + ignore_order=False): + actual = self.builder.to_schema() + if ignore_order: + sort_lists_in_schema(actual) + sort_lists_in_schema(expected) self.assertEqual( - expected, self.builder.to_schema(), + expected, actual, 'Generated schema (below) does not match expected (above)') if enforceUserContract: self.assertUserContract() diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/test/sort.py new/genson-1.4.0/test/sort.py --- old/genson-1.3.0/test/sort.py 1970-01-01 01:00:00.000000000 +0100 +++ new/genson-1.4.0/test/sort.py 2026-07-06 10:21:13.000000000 +0200 @@ -0,0 +1,21 @@ +def sort_lists_in_schema(schema): + """ + Recursively traverses a schema and sorts any lists it finds. + The sorting is stable and works on lists with mixed types. + """ + if isinstance(schema, dict): + for key, value in schema.items(): + schema[key] = sort_lists_in_schema(value) + return schema + elif isinstance(schema, list): + new_list = [sort_lists_in_schema(item) for item in schema] + try: + return sorted(new_list) + except TypeError: + # This handles mixed types by creating a tuple of the type + # name and the value. This ensures that types are grouped + # together and then sorted. + # It's safe to use str() here since only malformed custom + # objects could cause it to fail. + return sorted(new_list, key=lambda x: (type(x).__name__, str(x))) + return schema diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/test/test_bin.py new/genson-1.4.0/test/test_bin.py --- old/genson-1.3.0/test/test_bin.py 2024-05-15 02:52:06.000000000 +0200 +++ new/genson-1.4.0/test/test_bin.py 2026-07-06 10:21:13.000000000 +0200 @@ -1,6 +1,7 @@ import unittest import json import os +import sys from subprocess import Popen, PIPE from genson import SchemaBuilder @@ -20,23 +21,35 @@ return '{}\ngenson: error: {}\n'.format(SHORT_USAGE, message) -def run(args=tuple(), stdin_data=None): +def run(args=tuple(), stdin_data=None, tty_stdin=False): """ Run the ``genson`` executable as a subprocess and return - (stdout, stderr). + (stdout, stderr). ``tty_stdin`` attaches stdin to a pseudo-TTY so + the CLI treats the session as interactive; otherwise stdin is a + pipe (with ``stdin_data`` written to it, if given). """ - full_args = ['python', '-m', 'genson'] + full_args = [sys.executable, '-m', 'genson'] full_args.extend(args) env = os.environ.copy() env['COLUMNS'] = '80' # set width for deterministic text wrapping + if tty_stdin: + import pty + master_fd, slave_fd = pty.openpty() + stdin = slave_fd + else: + master_fd = slave_fd = None + stdin = PIPE if stdin_data is not None else None + genson_process = Popen( - full_args, env=env, stdout=PIPE, stderr=PIPE, - stdin=PIPE if stdin_data is not None else None) + full_args, env=env, stdout=PIPE, stderr=PIPE, stdin=stdin) if stdin_data is not None: stdin_data = stdin_data.encode('utf-8') (stdout, stderr) = genson_process.communicate(stdin_data) genson_process.wait() + if slave_fd is not None: + os.close(slave_fd) + os.close(master_fd) if isinstance(stdout, bytes): stdout = stdout.decode('utf-8') @@ -81,20 +94,35 @@ 'invalid JSON in %s: Expecting value: line 1 column 1 (char 0)' % BAD_JSON_FILE) + def assertEqualIgnoreWhitespace( + self, + first: str, + second: str, + msg: "str|None" = None, + ): + return self.assertEqual( + " ".join(first.split()), + " ".join(second.split()), + msg=msg + ) + + @unittest.skipUnless(os.name == 'posix', 'pty requires a POSIX system') def test_no_input(self): - (stdout, stderr) = run() - self.assertEqual(stderr, stderr_message( - 'noting to do - no schemas or objects given')) + # attach a pseudo-TTY so the CLI sees an interactive session + # with no piped input rather than inheriting the runner's stdin + (stdout, stderr) = run(tty_stdin=True) + self.assertEqualIgnoreWhitespace(stderr, stderr_message( + 'nothing to do - no schemas or objects given')) self.assertEqual(stdout, '') def test_object_not_json(self): (stdout, stderr) = run([self.BAD_JSON_FILE]) - self.assertEqual(stderr, self.BAD_JSON_MESSAGE) + self.assertEqualIgnoreWhitespace(stderr, self.BAD_JSON_MESSAGE) self.assertEqual(stdout, '') def test_schema_not_json(self): (stdout, stderr) = run(['-s', self.BAD_JSON_FILE]) - self.assertEqual(stderr, self.BAD_JSON_MESSAGE) + self.assertEqualIgnoreWhitespace(stderr, self.BAD_JSON_MESSAGE) self.assertEqual(stdout, '') diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/test/test_builder.py new/genson-1.4.0/test/test_builder.py --- old/genson-1.3.0/test/test_builder.py 2023-05-11 00:13:59.000000000 +0200 +++ new/genson-1.4.0/test/test_builder.py 2026-07-06 10:21:13.000000000 +0200 @@ -3,6 +3,7 @@ SCHEMA_URI = 'https://json-schema.org/draft/2020-12/schema' + class TestParams(base.SchemaBuilderTestCase): def test_uri(self): diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/test/test_custom.py new/genson-1.4.0/test/test_custom.py --- old/genson-1.3.0/test/test_custom.py 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/test/test_custom.py 2026-07-06 10:21:13.000000000 +0200 @@ -1,5 +1,7 @@ +import unittest from genson import SchemaBuilder -from genson.schema.strategies import SchemaStrategy, Number +from genson.schema.strategies import ( + SchemaStrategy, Number, BASIC_SCHEMA_STRATEGIES) from . import base @@ -56,6 +58,31 @@ 'maximum': 10}) +class DuplicateStrategiesSchemaBuilder(SchemaBuilder): + """many duplicate strategies to exercise deduplication""" + EXTRA_STRATEGIES = BASIC_SCHEMA_STRATEGIES * 100 + + +class TestStrategyDeduplication(unittest.TestCase): + + def test_deduplicates_strategies(self): + strategies = DuplicateStrategiesSchemaBuilder.STRATEGIES + self.assertEqual(len(strategies), len(set(strategies))) + + def test_preserves_first_occurrence_order(self): + self.assertEqual(DuplicateStrategiesSchemaBuilder.STRATEGIES, + tuple(BASIC_SCHEMA_STRATEGIES)) + + def test_extra_strategies_keep_priority(self): + # EXTRA_STRATEGIES stay ahead of the inherited strategies even + # when they duplicate each other + class DupExtra(SchemaBuilder): + EXTRA_STRATEGIES = (MaxTenStrategy, MaxTenStrategy) + + self.assertIs(DupExtra.STRATEGIES[0], MaxTenStrategy) + self.assertEqual(DupExtra.STRATEGIES.count(MaxTenStrategy), 1) + + class TestClobberStrategies(base.SchemaNodeTestCase): CLASS = FalseSchemaBuilder diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/test/test_seed_schema.py new/genson-1.4.0/test/test_seed_schema.py --- old/genson-1.3.0/test/test_seed_schema.py 2023-03-25 21:01:59.000000000 +0100 +++ new/genson-1.4.0/test/test_seed_schema.py 2026-07-06 10:21:13.000000000 +0200 @@ -8,6 +8,18 @@ self.add_object([None]) self.assertResult({'type': 'array', 'items': [{'type': 'null'}]}) + def test_empty_tuple(self): + # an empty tuple seed is padded to one empty item schema; a + # zero-length `items` array would be invalid under every draft + # of the meta-schema (see the discussion on issue #90) + self.add_schema({'type': 'array', 'items': []}) + self.assertResult({'type': 'array', 'items': [{}]}) + + def test_empty_tuple_merge(self): + self.add_schema({'type': 'array', 'items': []}) + self.add_schema({'type': 'array', 'items': []}) + self.assertResult({'type': 'array', 'items': [{}]}) + class TestPatternProperties(base.SchemaNodeTestCase): @@ -64,3 +76,32 @@ 'properties': {'a': {'type': 'boolean'}}, 'patternProperties': {r'^\d$': {'type': 'integer'}}, 'required': ['a']}) + + +class TestEnum(base.SchemaNodeTestCase): + + def test_enum_scalar_string(self): + self.add_schema({"enum": []}) + self.add_object("1") + self.assertResult({"enum": ["1"]}) + + def test_enum_scalar_list(self): + self.add_schema({"enum": ["1", 2]}) + self.add_object("34") + self.add_object(5) + self.add_object(6.7) + self.add_object(False) + self.add_object(None) + self.assertResult( + {"enum": ["1", 2, "34", 5, 6.7, False, None]}, + enforceUserContract=False, + ignore_order=True, + ) + + def test_enum_repeated_item(self): + self.add_schema({"enum": []}) + self.add_object(1) + self.add_object(1) + self.add_object(2) + self.add_object(1) + self.assertResult({"enum": [1, 2]}, ignore_order=True) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/genson-1.3.0/tox.ini new/genson-1.4.0/tox.ini --- old/genson-1.3.0/tox.ini 2024-05-15 22:27:09.000000000 +0200 +++ new/genson-1.4.0/tox.ini 1970-01-01 01:00:00.000000000 +0100 @@ -1,11 +0,0 @@ -[tox] -envlist = py3{7,8,9,10,11,12} -skip_missing_interpreters = true - -[testenv] -deps = - jsonschema>=4.0.0 - coverage -commands = - coverage run --source=genson -m unittest - coverage report --omit='*/__main__.py' --fail-under=90
