pax_global_header00006660000000000000000000000064147371523340014523gustar00rootroot0000000000000052 comment=7c07653643a1bd7a0546b50cd8954ede236f25be voluptuous-openapi-0.0.6/000077500000000000000000000000001473715233400154245ustar00rootroot00000000000000voluptuous-openapi-0.0.6/.github/000077500000000000000000000000001473715233400167645ustar00rootroot00000000000000voluptuous-openapi-0.0.6/.github/dependabot.yml000066400000000000000000000004101473715233400216070ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: daily open-pull-requests-limit: 10 - package-ecosystem: pip directory: "/" schedule: interval: weekly open-pull-requests-limit: 10 voluptuous-openapi-0.0.6/.github/release-drafter.yml000066400000000000000000000002221473715233400225500ustar00rootroot00000000000000categories: - title: "⬆️ Dependencies" collapse-after: 1 labels: - "dependencies" template: | ## What's Changed $CHANGES voluptuous-openapi-0.0.6/.github/workflows/000077500000000000000000000000001473715233400210215ustar00rootroot00000000000000voluptuous-openapi-0.0.6/.github/workflows/ci.yml000066400000000000000000000016161473715233400221430ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Run Tests on: push: branches: [master] pull_request: branches: [master] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4.2.2 - name: Set up Python 3.12 uses: actions/setup-python@v5.3.0 with: python-version: 3.12 - name: Install dependencies run: | pip install -r requirements_test.txt pip install -e . - name: Lint with flake8 run: | flake8 voluptuous_openapi - name: Test with pytest run: | pytest tests - name: Check formatting with black run: | black voluptuous_openapi tests --check voluptuous-openapi-0.0.6/.github/workflows/pythonpublish.yml000066400000000000000000000015251473715233400244570ustar00rootroot00000000000000# This workflows will upload a Python Package using Twine when a release is created # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries name: Upload Python Package on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4.2.2 - name: Set up Python uses: actions/setup-python@v5.3.0 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine - name: Build and publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | python setup.py sdist bdist_wheel twine upload dist/* voluptuous-openapi-0.0.6/.github/workflows/release-drafter.yml000066400000000000000000000005141473715233400246110ustar00rootroot00000000000000name: Release Drafter on: push: branches: - master jobs: update_release_draft: runs-on: ubuntu-latest steps: # Drafts your next Release notes as Pull Requests are merged into "master" - uses: release-drafter/release-drafter@v6.0.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} voluptuous-openapi-0.0.6/.gitignore000066400000000000000000000021211473715233400174100ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # IPython Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv venv/ ENV/ bin/ pip-selfcheck.json pyvenv.cfg # Spyder project settings .spyderproject # Rope project settings .ropeproject # py.test .pytest_cachevoluptuous-openapi-0.0.6/.vscode/000077500000000000000000000000001473715233400167655ustar00rootroot00000000000000voluptuous-openapi-0.0.6/.vscode/settings.json000066400000000000000000000002001473715233400215100ustar00rootroot00000000000000{ "python.testing.pytestArgs": ["tests"], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true } voluptuous-openapi-0.0.6/LICENSE000066400000000000000000000261221473715233400164340ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 Paulus Schoutsen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. voluptuous-openapi-0.0.6/MANIFEST.in000066400000000000000000000000431473715233400171570ustar00rootroot00000000000000include tests/*.py include LICENSE voluptuous-openapi-0.0.6/README.md000066400000000000000000000024501473715233400167040ustar00rootroot00000000000000# Voluptuous OpenAPI Convert Voluptuous schemas to [OpenAPI Schema object](https://spec.openapis.org/oas/v3.0.3#schema-object). ```python schema = {} schema[vol.Required('name')] = vol.All(str, vol.Length(min=5)) schema[vol.Required('age', description='Age in full years')] = vol.All(vol.Coerce(int), vol.Range(min=18)) schema[vol.Optional('hobby', default='not specified')] = str schema = vol.Schema(schema) ``` becomes ```json { "type": "object", "properties": { "name": { "type": "string", "minLength": 5, }, "age": { "type": "integer", "minimum": 18, "description": "Age in full years", }, "hobby": { "type": "string", "default": "not specified", }, }, "required": ["name", "age"], } ``` See the tests for more examples. ## Custom serializer You can pass a custom serializer to be able to process custom validators. If the serializer returns `UNSUPPORTED`, it will return to normal processing. Example: ```python from voluptuous_openai import UNSUPPORTED, convert def custom_convert(value): if value is my_custom_validator: return {'pattern': '^[a-zA-Z0-9]$'} return UNSUPPORTED convert(value, custom_serializer=custom_convert) ``` voluptuous-openapi-0.0.6/requirements_test.txt000066400000000000000000000001131473715233400217420ustar00rootroot00000000000000pytest==8.3.4 flake8==7.1.1 black==24.10.0 openapi-schema-validator==0.6.2 voluptuous-openapi-0.0.6/script/000077500000000000000000000000001473715233400167305ustar00rootroot00000000000000voluptuous-openapi-0.0.6/script/bootstrap000077500000000000000000000003561473715233400206770ustar00rootroot00000000000000#!/bin/sh # Resolve all dependencies that the application requires to run. # Stop on errors set -e cd "$(dirname "$0")/.." echo "Installing test and release dependencies..." python3 -m pip install pytest pylint flake8 pydocstyle twine voluptuous-openapi-0.0.6/script/release000077500000000000000000000002261473715233400202760ustar00rootroot00000000000000#!/bin/sh # Pushes a new version to PyPi. cd "$(dirname "$0")/.." rm -rf dist python3 setup.py sdist python3 -m twine upload dist/* --skip-existing voluptuous-openapi-0.0.6/script/setup000077500000000000000000000001711473715233400200150ustar00rootroot00000000000000#!/bin/sh # Setups the repository. # Stop on errors set -e cd "$(dirname "$0")/.." script/bootstrap pip3 install -e . voluptuous-openapi-0.0.6/setup.cfg000066400000000000000000000005261473715233400172500ustar00rootroot00000000000000[tool:pytest] testpaths = tests norecursedirs = .git [flake8] # To work with Black # E501: line too long # W503: Line break occurred before a binary operator # E203: Whitespace before ':' # D202 No blank lines allowed after function docstring # W504 line break after binary operator ignore = E501, W503, E203, D202, W504 voluptuous-openapi-0.0.6/setup.py000066400000000000000000000006521473715233400171410ustar00rootroot00000000000000from setuptools import setup setup( name="voluptuous-openapi", version="0.0.6", description="Convert voluptuous schemas to OpenAPI Schema object", url="https://github.com/home-assistant-libs/voluptuous-openapi", author="Denis Shulyaka", author_email="Shulyaka@gmail.com", license="Apache License 2.0", install_requires=["voluptuous"], packages=["voluptuous_openapi"], zip_safe=True, ) voluptuous-openapi-0.0.6/tests/000077500000000000000000000000001473715233400165665ustar00rootroot00000000000000voluptuous-openapi-0.0.6/tests/test_lib.py000066400000000000000000000354161473715233400207560ustar00rootroot00000000000000from enum import Enum from typing import Any, TypeVar import pytest import voluptuous as vol from voluptuous_openapi import UNSUPPORTED, convert, convert_to_voluptuous def test_int_schema(): for value in int, vol.Coerce(int): assert {"type": "integer"} == convert(vol.Schema(value)) def test_str_schema(): for value in str, vol.Coerce(str): assert {"type": "string"} == convert(vol.Schema(value)) def test_float_schema(): for value in float, vol.Coerce(float): assert {"type": "number"} == convert(vol.Schema(value)) def test_bool_schema(): for value in bool, vol.Coerce(bool): assert {"type": "boolean"} == convert(vol.Schema(value)) def test_integer_clamp(): assert { "type": "integer", "minimum": 100, "maximum": 1000, } == convert(vol.Schema(vol.All(vol.Coerce(int), vol.Clamp(min=100, max=1000)))) def test_length(): assert { "type": "string", "minLength": 100, "maxLength": 1000, } == convert(vol.Schema(vol.All(vol.Coerce(str), vol.Length(min=100, max=1000)))) def test_datetime(): assert { "type": "string", "format": "date-time", } == convert(vol.Schema(vol.Datetime())) def test_in(): assert {"type": "string", "enum": ["beer", "wine"]} == convert( vol.Schema(vol.In(["beer", "wine"])) ) def test_in_integer(): assert {"type": "integer", "enum": [1, 2]} == convert(vol.Schema(vol.In([1, 2]))) def test_in_dict(): assert { "type": "string", "enum": ["en_US", "zh_CN"], } == convert( vol.Schema( vol.In({"en_US": "American English", "zh_CN": "Chinese (Simplified)"}) ) ) def test_dict(): assert { "type": "object", "properties": { "name": { "type": "string", "minLength": 5, }, "age": { "type": "integer", "minimum": 18, }, "hobby": { "type": "string", "default": "not specified", }, }, "required": ["name", "age"], } == convert( vol.Schema( { vol.Required("name"): vol.All(str, vol.Length(min=5)), vol.Required("age"): vol.All(vol.Coerce(int), vol.Range(min=18)), vol.Optional("hobby", default="not specified"): str, } ) ) assert {"type": "object", "additionalProperties": True} == convert(vol.Schema(dict)) assert {"type": "object", "additionalProperties": True} == convert( vol.Schema(dict[str, Any]) ) assert {"type": "object", "additionalProperties": {"type": "integer"}} == convert( vol.Schema({str: int}) ) assert { "type": "object", "properties": {"x": {"type": "integer"}}, "required": [], "additionalProperties": {"type": "string"}, } == convert(vol.Schema({"x": int, str: str})) assert {"type": "object", "properties": {}, "required": []} == convert( vol.Schema({}) ) def string(x: str) -> str: return x assert {"type": "object", "additionalProperties": {"type": "string"}} == convert( vol.Schema({string: string}) ) assert {"type": "object", "additionalProperties": True} == convert( vol.Schema(object) ) assert {"type": "object", "additionalProperties": True} == convert( vol.Schema({string: object}) ) def test_tuple(): assert {"type": "array", "items": {"type": "string"}} == convert(vol.Schema(tuple)) assert {"type": "array", "items": {"type": "string"}} == convert( vol.Schema(tuple[Any]) ) assert {"type": "array", "items": {"type": "integer"}} == convert( vol.Schema(tuple[int]) ) def test_marker_description(): assert { "type": "object", "properties": { "name": { "type": "string", "description": "Description of name", }, }, "required": ["name"], } == convert( vol.Schema( { vol.Required("name", description="Description of name"): str, } ) ) def test_lower(): assert { "type": "string", "format": "lower", } == convert(vol.Schema(vol.All(vol.Lower, str))) def test_upper(): assert { "type": "string", "format": "upper", } == convert(vol.Schema(vol.All(vol.Upper, str))) def test_capitalize(): assert { "type": "string", "format": "capitalize", } == convert(vol.Schema(vol.All(vol.Capitalize, str))) def test_title(): assert { "type": "string", "format": "title", } == convert(vol.Schema(vol.All(vol.Title, str))) def test_strip(): assert { "type": "string", "format": "strip", } == convert(vol.Schema(vol.All(vol.Strip, str))) def test_email(): assert { "type": "string", "format": "email", } == convert(vol.Schema(vol.All(vol.Email, str))) def test_url(): assert { "type": "string", "format": "url", } == convert(vol.Schema(vol.All(vol.Url, str))) def test_fqdnurl(): assert { "type": "string", "format": "fqdnurl", } == convert(vol.Schema(vol.All(vol.FqdnUrl, str))) def test_maybe(): assert { "type": "string", "nullable": True, } == convert(vol.Schema(vol.Maybe(str))) def test_custom_serializer(): def custem_serializer(schema): if schema is str: return {"pattern": "[A-Z]{1,8}\\.[A-Z]{3,3}", "type": "string"} return UNSUPPORTED assert { "type": "string", "pattern": "[A-Z]{1,8}\\.[A-Z]{3,3}", "format": "upper", } == convert( vol.Schema(vol.All(vol.Upper, str)), custom_serializer=custem_serializer ) def test_constant(): assert {"type": "boolean", "enum": [True]} == convert(vol.Schema(True)) assert {"type": "boolean", "enum": [False]} == convert(vol.Schema(False)) assert {"type": "string", "enum": ["Hello"]} == convert(vol.Schema("Hello")) assert {"type": "integer", "enum": [1]} == convert(vol.Schema(1)) assert {"type": "number", "enum": [1.5]} == convert(vol.Schema(1.5)) assert { "type": "object", "nullable": True, "description": "Must be null", } == convert(vol.Schema(None)) assert { "type": "object", "nullable": True, "description": "Must be null", } == convert(vol.Schema(type(None))) def test_enum(): class StringEnum(Enum): ONE = "one" TWO = "two" assert {"type": "string", "enum": ["one", "two"]} == convert( vol.Schema(vol.Coerce(StringEnum)) ) class IntEnum(Enum): ONE = 1 TWO = 2 assert {"type": "integer", "enum": [1, 2]} == convert( vol.Schema(vol.Coerce(IntEnum)) ) def test_list(): assert { "type": "array", "items": {"type": "string"}, } == convert(vol.Schema([str])) assert {"type": "array", "items": {"type": "string"}} == convert(vol.Schema(list)) assert {"type": "array", "items": {"type": "string"}} == convert( vol.Schema(list[Any]) ) assert {"type": "array", "items": {"type": "integer"}} == convert( vol.Schema(list[int]) ) def test_any_of(): assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert( vol.Any(float, int) ) assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert( vol.Any(float, int, float, int, int) ) assert {"type": "object", "additionalProperties": True} == convert( vol.Any(float, int, object) ) assert {"type": "integer", "nullable": True, "enum": [1, 2]} == convert( vol.Schema(vol.In([1, 2, None])) ) assert {"type": "integer", "enum": [1, 2, 3]} == convert( vol.Schema(vol.Any(1, 2, 3)) ) assert { "anyOf": [{"type": "number"}, {"type": "integer"}, {"type": "string"}] } == convert( vol.Any( vol.Any(float, int), vol.Any(int, float), vol.Any(float, vol.Any(int, str)) ) ) assert { "anyOf": [{"type": "number"}, {"type": "integer"}], "nullable": True, } == convert(vol.Any(vol.Maybe(float), vol.Maybe(int))) def test_all_of(): assert {"allOf": [{"minimum": 5}, {"minimum": 10}]} == convert( vol.All(vol.Range(min=5), vol.Range(min=10)) ) assert {"type": "string"} == convert(vol.All(object, str)) assert {"type": "object", "additionalProperties": {"type": "string"}} == convert( vol.All(object, {str: str}) ) assert {"maximum": 10, "minimum": 5, "type": "number"} == convert( vol.All(vol.Range(min=5), vol.Range(max=10)) ) assert {"maximum": 10, "minimum": 5, "type": "number"} == convert( vol.All( vol.All(vol.Range(min=5), float), vol.All(vol.All(vol.Range(max=10), float), float), ) ) def test_key_any(): assert { "type": "object", "properties": { "name": { "type": "string", }, "area": { "type": "string", "description": "The ID or the area", }, }, "required": [], } == convert( vol.Schema( { vol.Any( "name", vol.Optional("area", description="The ID or the area") ): str } ) ) assert { "properties": { "conversation_command": {"type": "string"}, "hours": {"type": "integer"}, "minutes": {"type": "integer"}, "name": {"type": "string"}, "seconds": {"type": "integer"}, }, "required": [], "type": "object", } == convert( { vol.Required(vol.Any("hours", "minutes", "seconds")): int, vol.Optional("name"): str, vol.Optional("conversation_command"): str, } ) def test_function(): def validator(data): return data assert { "type": "object", "properties": {"test_data": {"type": "string"}}, "required": [], } == convert(vol.Schema({"test_data": validator})) def validator_str(data: str): return data assert {"type": "string"} == convert(vol.Schema(validator_str)) def validator_any(data: Any): return data assert {} == convert(validator_any) assert {"type": "integer"} == convert(vol.All(vol.Coerce(int), lambda x: x / 100)) def validator_nullable(data: float | None): return data assert {"type": "number", "nullable": True} == convert( vol.Schema(validator_nullable) ) def validator_union(data: float | int): return data assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert( vol.Schema(validator_union) ) _T = TypeVar("_T") def validator_nullable_2(value: _T | None): return value assert { "type": "object", "properties": {"var": {"type": "array", "items": {"type": "string"}}}, "required": [], } == convert(vol.Schema({"var": vol.All(validator_nullable_2, [validator_any])})) def validator_list_int(value: list[int]): return value assert {"type": "array", "items": {"type": "integer"}} == convert( validator_list_int ) def validator_list_any(value: list[Any]): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_list_any) def validator_list(value: list): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_list) def validator_set_int(value: set[int]): return value assert {"type": "array", "items": {"type": "integer"}} == convert(validator_set_int) def validator_set_any(value: set[Any]): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_set_any) def validator_set(value: set): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_set) def validator_dict(value: dict): return value assert {"type": "object", "additionalProperties": True} == convert(validator_dict) def validator_dict_int(value: dict[str, int]): return value assert {"type": "object", "additionalProperties": {"type": "integer"}} == convert( validator_dict_int ) def test_nested_in_list(): assert { "properties": { "drink": { "type": "array", "items": {"type": "string", "enum": ["beer", "wine"]}, }, }, "required": [], "type": "object", } == convert(vol.Schema({vol.Optional("drink"): [vol.In(["beer", "wine"])]})) assert {"type": "integer", "enum": [1, 2, 3]} == convert( vol.Schema(vol.In([1, 2, 3])) ) def test_reverse_int_schema(): assert convert_to_voluptuous({"type": "integer"}) == int def test_reverse_str_schema(): assert convert_to_voluptuous({"type": "string"}) == str def test_reverse_float_schema(): assert convert_to_voluptuous({"type": "number"}) == float def test_reverse_bool_schema(): assert convert_to_voluptuous({"type": "boolean"}) == bool def test_reverse_datetime(): validator = convert_to_voluptuous( { "type": "string", "format": "date-time", } ) validator("2025-01-01T12:32:55.11Z") with pytest.raises(vol.Invalid): validator("2021-01-01") with pytest.raises(vol.Invalid): validator("abc") def test_reverse_unknown_type(): with pytest.raises(ValueError): convert_to_voluptuous({}) with pytest.raises(ValueError): convert_to_voluptuous({"type": "unknown"}) def test_convert_to_voluptuous_wrong_type() -> None: """Test calling with the wrong type""" with pytest.raises(ValueError): convert_to_voluptuous({"oneOf": ["integer"]}) with pytest.raises(ValueError): convert_to_voluptuous({"oneOf": "integer"}) with pytest.raises(ValueError): convert_to_voluptuous("a") def test_unsupported_features() -> None: """Test converting a mixed aray type.""" with pytest.raises(ValueError): convert_to_voluptuous({"type": "integer", "multipleOf": 2}) with pytest.raises(ValueError): convert_to_voluptuous({"type": "array", "items": {"minItems": 1}}) def test_mixed_type_list() -> None: """Test converting a mixed aray type.""" validator = convert_to_voluptuous( {"type": "array", "items": {"oneOf": [{"type": "string"}, {"type": "integer"}]}} ) validator(["a", "b"]) validator([1, 2]) validator(["a", 1, "b", 2]) with pytest.raises(vol.Invalid): validator("abc") with pytest.raises(vol.Invalid): validator(123) voluptuous-openapi-0.0.6/tests/test_validation.py000066400000000000000000000226511473715233400223370ustar00rootroot00000000000000"""Tests for voluptuous schema and openapi schemas that exercise validation code. Each test in this file defines an equivalent schema in both `openapi` and `voluptuous` formats. The schema is then converted to the other format and validation code is run against all variations of schema types. The motivation is because voluptuous schemas cannot be introspected directly and are tested by exercising with both valid and invalid data. """ from collections.abc import Callable, Generator import datetime import pytest import voluptuous as vol import openapi_schema_validator from typing import Any import logging from voluptuous_openapi import convert, convert_to_voluptuous from jsonschema.exceptions import ValidationError _LOGGER = logging.getLogger(__name__) # Validator type used to represent a validation function for a specific schema type Validator = Callable[[Any], Any] class InvalidFormat(Exception): """Validation exception thrown on invalid input test data.""" def voluptuous_validator(schema: vol.Schema) -> Validator: """Create a Validator for a voluptuous schema.""" def validator(data: Any) -> Any: try: _LOGGER.debug("Validating %s with schema %s", data, schema) return schema(data) except (vol.Invalid, ValueError) as e: raise InvalidFormat(str(e)) return validator def openapi_validator(schema: dict) -> Any: """Create a Validator for an OpenAPI schema.""" def validator(data: Any) -> Any: try: _LOGGER.debug("Validating %s with schema %s", data, schema) openapi_schema_validator.validate(data, schema) return data except ValidationError as e: raise InvalidFormat(str(e)) return validator # Order of id created by `generate_validators` TEST_IDS = ["openapi", "voluptuous", "voluptuous_to_openapi", "openapi_to_voluptuous"] def generate_validators( openapi_schema: dict, voluptuous_schema: vol.Schema ) -> Generator[Validator]: """Create validation functions for the various schema types.""" # Native schema validations yield openapi_validator(openapi_schema) yield voluptuous_validator(voluptuous_schema) # Converted schema validations yield openapi_validator(convert(voluptuous_schema)) yield voluptuous_validator(convert_to_voluptuous(openapi_schema)) @pytest.mark.parametrize( "validator", generate_validators( {"type": "string"}, str, ), ids=TEST_IDS, ) def test_string(validator: Validator) -> None: """Test string schema.""" validator("hello") validator("A" * 10) validator("A" * 12) validator("123") # Note voluptuos coerces everything to string but openapi does not, # so not validated here. @pytest.mark.parametrize( "validator", generate_validators( {"type": "string", "minLength": 1, "maxLength": 10}, vol.All(str, vol.Length(min=1, max=10)), ), ids=TEST_IDS, ) def test_string_min_max_length(validator: Validator) -> None: """Test string min and max length.""" validator("hello") validator("A" * 10) with pytest.raises(InvalidFormat): validator(123) with pytest.raises(InvalidFormat): validator("") with pytest.raises(InvalidFormat): validator("A" * 12) @pytest.mark.parametrize( "validator", generate_validators( {"type": "integer"}, int, ), ids=TEST_IDS, ) def test_int(validator: Validator) -> None: """Test int schema.""" validator(1) validator(10) validator(0) with pytest.raises(InvalidFormat): validator("abc") @pytest.mark.parametrize( "validator", generate_validators( {"type": "integer", "minimum": 1, "maximum": 10}, vol.All(int, vol.Range(min=1, max=10)), ), ids=TEST_IDS, ) def test_int_range(validator: Validator) -> None: """Test an int range""" validator(1) validator(10) with pytest.raises(InvalidFormat): validator(0) with pytest.raises(InvalidFormat): validator(11) with pytest.raises(InvalidFormat): validator(5.5) with pytest.raises(InvalidFormat): validator("abc") @pytest.mark.parametrize( "validator", generate_validators( {"type": "number"}, float, ), ids=TEST_IDS, ) def test_float(validator: Validator) -> None: """Test float schema.""" validator(1.0) validator(5.5) validator(10.0) with pytest.raises(InvalidFormat): validator("abc") @pytest.mark.parametrize( "validator", generate_validators( {"type": "number", "minimum": 1, "maximum": 10}, vol.All(float, vol.Range(min=1, max=10)), ), ids=TEST_IDS, ) def test_float_range(validator: Validator) -> None: """Test float range schema.""" validator(1.0) validator(5.5) validator(10.0) with pytest.raises(InvalidFormat): validator(0.0) with pytest.raises(InvalidFormat): validator(10.1) with pytest.raises(InvalidFormat): validator("abc") @pytest.mark.parametrize( "validator", generate_validators( {"type": "string", "pattern": r"^\d{3}-\d{2}-\d{4}$"}, vol.All(str, vol.Match(r"^\d{3}-\d{2}-\d{4}$")), ), ids=TEST_IDS, ) def test_match_pattern(validator: Validator) -> None: """Test matching a regular expression pattern.""" validator("555-10-2020") with pytest.raises(InvalidFormat): validator("555-1-2020") with pytest.raises(InvalidFormat): validator("555") with pytest.raises(InvalidFormat): validator("abc") @pytest.mark.parametrize( "validator", generate_validators( {"type": "array", "items": {"type": "string"}}, vol.All([str]), ), ids=TEST_IDS, ) def test_string_list(validator: Validator) -> None: """Test a list of strings.""" validator(["a"]) validator(["a", "b"]) with pytest.raises(InvalidFormat): validator("abc") with pytest.raises(InvalidFormat): validator(123) @pytest.mark.parametrize( "validator", generate_validators( { "type": "object", "properties": {"id": {"type": "integer"}, "name": {"type": "string"}}, "required": ["id"], }, vol.Schema({vol.Required("id"): int, vol.Optional("name"): str}), ), ids=TEST_IDS, ) def test_object(validator: Validator) -> None: """Test an object.""" validator({"id": 1, "name": "hello"}) validator({"id": 1}) with pytest.raises(InvalidFormat): validator({"id": "abc", "name": "hello"}) with pytest.raises(InvalidFormat): validator({"name": "hello"}) with pytest.raises(InvalidFormat): validator("abc") with pytest.raises(InvalidFormat): validator(123) @pytest.mark.parametrize( "validator", generate_validators( { "type": "object", "properties": { "id": {"type": "integer"}, "content": { "type": "object", "properties": { "name": {"type": "string"}, }, }, }, }, vol.Schema( { vol.Required("id"): int, vol.Optional("content"): vol.Schema({vol.Optional("name"): str}), } ), ), ids=TEST_IDS, ) def test_nested_object(validator: Validator) -> None: """Test an object nested in an object.""" validator({"id": 1, "content": {"name": "hello"}}) validator({"id": 1, "content": {}}) validator({"id": 1}) with pytest.raises(InvalidFormat): validator({"id": 1, "content": {"name": 1234}}) with pytest.raises(InvalidFormat): validator(123) @pytest.mark.parametrize( "validator", generate_validators( { "type": "object", "properties": {"id": {"type": "integer"}}, "additionalProperties": True, }, vol.Schema( {vol.Required("id"): int, vol.Optional("name"): str}, extra=vol.ALLOW_EXTRA ), ), ids=TEST_IDS, ) def test_allow_extra(validator: Validator) -> None: """Test additional properties are allowed.""" validator({"id": 1}) validator({"id": 1, "extra-key": "hello"}) with pytest.raises(InvalidFormat): validator(123) @pytest.mark.parametrize( "validator", generate_validators( { "type": "object", "properties": {"id": {"type": "integer"}}, "additionalProperties": False, }, vol.Schema({vol.Required("id"): int, vol.Optional("name"): str}), ), ids=TEST_IDS, ) def test_no_extra(validator: Validator) -> None: """Test additional properties are not allowed.""" validator({"id": 1}) # TODO: Note this does not currently fail when converting from openapi to voluptuous because # additionalProperties: False is not set. Fix that then uncomment here. # with pytest.raises(InvalidFormat): # validator({"id": 1, "extra-key": "hello"}) with pytest.raises(InvalidFormat): validator(123) @pytest.mark.parametrize( "validator", generate_validators( {"oneOf": [{"type": "string"}, {"type": "integer"}]}, vol.Any(str, int), ), ids=TEST_IDS, ) def test_one_of(validator: Validator) -> None: """Test oneOf multiple types.""" validator(1) validator(10) validator("hello") with pytest.raises(InvalidFormat): validator(1.4) voluptuous-openapi-0.0.6/voluptuous_openapi/000077500000000000000000000000001473715233400214045ustar00rootroot00000000000000voluptuous-openapi-0.0.6/voluptuous_openapi/__init__.py000066400000000000000000000365661473715233400235350ustar00rootroot00000000000000"""Module to convert voluptuous schemas to dictionaries.""" from collections.abc import Callable, Mapping, Sequence from inspect import signature from enum import Enum import re from typing import Any, TypeVar, Union, get_args, get_origin, get_type_hints from types import NoneType, UnionType import voluptuous as vol TYPES_MAP = { int: "integer", str: "string", float: "number", bool: "boolean", } TYPES_MAP_REV = {v: k for k, v in TYPES_MAP.items()} UNSUPPORTED = object() # These are not supported when converting from OpenAPI to voluptuous OPENAPI_UNSUPPORTED_KEYWORDS = { "anyOf", "allOf", "multipleOf", "minItems", "maxItems", "uniqueItems", } def convert(schema: Any, *, custom_serializer: Callable | None = None) -> dict: """Convert a voluptuous schema to a OpenAPI Schema object.""" # pylint: disable=too-many-return-statements,too-many-branches def ensure_default(value: dict[str:Any]): """Make sure that type is set.""" if all(x not in value for x in ("type", "anyOf", "oneOf", "allOf", "not")): if any( x in value for x in ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum") ): value["type"] = "number" else: value["type"] = "string" return value additional_properties = None if isinstance(schema, vol.Schema): if schema.extra == vol.ALLOW_EXTRA: additional_properties = True schema = schema.schema if custom_serializer: val = custom_serializer(schema) if val is not UNSUPPORTED: return val if isinstance(schema, vol.Object): schema = schema.schema if custom_serializer: val = custom_serializer(schema) if val is not UNSUPPORTED: return val if isinstance(schema, Mapping): properties = {} required = [] for key, value in schema.items(): description = None if isinstance(key, vol.Marker): pkey = key.schema description = key.description else: pkey = key pval = convert(value, custom_serializer=custom_serializer) if description: pval["description"] = key.description if isinstance(key, (vol.Required, vol.Optional)): if key.default is not vol.UNDEFINED: pval["default"] = key.default() pval = ensure_default(pval) if isinstance(pkey, vol.Any): for val in pkey.validators: if isinstance(val, vol.Marker): if val.description: properties[str(val.schema)] = pval.copy() properties[str(val.schema)]["description"] = val.description else: properties[str(val)] = pval else: properties[str(val)] = pval elif isinstance(pkey, str): properties[pkey] = pval else: if pval == {"type": "object", "additionalProperties": True}: pval = True additional_properties = None if additional_properties is None: additional_properties = pval if isinstance(key, vol.Required) and not isinstance(pkey, vol.Any): required.append(str(pkey)) val = {"type": "object"} if properties or not additional_properties: val["properties"] = properties val["required"] = required if additional_properties: val["additionalProperties"] = additional_properties return val if isinstance(schema, vol.All): val = {} fallback = False allOf = [] for validator in schema.validators: v = convert(validator, custom_serializer=custom_serializer) if ( not v or v in allOf or v == {"type": "object", "additionalProperties": True} ): continue if any(v[key] != val[key] for key in v.keys() & val.keys()): # Some of the keys are intersecting - fallback to allOf fallback = True allOf.append(v) if not fallback: val.update(v) if fallback: return {"allOf": allOf} return ensure_default(val) if isinstance(schema, (vol.Clamp, vol.Range)): val = {} if schema.min is not None: if isinstance(schema, vol.Clamp) or schema.min_included: val["minimum"] = schema.min else: val["exclusiveMinimum"] = schema.min if schema.max is not None: if isinstance(schema, vol.Clamp) or schema.max_included: val["maximum"] = schema.max else: val["exclusiveMaximum"] = schema.max return val if isinstance(schema, vol.Length): val = {} if schema.min is not None: val["minLength"] = schema.min if schema.max is not None: val["maxLength"] = schema.max return val if isinstance(schema, vol.Datetime): return { "type": "string", "format": "date-time", } if isinstance(schema, vol.Match): return {"pattern": schema.pattern.pattern} if isinstance(schema, vol.In): if isinstance(schema.container, Mapping): enum_values = list(schema.container.keys()) else: enum_values = schema.container # Infer the enum type based on the type of the first value, but default # to a string as a fallback. nullable = False while None in enum_values: enum_values.remove(None) nullable = True while NoneType in enum_values: enum_values.remove(NoneType) nullable = True if enum_values: enum_type = TYPES_MAP.get(type(enum_values[0]), "string") else: enum_type = "string" if nullable: return {"type": enum_type, "enum": enum_values, "nullable": True} return {"type": enum_type, "enum": enum_values} if schema in ( vol.Lower, vol.Upper, vol.Capitalize, vol.Title, vol.Strip, vol.Email, vol.Url, vol.FqdnUrl, ): return { "format": schema.__name__.lower(), } if isinstance(schema, vol.Any): schema = schema.validators if None in schema or NoneType in schema: schema = [val for val in schema if val is not None and val is not NoneType] nullable = True else: nullable = False if len(schema) == 1: result = convert(schema[0], custom_serializer=custom_serializer) else: anyOf = [ convert(val, custom_serializer=custom_serializer) for val in schema ] # Merge nested anyOf tmpAnyOf = [] for item in anyOf: if item.get("anyOf"): tmpAnyOf.extend(item["anyOf"]) if item.get("nullable"): nullable = True else: tmpAnyOf.append(item) anyOf = tmpAnyOf if {"type": "object", "additionalProperties": True} in anyOf: result = {"type": "object", "additionalProperties": True} else: tmpAnyOf = [] for item in anyOf: if item in tmpAnyOf: # Remove duplicated items continue tmpItem = item.copy() if item.get( "nullable" ): # Merge "nullable" property into an existing item tmpItem.pop("nullable") if tmpItem in tmpAnyOf: tmpAnyOf[tmpAnyOf.index(tmpItem)]["nullable"] = True continue tmpItem["nullable"] = True if tmpItem in tmpAnyOf: # Ignore duplicated items that are nullable continue if item.get("enum"): merged = False for item2 in tmpAnyOf: if item2.get("enum") and item.get("type") == item2.get( "type" ): # Merge nested enums of the same type if item.get("nullable"): item2["nullable"] = True item2["enum"] = list(set(item2["enum"] + item["enum"])) merged = True break if merged: continue tmpAnyOf.append(item) anyOf = tmpAnyOf # Remove excessive nullables null_count = 0 if not nullable: for item in anyOf: if item.get("nullable") is True: null_count = null_count + 1 if null_count > 1: break if nullable or null_count > 1: nullable = True tmpAnyOf = [] for item in anyOf: if "nullable" not in item: tmpAnyOf.append(item) continue tmpItem = item.copy() tmpItem.pop("nullable") tmpAnyOf.append(tmpItem) anyOf = tmpAnyOf if len(anyOf) == 1: result = anyOf[0] else: result = {"anyOf": anyOf} if nullable: result["nullable"] = True return result if isinstance(schema, vol.Coerce): schema = schema.type if isinstance(schema, (str, int, float, bool)): return {"type": TYPES_MAP[type(schema)], "enum": [schema]} if schema is None: return {"type": "object", "nullable": True, "description": "Must be null"} if ( get_origin(schema) is list or get_origin(schema) is set or get_origin(schema) is tuple ): schema = [get_args(schema)[0]] if isinstance(schema, Sequence): if len(schema) == 1: return { "type": "array", "items": ensure_default( convert(schema[0], custom_serializer=custom_serializer) ), } return { "type": "array", "items": [ ensure_default(convert(s, custom_serializer=custom_serializer)) for s in schema.items() ], } if schema in TYPES_MAP: return {"type": TYPES_MAP[schema]} if get_origin(schema) is dict: if get_args(schema)[1] is Any or isinstance(get_args(schema)[1], TypeVar): schema = dict else: return convert({get_args(schema)[0]: get_args(schema)[1]}) if isinstance(schema, type): if schema is dict: return {"type": "object", "additionalProperties": True} if schema is list or schema is set or schema is tuple: return {"type": "array", "items": ensure_default({})} if issubclass(schema, Enum): enum_values = list(item.value for item in schema) nullable = False while None in enum_values: enum_values.remove(None) nullable = True while NoneType in enum_values: enum_values.remove(NoneType) nullable = True if enum_values: enum_type = TYPES_MAP.get(type(enum_values[0]), "string") else: enum_type = "string" if nullable: return {"type": enum_type, "enum": enum_values, "nullable": True} return {"type": enum_type, "enum": enum_values} elif schema is NoneType: return {"type": "object", "nullable": True, "description": "Must be null"} if schema is object: return {"type": "object", "additionalProperties": True} if callable(schema): schema = get_type_hints(schema).get( list(signature(schema).parameters.keys())[0], Any ) if schema is Any or isinstance(schema, TypeVar): return {} if isinstance(schema, UnionType) or get_origin(schema) is Union: schema = [t for t in get_args(schema) if not isinstance(t, TypeVar)] if len(schema) > 1: schema = vol.Any(*schema) elif len(schema) == 1 and schema[0] is not NoneType: schema = schema[0] else: return {} return ensure_default(convert(schema, custom_serializer=custom_serializer)) raise ValueError("Unable to convert schema: {}".format(schema)) def convert_to_voluptuous(schema: dict) -> vol.Schema: """Convert an OpenAPI Schema object to a voluptuous schema.""" if not isinstance(schema, dict): raise ValueError("Invalid schema, expected a dictionary") for keyword in OPENAPI_UNSUPPORTED_KEYWORDS: if keyword in schema: raise ValueError(f"{keyword} is not supported") if (one_of := schema.get("oneOf")) is not None: if not isinstance(one_of, list): raise ValueError("Invalid schema, oneOf should be a list") return vol.Any(*[convert_to_voluptuous(sub_schema) for sub_schema in one_of]) if (schema_type := schema.get("type")) is None: raise ValueError("Invalid schema, missing type") if (basic_type := TYPES_MAP_REV.get(schema_type)) is not None: if schema_type == "string": if (pattern := schema.get("pattern")) is not None: return vol.Match(re.compile(pattern)) format = schema.get("format") if format == "date-time": return vol.Datetime() min = schema.get("minLength") max = schema.get("maxLength") if min is not None or max is not None: return vol.All(basic_type, vol.Length(min=min, max=max)) if schema_type == "integer" or schema_type == "number": min = schema.get("minimum") max = schema.get("maximum") if min is not None or max is not None: return vol.All(basic_type, vol.Range(min=min, max=max)) return basic_type if schema["type"] == "object": properties = {} required_properties = set(schema.get("required", [])) for key, value in schema.get("properties", {}).items(): value_type = convert_to_voluptuous(value) if key in required_properties: key_type = vol.Required else: key_type = vol.Optional properties[key_type(key)] = value_type if schema.get("additionalProperties") is True: return vol.Schema(properties, extra=vol.ALLOW_EXTRA) return vol.Schema(properties) if schema["type"] == "array": return vol.Schema([convert_to_voluptuous(schema["items"])]) raise ValueError("Unable to convert schema: {}".format(schema))