import marshmallow as ma import pytest from apispec import APISpec from common_apispec.marshmellow_plugin import CustomMarshmallowPlugin @pytest.fixture() def custom_plugin(): plugin = CustomMarshmallowPlugin() # APISpec is required to initialize plugin. APISpec( title="mock_title", version="v1", openapi_version="3.0.0", plugins=[plugin], ) return plugin def test_schema2jsonschema_regular_schema(custom_plugin): """Test schema2jsonschema when no custom schema is specified.""" class TestSchema(ma.Schema): field = ma.fields.Integer() schema = TestSchema() expected = { "additionalProperties": False, "type": "object", "properties": {"field": {"type": "integer"}}, } # Convert schema result = custom_plugin.converter.schema2jsonschema(schema) assert result == expected def test_schema2jsonschema_custom_schema(custom_plugin): """Test schema2jsonschema when custom openapi schema is specified.""" class TestSchema(ma.Schema): class Meta: openapi_schema = { "type": "object", "title": "Info from custom openapi_schema", "properties": {"field": {"type": "integer"}}, "example": {"field": 123}, } field = ma.fields.Integer() schema = TestSchema() expected = TestSchema.Meta.openapi_schema # Convert schema result = custom_plugin.converter.schema2jsonschema(schema) assert result == expected def test_schema2jsonschema_with_example(custom_plugin): """Test schema2jsonschema when example is specified in schema Meta class.""" class TestSchema(ma.Schema): class Meta: example = { "field1": 123, "field2": 456, } field1 = ma.fields.Integer() field2 = ma.fields.Integer() schema = TestSchema() expected = { "additionalProperties": False, "type": "object", "properties": {"field1": {"type": "integer"}, "field2": {"type": "integer"}}, "example": { "field1": 123, "field2": 456, }, } # Convert schema result = custom_plugin.converter.schema2jsonschema(schema) assert result == expected