forked from loafle/openapi-generator-original
Switches python-experimental in as the primary python client (#13501)
* Changes python to python-prior * python -> python-prior, python-experimental->python * Renames sample spec directories * Samples regnerated * Regenerates docs * Fixes test * Samples regenerated * Updates renerators list * Fixes made to python paths in pom.xml * Fixes node4 sh file paths
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
import json
|
||||
import typing
|
||||
import unittest
|
||||
|
||||
import urllib3
|
||||
from urllib3._collections import HTTPHeaderDict
|
||||
|
||||
from petstore_api import api_client
|
||||
|
||||
|
||||
class ApiTestMixin(unittest.TestCase):
|
||||
json_content_type = 'application/json'
|
||||
user_agent = 'OpenAPI-Generator/1.0.0/python'
|
||||
|
||||
@classmethod
|
||||
def assert_request_called_with(
|
||||
cls,
|
||||
mock_request,
|
||||
url: str,
|
||||
method: str = 'POST',
|
||||
body: typing.Optional[bytes] = None,
|
||||
content_type: typing.Optional[str] = 'application/json',
|
||||
fields: typing.Optional[typing.Tuple[api_client.RequestField, ...]] = None,
|
||||
accept_content_type: typing.Optional[str] = 'application/json',
|
||||
stream: bool = False,
|
||||
):
|
||||
headers = {
|
||||
'User-Agent': cls.user_agent
|
||||
}
|
||||
if accept_content_type:
|
||||
headers['Accept'] = accept_content_type
|
||||
if content_type:
|
||||
headers['Content-Type'] = content_type
|
||||
kwargs = dict(
|
||||
headers=HTTPHeaderDict(headers),
|
||||
fields=fields,
|
||||
stream=stream,
|
||||
timeout=None,
|
||||
)
|
||||
if method != 'GET':
|
||||
kwargs['body'] = body
|
||||
mock_request.assert_called_with(
|
||||
method,
|
||||
url,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def assert_pool_manager_request_called_with(
|
||||
cls,
|
||||
mock_request,
|
||||
url: str,
|
||||
method: str = 'POST',
|
||||
body: typing.Optional[bytes] = None,
|
||||
content_type: typing.Optional[str] = 'application/json',
|
||||
accept_content_type: typing.Optional[str] = 'application/json',
|
||||
stream: bool = False,
|
||||
):
|
||||
headers = {
|
||||
'User-Agent': cls.user_agent
|
||||
}
|
||||
if accept_content_type:
|
||||
headers['Accept'] = accept_content_type
|
||||
if content_type:
|
||||
headers['Content-Type'] = content_type
|
||||
kwargs = dict(
|
||||
headers=HTTPHeaderDict(headers),
|
||||
preload_content=not stream,
|
||||
timeout=None,
|
||||
)
|
||||
if content_type and method != 'GET':
|
||||
kwargs['body'] = body
|
||||
mock_request.assert_called_with(
|
||||
method,
|
||||
url,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def headers_for_content_type(content_type: str) -> typing.Dict[str, str]:
|
||||
return {'content-type': content_type}
|
||||
|
||||
@classmethod
|
||||
def response(
|
||||
cls,
|
||||
body: typing.Union[str, bytes],
|
||||
status: int = 200,
|
||||
content_type: str = json_content_type,
|
||||
headers: typing.Optional[typing.Dict[str, str]] = None,
|
||||
preload_content: bool = True
|
||||
) -> urllib3.HTTPResponse:
|
||||
if headers is None:
|
||||
headers = {}
|
||||
headers.update(cls.headers_for_content_type(content_type))
|
||||
return urllib3.HTTPResponse(
|
||||
body,
|
||||
headers=headers,
|
||||
status=status,
|
||||
preload_content=preload_content
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def json_bytes(in_data: typing.Any) -> bytes:
|
||||
return json.dumps(in_data, separators=(",", ":"), ensure_ascii=False).encode('utf-8')
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
from petstore_api.model.additional_properties_class import AdditionalPropertiesClass
|
||||
from petstore_api import schemas
|
||||
|
||||
|
||||
class TestAdditionalPropertiesClass(unittest.TestCase):
|
||||
"""AdditionalPropertiesClass unit test stubs"""
|
||||
|
||||
def test_additional_properties_class(self):
|
||||
inst = AdditionalPropertiesClass({})
|
||||
with self.assertRaises(KeyError):
|
||||
inst["map_property"]
|
||||
assert inst.get_item_oapg("map_property") is schemas.unset
|
||||
with self.assertRaises(AttributeError):
|
||||
inst.map_property
|
||||
|
||||
inst = AdditionalPropertiesClass(map_property={})
|
||||
map_property = inst["map_property"]
|
||||
assert map_property == {}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,39 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
from petstore_api.model.additional_properties_validator import AdditionalPropertiesValidator
|
||||
from petstore_api import schemas, exceptions
|
||||
|
||||
|
||||
class TestAdditionalPropertiesValidator(unittest.TestCase):
|
||||
"""AdditionalPropertiesValidator unit test stubs"""
|
||||
|
||||
def test_additional_properties_validator(self):
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AdditionalPropertiesValidator(tooShort='ab')
|
||||
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AdditionalPropertiesValidator(tooLong='abcdef')
|
||||
|
||||
inst = AdditionalPropertiesValidator(addProp='abc')
|
||||
add_prop = inst['addProp']
|
||||
assert add_prop == 'abc'
|
||||
assert isinstance(add_prop, str)
|
||||
assert isinstance(add_prop, schemas.AnyTypeSchema)
|
||||
assert isinstance(add_prop, AdditionalPropertiesValidator.MetaOapg.all_of()[1].MetaOapg.additional_properties)
|
||||
assert isinstance(add_prop, AdditionalPropertiesValidator.MetaOapg.all_of()[2].MetaOapg.additional_properties)
|
||||
assert not isinstance(add_prop, schemas.UnsetAnyTypeSchema)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,96 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import unittest
|
||||
|
||||
import frozendict
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.cat import Cat
|
||||
from petstore_api.model.dog import Dog
|
||||
from petstore_api.model.animal import Animal
|
||||
from petstore_api.schemas import StrSchema, BoolSchema
|
||||
|
||||
|
||||
class TestAnimal(unittest.TestCase):
|
||||
"""Animal unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testAnimal(self):
|
||||
"""Test Animal"""
|
||||
|
||||
regex_err = (
|
||||
r"Invalid discriminator value was passed in to Animal.className "
|
||||
r"Only the values \['Cat', 'Dog'\] are allowed at \('args\[0\]', 'className'\)"
|
||||
)
|
||||
with self.assertRaisesRegex(petstore_api.ApiValueError, regex_err):
|
||||
Animal(className='Fox', color='red')
|
||||
|
||||
animal = Animal(className='Cat', color='black')
|
||||
assert isinstance(animal, frozendict.frozendict)
|
||||
assert isinstance(animal, Cat)
|
||||
assert isinstance(animal, Cat.MetaOapg.all_of()[1])
|
||||
assert isinstance(animal, Animal)
|
||||
assert set(animal.keys()) == {'className', 'color'}
|
||||
assert animal.className == 'Cat'
|
||||
assert animal["color"] == 'black'
|
||||
assert isinstance(animal["color"], StrSchema)
|
||||
assert isinstance(animal.className, StrSchema)
|
||||
|
||||
# pass in optional param
|
||||
animal = Animal(className='Cat', color='black', declawed=True)
|
||||
assert isinstance(animal, Animal)
|
||||
assert isinstance(animal, frozendict.frozendict)
|
||||
assert isinstance(animal, Cat)
|
||||
assert isinstance(animal, Cat.MetaOapg.all_of()[1])
|
||||
assert set(animal.keys()) == {'className', 'color', 'declawed'}
|
||||
assert animal.className == 'Cat'
|
||||
assert animal["color"] == 'black'
|
||||
assert bool(animal["declawed"]) is True
|
||||
assert isinstance(animal["color"], StrSchema)
|
||||
assert isinstance(animal.className, StrSchema)
|
||||
assert isinstance(animal["declawed"], BoolSchema)
|
||||
|
||||
# make a Dog
|
||||
animal = Animal(className='Dog', color='black')
|
||||
assert isinstance(animal, Animal)
|
||||
assert isinstance(animal, frozendict.frozendict)
|
||||
assert isinstance(animal, Dog)
|
||||
assert isinstance(animal, Dog.MetaOapg.all_of()[1])
|
||||
assert set(animal.keys()) == {'className', 'color'}
|
||||
assert animal.className == 'Dog'
|
||||
assert animal["color"] == 'black'
|
||||
assert isinstance(animal["color"], StrSchema)
|
||||
assert isinstance(animal.className, StrSchema)
|
||||
|
||||
# pass in optional param
|
||||
animal = Animal(className='Dog', color='black', breed='Labrador')
|
||||
assert isinstance(animal, Animal)
|
||||
assert isinstance(animal, frozendict.frozendict)
|
||||
assert isinstance(animal, Dog)
|
||||
assert isinstance(animal, Dog.MetaOapg.all_of()[1])
|
||||
assert set(animal.keys()) == {'className', 'color', 'breed'}
|
||||
assert animal.className == 'Dog'
|
||||
assert animal["color"] == 'black'
|
||||
assert animal["breed"] == 'Labrador'
|
||||
assert isinstance(animal.className, StrSchema)
|
||||
assert isinstance(animal["color"], StrSchema)
|
||||
assert isinstance(animal["breed"], StrSchema)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,237 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import decimal
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from petstore_api.model.any_type_and_format import AnyTypeAndFormat
|
||||
from petstore_api import exceptions
|
||||
|
||||
|
||||
class TestAnyTypeAndFormat(unittest.TestCase):
|
||||
"""AnyTypeAndFormat unit test stubs"""
|
||||
|
||||
def test_uuid(self):
|
||||
valid_uuid_str = '12345678-1234-5678-1234-567812345678'
|
||||
valid_values = [
|
||||
valid_uuid_str,
|
||||
{},
|
||||
uuid.UUID(valid_uuid_str),
|
||||
1,
|
||||
3.14,
|
||||
decimal.Decimal('3.14'),
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat(uuid=valid_value)
|
||||
|
||||
# an invalid value does not work
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat(uuid='1')
|
||||
|
||||
def test_date(self):
|
||||
valid_values = [
|
||||
'2022-01-02',
|
||||
{},
|
||||
datetime.date(2022, 1, 2),
|
||||
1,
|
||||
3.14,
|
||||
decimal.Decimal('3.14'),
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat(date=valid_value)
|
||||
|
||||
# an invalid value does not work
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat(date='1')
|
||||
|
||||
def test_date_time(self):
|
||||
valid_values = [
|
||||
"2020-01-01T00:00:00",
|
||||
{},
|
||||
datetime.datetime(2020, 1, 1),
|
||||
1,
|
||||
3.14,
|
||||
decimal.Decimal('3.14'),
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat({'date-time': valid_value})
|
||||
|
||||
# an invalid value does not work
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat({'date-time': 'abcd'})
|
||||
|
||||
def test_number(self):
|
||||
valid_values = [
|
||||
'3.14',
|
||||
{},
|
||||
1,
|
||||
3.14,
|
||||
decimal.Decimal('3.14'),
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat(number=valid_value)
|
||||
|
||||
# an invalid value does not work
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat(number='a')
|
||||
|
||||
def test_int32(self):
|
||||
min_bound = decimal.Decimal(-2147483648)
|
||||
max_bound = decimal.Decimal(2147483647)
|
||||
under_min_number = min_bound - decimal.Decimal('0.1')
|
||||
over_max_number = max_bound + decimal.Decimal('0.1')
|
||||
valid_values = [
|
||||
'a',
|
||||
{},
|
||||
1,
|
||||
3.14,
|
||||
min_bound,
|
||||
max_bound,
|
||||
under_min_number,
|
||||
over_max_number,
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat(int32=valid_value)
|
||||
|
||||
# invalid values do not work
|
||||
invalid_values = (
|
||||
min_bound - 1,
|
||||
max_bound + 1
|
||||
)
|
||||
for invalid_value in invalid_values:
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat(int32=invalid_value)
|
||||
|
||||
def test_int64(self):
|
||||
min_bound = decimal.Decimal(-9223372036854775808)
|
||||
max_bound = decimal.Decimal(9223372036854775807)
|
||||
under_min_number = min_bound - decimal.Decimal('0.1')
|
||||
over_max_number = max_bound + decimal.Decimal('0.1')
|
||||
valid_values = [
|
||||
'a',
|
||||
{},
|
||||
1,
|
||||
3.14,
|
||||
min_bound,
|
||||
max_bound,
|
||||
under_min_number,
|
||||
over_max_number,
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat(int64=valid_value)
|
||||
|
||||
# invalid values do not work
|
||||
invalid_values = (
|
||||
min_bound - 1,
|
||||
max_bound + 1
|
||||
)
|
||||
for invalid_value in invalid_values:
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat(int64=invalid_value)
|
||||
|
||||
def test_float(self):
|
||||
min_bound = decimal.Decimal(-3.4028234663852886e+38)
|
||||
max_bound = decimal.Decimal(3.4028234663852886e+38)
|
||||
valid_values = [
|
||||
'a',
|
||||
{},
|
||||
1,
|
||||
3.14,
|
||||
min_bound,
|
||||
max_bound,
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat(double=valid_value)
|
||||
|
||||
# invalid values do not work
|
||||
invalid_values = (
|
||||
min_bound - decimal.Decimal('0.1'),
|
||||
max_bound + decimal.Decimal('0.1'),
|
||||
min_bound - 1,
|
||||
max_bound + 1
|
||||
)
|
||||
for invalid_value in invalid_values:
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat(float=invalid_value)
|
||||
|
||||
def test_double(self):
|
||||
min_bound = decimal.Decimal(-1.7976931348623157E+308)
|
||||
max_bound = decimal.Decimal(1.7976931348623157E+308)
|
||||
valid_values = [
|
||||
'a',
|
||||
{},
|
||||
1,
|
||||
3.14,
|
||||
min_bound,
|
||||
max_bound,
|
||||
True,
|
||||
None,
|
||||
[],
|
||||
(),
|
||||
b'abc'
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeAndFormat(double=valid_value)
|
||||
|
||||
with decimal.localcontext() as ctx:
|
||||
ctx.prec = 310
|
||||
# local higher precision context needed to correctly create these numbers
|
||||
invalid_values = (
|
||||
min_bound - decimal.Decimal('0.1'),
|
||||
max_bound + decimal.Decimal('0.1'),
|
||||
min_bound - 1,
|
||||
max_bound + 1
|
||||
)
|
||||
# invalid values do not work
|
||||
for invalid_value in invalid_values:
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
AnyTypeAndFormat(double=invalid_value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,40 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.any_type_not_string import AnyTypeNotString
|
||||
|
||||
|
||||
class TestAnyTypeNotString(unittest.TestCase):
|
||||
"""AnyTypeNotString unit test stubs"""
|
||||
|
||||
def test_AnyTypeNotString(self):
|
||||
# valid values work
|
||||
valid_values = [
|
||||
True,
|
||||
None,
|
||||
0,
|
||||
3.14,
|
||||
[],
|
||||
{}
|
||||
]
|
||||
for valid_value in valid_values:
|
||||
AnyTypeNotString(valid_value)
|
||||
|
||||
# invalid value raises an exception
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
AnyTypeNotString('')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,230 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import unittest
|
||||
from decimal import Decimal
|
||||
|
||||
import frozendict
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.schemas import (
|
||||
AnyTypeSchema,
|
||||
DictSchema,
|
||||
ListSchema,
|
||||
StrSchema,
|
||||
NumberSchema,
|
||||
IntSchema,
|
||||
BoolSchema,
|
||||
NoneSchema,
|
||||
DateSchema,
|
||||
DateTimeSchema,
|
||||
DecimalSchema,
|
||||
ComposedSchema,
|
||||
NoneClass,
|
||||
BoolClass
|
||||
)
|
||||
|
||||
|
||||
class TestAnyTypeSchema(unittest.TestCase):
|
||||
|
||||
def testDictSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
DictSchema,
|
||||
]
|
||||
|
||||
m = Model(a=1, b='hi')
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, DictSchema)
|
||||
assert isinstance(m, frozendict.frozendict)
|
||||
assert m == frozendict.frozendict(a=Decimal(1), b='hi')
|
||||
|
||||
def testListSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
ListSchema,
|
||||
]
|
||||
|
||||
m = Model([1, 'hi'])
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, ListSchema)
|
||||
assert isinstance(m, tuple)
|
||||
assert m == tuple([Decimal(1), 'hi'])
|
||||
|
||||
def testStrSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
StrSchema,
|
||||
]
|
||||
|
||||
m = Model('hi')
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, StrSchema)
|
||||
assert isinstance(m, str)
|
||||
assert m == 'hi'
|
||||
|
||||
def testNumberSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
NumberSchema,
|
||||
]
|
||||
|
||||
m = Model(1)
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, NumberSchema)
|
||||
assert isinstance(m, Decimal)
|
||||
assert m == Decimal(1)
|
||||
|
||||
m = Model(3.14)
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, NumberSchema)
|
||||
assert isinstance(m, Decimal)
|
||||
assert m == Decimal(3.14)
|
||||
|
||||
def testIntSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
IntSchema,
|
||||
]
|
||||
|
||||
m = Model(1)
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, IntSchema)
|
||||
assert isinstance(m, Decimal)
|
||||
assert m == Decimal(1)
|
||||
|
||||
with self.assertRaises(petstore_api.exceptions.ApiValueError):
|
||||
# can't pass in float into Int
|
||||
Model(3.14)
|
||||
|
||||
def testBoolSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
BoolSchema,
|
||||
]
|
||||
|
||||
m = Model(True)
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, BoolSchema)
|
||||
assert isinstance(m, BoolClass)
|
||||
self.assertTrue(m)
|
||||
|
||||
m = Model(False)
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, BoolSchema)
|
||||
assert isinstance(m, BoolClass)
|
||||
self.assertFalse(m)
|
||||
|
||||
def testNoneSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
NoneSchema,
|
||||
]
|
||||
|
||||
m = Model(None)
|
||||
self.assertTrue(m.is_none_oapg())
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, NoneSchema)
|
||||
assert isinstance(m, NoneClass)
|
||||
|
||||
def testDateSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
DateSchema,
|
||||
]
|
||||
|
||||
m = Model('1970-01-01')
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, DateSchema)
|
||||
assert isinstance(m, str)
|
||||
assert m == '1970-01-01'
|
||||
|
||||
def testDateTimeSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
DateTimeSchema,
|
||||
]
|
||||
|
||||
m = Model('2020-01-01T00:00:00')
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, DateTimeSchema)
|
||||
assert isinstance(m, str)
|
||||
assert m == '2020-01-01T00:00:00'
|
||||
|
||||
def testDecimalSchema(self):
|
||||
class Model(ComposedSchema):
|
||||
class MetaOapg:
|
||||
@staticmethod
|
||||
def all_of():
|
||||
return [
|
||||
AnyTypeSchema,
|
||||
DecimalSchema,
|
||||
]
|
||||
|
||||
m = Model('12.34')
|
||||
assert m == '12.34'
|
||||
assert m.as_decimal_oapg == Decimal('12.34')
|
||||
assert isinstance(m, Model)
|
||||
assert isinstance(m, AnyTypeSchema)
|
||||
assert isinstance(m, DecimalSchema)
|
||||
assert isinstance(m, str)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,176 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd OpenAPIetstore-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import atexit
|
||||
import datetime
|
||||
import functools
|
||||
import json
|
||||
import sys
|
||||
import weakref
|
||||
import unittest
|
||||
from dateutil.parser import parse
|
||||
from collections import namedtuple
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.api import pet_api
|
||||
from petstore_api.model import array_of_enums
|
||||
from petstore_api.model import format_test
|
||||
from petstore_api.model import string_enum
|
||||
import petstore_api.configuration
|
||||
|
||||
HOST = 'http://petstore.swagger.io/v2'
|
||||
MockResponse = namedtuple('MockResponse', 'data')
|
||||
|
||||
|
||||
class ApiClientTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.api_client = petstore_api.ApiClient()
|
||||
|
||||
def test_configuration(self):
|
||||
config = petstore_api.Configuration()
|
||||
config.host = 'http://localhost/'
|
||||
|
||||
config.disabled_client_side_validations = ("multipleOf,maximum,exclusiveMaximum,minimum,exclusiveMinimum,"
|
||||
"maxLength,minLength,pattern,maxItems,minItems")
|
||||
with self.checkRaiseRegex(ValueError, "Invalid keyword: 'foo'"):
|
||||
config.disabled_client_side_validations = 'foo'
|
||||
config.disabled_client_side_validations = ""
|
||||
|
||||
def test_servers(self):
|
||||
config = petstore_api.Configuration(server_index=1, server_variables={'version': 'v1'})
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
api = pet_api.PetApi(api_client)
|
||||
|
||||
def request(expected_url, method, url, **kwargs):
|
||||
assert expected_url == url
|
||||
raise RuntimeError('pass')
|
||||
|
||||
api_client.request = functools.partial(request, 'http://path-server-test.petstore.local/v2/pet')
|
||||
try:
|
||||
api.add_pet({'name': 'pet', 'photo_urls': []})
|
||||
except RuntimeError as e:
|
||||
assert "pass" == str(e)
|
||||
|
||||
api_client.request = functools.partial(request, 'https://localhost:8080/v1/pet/123456789')
|
||||
try:
|
||||
api.delete_pet(123456789)
|
||||
except RuntimeError as e:
|
||||
assert "pass" == str(e)
|
||||
|
||||
def test_array_of_enums(self):
|
||||
data = [
|
||||
"placed", None
|
||||
]
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.api_client.deserialize(response, (array_of_enums.ArrayOfEnums, ), True)
|
||||
assert isinstance(deserialized, array_of_enums.ArrayOfEnums)
|
||||
assert array_of_enums.ArrayOfEnums([string_enum.StringEnum(v) for v in data]) == deserialized
|
||||
|
||||
def checkRaiseRegex(self, expected_exception, expected_regex):
|
||||
if sys.version_info < (3, 0):
|
||||
return self.assertRaisesRegexp(expected_exception, expected_regex)
|
||||
|
||||
return self.assertRaisesRegex(expected_exception, expected_regex)
|
||||
|
||||
|
||||
def test_multiple_of(self):
|
||||
inst = format_test.FormatTest(
|
||||
byte='3',
|
||||
date=datetime.date(2000, 1, 1),
|
||||
password="abcdefghijkl",
|
||||
integer=30,
|
||||
number=65.0,
|
||||
float=62.4
|
||||
)
|
||||
assert isinstance(inst, format_test.FormatTest)
|
||||
|
||||
with self.checkRaiseRegex(petstore_api.exceptions.ApiValueError, "Invalid value for `integer`, value must be a multiple of `2`"):
|
||||
inst = format_test.FormatTest(
|
||||
byte='3',
|
||||
date=datetime.date(2000, 1, 1),
|
||||
password="abcdefghijkl",
|
||||
integer=31, # Value is supposed to be multiple of '2'. An error must be raised
|
||||
number=65.0,
|
||||
float=62.4
|
||||
)
|
||||
|
||||
def test_multiple_of_deserialization(self):
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 30,
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.api_client.deserialize(response, (format_test.FormatTest,), True)
|
||||
self.assertTrue(isinstance(deserialized, format_test.FormatTest))
|
||||
|
||||
with self.checkRaiseRegex(petstore_api.exceptions.ApiValueError, "Invalid value for `integer`, value must be a multiple of `2`"):
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 31, # Value is supposed to be multiple of '2'. An error must be raised
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.api_client.deserialize(response, (format_test.FormatTest,), True)
|
||||
|
||||
# Disable JSON schema validation. No error should be raised during deserialization.
|
||||
config = petstore_api.Configuration()
|
||||
config.disabled_client_side_validations = "multipleOf"
|
||||
api_client = petstore_api.ApiClient(configuration=config)
|
||||
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 31, # Value is supposed to be multiple of '2'
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = api_client.deserialize(response, (format_test.FormatTest,), True)
|
||||
self.assertTrue(isinstance(deserialized, format_test.FormatTest))
|
||||
|
||||
# Disable JSON schema validation but for a different keyword.
|
||||
# An error should be raised during deserialization.
|
||||
config = petstore_api.Configuration()
|
||||
config.disabled_client_side_validations = "maxItems"
|
||||
api_client = petstore_api.ApiClient(configuration=config)
|
||||
|
||||
with self.checkRaiseRegex(petstore_api.exceptions.ApiValueError, "Invalid value for `integer`, value must be a multiple of `2`"):
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 31, # Value is supposed to be multiple of '2'
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = api_client.deserialize(response, (format_test.FormatTest,), True)
|
||||
|
||||
def test_sanitize_for_serialization(self):
|
||||
data = {
|
||||
"prop1": [{"key1": "val1"}],
|
||||
"prop2": {"key2": "val2"}
|
||||
}
|
||||
from petstore_api.model.foo_object import FooObject
|
||||
# the property named prop1 of this model is a list of dict
|
||||
foo_object = FooObject(prop1=data["prop1"], prop2=data["prop2"])
|
||||
result = self.api_client.sanitize_for_serialization(foo_object)
|
||||
self.assertEqual(data, result)
|
||||
@@ -0,0 +1,64 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType
|
||||
from petstore_api.schemas import NoneClass, BoolClass
|
||||
|
||||
|
||||
class TestArrayHoldingAnyType(unittest.TestCase):
|
||||
"""ArrayHoldingAnyType unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testArrayHoldingAnyType(self):
|
||||
"""Test ArrayHoldingAnyType"""
|
||||
|
||||
enum_values = [True, False]
|
||||
for enum_value in enum_values:
|
||||
inst = ArrayHoldingAnyType([enum_value])
|
||||
assert isinstance(inst, ArrayHoldingAnyType)
|
||||
assert isinstance(inst, tuple)
|
||||
assert isinstance(inst[0], BoolClass)
|
||||
assert bool(inst[0]) is enum_value
|
||||
|
||||
inst = ArrayHoldingAnyType([None])
|
||||
assert isinstance(inst, ArrayHoldingAnyType)
|
||||
assert isinstance(inst, tuple)
|
||||
assert isinstance(inst[0], NoneClass)
|
||||
|
||||
input_to_stored_value = [
|
||||
(0, 0),
|
||||
(3.14, 3.14),
|
||||
(date(1970, 1, 1), '1970-01-01'),
|
||||
(datetime(1970, 1, 1, 0, 0, 0), '1970-01-01T00:00:00'),
|
||||
(datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone.utc), '1970-01-01T00:00:00+00:00'),
|
||||
([], ()),
|
||||
({}, {}),
|
||||
('hi', 'hi'),
|
||||
]
|
||||
for input, stored_value in input_to_stored_value:
|
||||
inst = ArrayHoldingAnyType([input])
|
||||
assert isinstance(inst, ArrayHoldingAnyType)
|
||||
assert isinstance(inst, tuple)
|
||||
assert inst[0] == stored_value
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,52 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.array_with_validations_in_items import ArrayWithValidationsInItems
|
||||
|
||||
|
||||
class TestArrayWithValidationsInItems(unittest.TestCase):
|
||||
"""ArrayWithValidationsInItems unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testArrayWithValidationsInItems(self):
|
||||
"""Test ArrayWithValidationsInItems"""
|
||||
|
||||
valid_values = [-1, 5, 7]
|
||||
for valid_value in valid_values:
|
||||
inst = ArrayWithValidationsInItems([valid_value])
|
||||
assert isinstance(inst, ArrayWithValidationsInItems)
|
||||
assert inst == (valid_value,)
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.exceptions.ApiValueError,
|
||||
r"Invalid value `8`, must be a value less than or equal to `7` at \('args\[0\]', 0\)"
|
||||
):
|
||||
ArrayWithValidationsInItems([8])
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.exceptions.ApiValueError,
|
||||
r"Invalid value `\(Decimal\('1'\), Decimal\('2'\), Decimal\('3'\)\)`, number of items must be less than or equal to `2` at \('args\[0\]',\)"
|
||||
):
|
||||
ArrayWithValidationsInItems([1, 2, 3])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,3 +1,5 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
@@ -8,7 +10,6 @@
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
@@ -24,13 +25,13 @@ class TestBooleanEnum(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testBooleanEnum(self):
|
||||
def test_BooleanEnum(self):
|
||||
"""Test BooleanEnum"""
|
||||
model = BooleanEnum(True)
|
||||
assert model.value is True
|
||||
|
||||
assert BooleanEnum.allowed_values[('value',)]['TRUE'] is True
|
||||
|
||||
assert model is BooleanEnum.TRUE
|
||||
assert model.is_true_oapg()
|
||||
assert model.is_false_oapg() is False
|
||||
assert repr(model) == '<DynamicSchema: True>'
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
BooleanEnum(False)
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.schemas import AnyTypeSchema, DictSchema, IntSchema, StrSchema, Float32Schema, DateSchema
|
||||
from petstore_api.model.danish_pig import DanishPig
|
||||
from petstore_api.model.basque_pig import BasquePig
|
||||
from petstore_api.model.no_additional_properties import NoAdditionalProperties
|
||||
from petstore_api.model.address import Address
|
||||
from petstore_api.model.apple_req import AppleReq
|
||||
from petstore_api.model.banana_req import BananaReq
|
||||
from petstore_api.model.player import Player
|
||||
|
||||
class TestCombineObjectSchemas(unittest.TestCase):
|
||||
pass
|
||||
# def test_invalid_combo_additional_properties_missing(self):
|
||||
# regex_err = (
|
||||
# r"Cannot combine additionalProperties schemas from.+?DanishPig.+?and.+?NoAdditionalProperties.+?"
|
||||
# r"in.+?Combo.+?because additionalProperties does not exist in both schemas"
|
||||
# )
|
||||
# with self.assertRaisesRegex(petstore_api.ApiTypeError, regex_err):
|
||||
# class Combo(DanishPig, NoAdditionalProperties):
|
||||
# pass
|
||||
#
|
||||
# def test_invalid_combo_both_no_addprops(self):
|
||||
# regex_err = (
|
||||
# r"Cannot combine schemas from.+?AppleReq.+?and.+?BananaReq.+?"
|
||||
# r"in.+?Combo.+?because cultivar is missing from.+?BananaReq.+?"
|
||||
# )
|
||||
# with self.assertRaisesRegex(petstore_api.ApiTypeError, regex_err):
|
||||
# class Combo(AppleReq, BananaReq):
|
||||
# pass
|
||||
#
|
||||
# def test_valid_no_addprops(self):
|
||||
# class FirstSchema(DictSchema):
|
||||
#
|
||||
#
|
||||
# class a(IntSchema):
|
||||
# _validations = {
|
||||
# 'inclusive_maximum': 20,
|
||||
# }
|
||||
#
|
||||
# b = Float32Schema
|
||||
#
|
||||
# _additional_properties = None
|
||||
#
|
||||
# class SecondSchema(DictSchema):
|
||||
#
|
||||
#
|
||||
# class a(IntSchema):
|
||||
# _validations = {
|
||||
# 'inclusive_minimum': 10,
|
||||
# }
|
||||
#
|
||||
# b = Float32Schema
|
||||
#
|
||||
# _additional_properties = None
|
||||
#
|
||||
# class Combo(FirstSchema, SecondSchema):
|
||||
# pass
|
||||
#
|
||||
# assert Combo._additional_properties is None
|
||||
# self.assertEqual(Combo._property_names, ('a', 'b'))
|
||||
# assert Combo.a._validations == {
|
||||
# 'inclusive_maximum': 20,
|
||||
# 'inclusive_minimum': 10,
|
||||
# }
|
||||
# assert Combo.b is Float32Schema
|
||||
#
|
||||
#
|
||||
# def test_valid_combo_additional_properties_anytype_prim(self):
|
||||
# class TwoPropsAndIntegerAddProp(DictSchema):
|
||||
# a = StrSchema
|
||||
# b = Float32Schema
|
||||
# _additional_properties = IntSchema
|
||||
#
|
||||
# class OnePropAndAnyTypeAddProps(DictSchema):
|
||||
# c = IntSchema
|
||||
# _additional_properties = AnyTypeSchema
|
||||
#
|
||||
# class Combo(TwoPropsAndIntegerAddProp, OnePropAndAnyTypeAddProps):
|
||||
# pass
|
||||
#
|
||||
# assert Combo._additional_properties is TwoPropsAndIntegerAddProp._additional_properties
|
||||
# self.assertEqual(Combo._property_names, ('a', 'b', 'c'))
|
||||
# assert Combo.a is TwoPropsAndIntegerAddProp.a
|
||||
# assert Combo.b is TwoPropsAndIntegerAddProp.b
|
||||
# assert Combo.c is OnePropAndAnyTypeAddProps.c
|
||||
#
|
||||
# def test_invalid_type_disagreement(self):
|
||||
# class StrSchemaA(DictSchema):
|
||||
# a = StrSchema
|
||||
# _additional_properties = AnyTypeSchema
|
||||
#
|
||||
# class FloatSchemaA(DictSchema):
|
||||
# a = Float32Schema
|
||||
# _additional_properties = AnyTypeSchema
|
||||
#
|
||||
# regex_err = (
|
||||
# r"Cannot combine schemas.+?StrSchema.+?and.+?Float32Schema.+?"
|
||||
# r"in.+?a.+?because their types do not intersect"
|
||||
# )
|
||||
# with self.assertRaisesRegex(petstore_api.ApiTypeError, regex_err):
|
||||
# class Combo(StrSchemaA, FloatSchemaA):
|
||||
# pass
|
||||
#
|
||||
# def test_valid_combo_including_self_reference(self):
|
||||
#
|
||||
# class EnemyPlayerAndA(DictSchema):
|
||||
# a = DateSchema
|
||||
#
|
||||
# class enemyPlayer(DictSchema):
|
||||
# heightCm = IntSchema
|
||||
# _additional_properties = AnyTypeSchema
|
||||
#
|
||||
# _additional_properties = AnyTypeSchema
|
||||
#
|
||||
# class Combo(Player, EnemyPlayerAndA):
|
||||
# # we have a self reference where Player.enemyPlayer = Player
|
||||
# pass
|
||||
#
|
||||
# """
|
||||
# For Combo
|
||||
# name is from Player
|
||||
# enemyPlayer is from Player + EnemyPlayerAndA
|
||||
# a is from EnemyPlayerAndA
|
||||
# """
|
||||
# self.assertEqual(Combo._property_names, ('a', 'enemyPlayer', 'name'))
|
||||
# self.assertEqual(Combo.enemyPlayer.__bases__, (EnemyPlayerAndA.enemyPlayer, Player))
|
||||
# """
|
||||
# For Combo.enemyPlayer
|
||||
# heightCm is from EnemyPlayerAndA.enemyPlayer
|
||||
# name is from Player.enemyPlayer
|
||||
# enemyPlayer is from Player.enemyPlayer
|
||||
# """
|
||||
# self.assertEqual(Combo.enemyPlayer._property_names, ('enemyPlayer', 'heightCm', 'name'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,74 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import decimal
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.date_with_validations import DateWithValidations
|
||||
from petstore_api.model.date_time_with_validations import DateTimeWithValidations
|
||||
from petstore_api.model.string_with_validation import StringWithValidation
|
||||
from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue
|
||||
from petstore_api.model.integer_enum import IntegerEnum
|
||||
from petstore_api.model.integer_enum_big import IntegerEnumBig
|
||||
from petstore_api.model.integer_max10 import IntegerMax10
|
||||
from petstore_api.model.integer_min15 import IntegerMin15
|
||||
from petstore_api.model.nullable_string import NullableString
|
||||
from petstore_api.schemas import AnyTypeSchema, Schema, NoneSchema, StrSchema, none_type, Singleton
|
||||
|
||||
|
||||
class TestCombineNonObjectSchemas(unittest.TestCase):
|
||||
|
||||
def test_valid_enum_plus_prim(self):
|
||||
class EnumPlusPrim(IntegerMax10, IntegerEnumOneValue):
|
||||
pass
|
||||
|
||||
# order of base classes does not matter
|
||||
class EnumPlusPrim(IntegerEnumOneValue, IntegerMax10):
|
||||
pass
|
||||
|
||||
enum_value = EnumPlusPrim.POSITIVE_0
|
||||
assert isinstance(enum_value, EnumPlusPrim)
|
||||
assert isinstance(enum_value, Singleton)
|
||||
assert isinstance(enum_value, decimal.Decimal)
|
||||
# we can access this enum from our class
|
||||
assert EnumPlusPrim.POSITIVE_0 == 0
|
||||
|
||||
# invalid value throws an exception
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
EnumPlusPrim(9)
|
||||
|
||||
# valid value succeeds
|
||||
val = EnumPlusPrim(0)
|
||||
assert val == 0
|
||||
assert isinstance(val, EnumPlusPrim)
|
||||
assert isinstance(val, Singleton)
|
||||
assert isinstance(val, decimal.Decimal)
|
||||
|
||||
def test_valid_enum_plus_enum(self):
|
||||
class IntegerOneEnum(IntegerEnumOneValue, IntegerEnum):
|
||||
pass
|
||||
|
||||
# order of base classes does not matter
|
||||
class IntegerOneEnum(IntegerEnum, IntegerEnumOneValue):
|
||||
pass
|
||||
|
||||
enum_value = IntegerOneEnum.POSITIVE_0
|
||||
assert isinstance(enum_value, IntegerOneEnum)
|
||||
assert isinstance(enum_value, Singleton)
|
||||
assert isinstance(enum_value, decimal.Decimal)
|
||||
# we can access this enum from our class
|
||||
assert IntegerOneEnum.POSITIVE_0 == 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,49 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.composed_bool import ComposedBool
|
||||
|
||||
|
||||
class TestComposedBool(unittest.TestCase):
|
||||
"""ComposedBool unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_ComposedBool(self):
|
||||
"""Test ComposedBool"""
|
||||
all_values = [None, True, False, 2, 3.14, '', {}, []]
|
||||
for value in all_values:
|
||||
if isinstance(value, bool):
|
||||
model = ComposedBool(value)
|
||||
if value is True:
|
||||
self.assertTrue(bool(model))
|
||||
self.assertTrue(model.is_true_oapg())
|
||||
self.assertFalse(model.is_false_oapg())
|
||||
else:
|
||||
self.assertTrue(model.is_false_oapg())
|
||||
self.assertFalse(model.is_true_oapg())
|
||||
self.assertFalse(bool(model))
|
||||
continue
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
ComposedBool(value)
|
||||
continue
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,42 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.composed_none import ComposedNone
|
||||
|
||||
|
||||
class TestComposedNone(unittest.TestCase):
|
||||
"""ComposedNone unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_ComposedNone(self):
|
||||
"""Test ComposedNone"""
|
||||
valid_values = [None]
|
||||
all_values = [None, True, False, 2, 3.14, '', {}, []]
|
||||
for value in all_values:
|
||||
if value not in valid_values:
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
model = ComposedNone(value)
|
||||
continue
|
||||
model = ComposedNone(value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -14,12 +14,11 @@ import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.dog import Dog
|
||||
from petstore_api.model.legs import Legs
|
||||
from petstore_api.model.composed_number import ComposedNumber
|
||||
|
||||
|
||||
class TestSetAttrForComposedSchema(unittest.TestCase):
|
||||
"""TestSetAttrForComposedSchema unit test"""
|
||||
class TestComposedNumber(unittest.TestCase):
|
||||
"""ComposedNumber unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
@@ -27,14 +26,16 @@ class TestSetAttrForComposedSchema(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testSetAttrForComposedSchema(self):
|
||||
"""Test SetAttrForComposedSchema"""
|
||||
try:
|
||||
dog_instance = Dog(class_name="Dog", color="Black")
|
||||
dog_instance.breed = "bulldog"
|
||||
dog_instance.legs = Legs(legs="4")
|
||||
except petstore_api.exceptions.ApiTypeError:
|
||||
self.assertTrue(False)
|
||||
def test_ComposedNumber(self):
|
||||
"""Test ComposedNumber"""
|
||||
valid_values = [2, 3.14]
|
||||
all_values = [None, True, False, 2, 3.14, '', {}, []]
|
||||
for value in all_values:
|
||||
if value not in valid_values:
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
model = ComposedNumber(value)
|
||||
continue
|
||||
model = ComposedNumber(value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -0,0 +1,42 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.composed_object import ComposedObject
|
||||
|
||||
|
||||
class TestComposedObject(unittest.TestCase):
|
||||
"""ComposedObject unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_ComposedObject(self):
|
||||
"""Test ComposedObject"""
|
||||
valid_values = [{}]
|
||||
all_values = [None, True, False, 2, 3.14, '', {}, []]
|
||||
for value in all_values:
|
||||
if value not in valid_values:
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
model = ComposedObject(value)
|
||||
continue
|
||||
model = ComposedObject(value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,108 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import unittest
|
||||
from datetime import date, datetime, timezone
|
||||
from dateutil.tz import tzutc
|
||||
|
||||
import frozendict
|
||||
|
||||
from petstore_api.schemas import DateSchema, DateTimeSchema, Singleton, NoneClass
|
||||
from petstore_api.model.animal import Animal
|
||||
from petstore_api.model.cat import Cat
|
||||
from petstore_api.model.composed_one_of_different_types import ComposedOneOfDifferentTypes
|
||||
from petstore_api.model.number_with_validations import NumberWithValidations
|
||||
|
||||
class TestComposedOneOfDifferentTypes(unittest.TestCase):
|
||||
"""ComposedOneOfDifferentTypes unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_ComposedOneOfDifferentTypes(self):
|
||||
"""Test ComposedOneOfDifferentTypes"""
|
||||
# we can make an instance that stores float data
|
||||
inst = ComposedOneOfDifferentTypes(10.0)
|
||||
assert isinstance(inst, NumberWithValidations)
|
||||
|
||||
# we can make an instance that stores object (dict) data
|
||||
inst = ComposedOneOfDifferentTypes(className="Cat", color="black")
|
||||
assert isinstance(inst, ComposedOneOfDifferentTypes)
|
||||
assert isinstance(inst, Animal)
|
||||
assert isinstance(inst, Cat)
|
||||
assert isinstance(inst, frozendict.frozendict)
|
||||
|
||||
# object that holds 4 properties and is not an Animal
|
||||
inst = ComposedOneOfDifferentTypes(a="a", b="b", c="c", d="d")
|
||||
assert isinstance(inst, ComposedOneOfDifferentTypes)
|
||||
assert not isinstance(inst, Animal)
|
||||
assert isinstance(inst, frozendict.frozendict)
|
||||
|
||||
# None
|
||||
inst = ComposedOneOfDifferentTypes(None)
|
||||
inst.is_none_oapg()
|
||||
assert isinstance(inst, ComposedOneOfDifferentTypes)
|
||||
assert isinstance(inst, Singleton)
|
||||
assert isinstance(inst, NoneClass)
|
||||
assert inst.is_none_oapg() is True
|
||||
|
||||
# date
|
||||
inst = ComposedOneOfDifferentTypes.from_openapi_data_oapg('2019-01-10')
|
||||
assert isinstance(inst, ComposedOneOfDifferentTypes)
|
||||
assert isinstance(inst, DateSchema)
|
||||
assert isinstance(inst, str)
|
||||
assert inst.as_date_oapg.year == 2019
|
||||
assert inst.as_date_oapg.month == 1
|
||||
assert inst.as_date_oapg.day == 10
|
||||
|
||||
# date
|
||||
inst = ComposedOneOfDifferentTypes(date(2019, 1, 10))
|
||||
assert isinstance(inst, ComposedOneOfDifferentTypes)
|
||||
assert isinstance(inst, DateSchema)
|
||||
assert isinstance(inst, str)
|
||||
assert inst.as_date_oapg.year == 2019
|
||||
assert inst.as_date_oapg.month == 1
|
||||
assert inst.as_date_oapg.day == 10
|
||||
|
||||
# date-time
|
||||
inst = ComposedOneOfDifferentTypes.from_openapi_data_oapg('2020-01-02T03:04:05Z')
|
||||
assert isinstance(inst, ComposedOneOfDifferentTypes)
|
||||
assert isinstance(inst, DateTimeSchema)
|
||||
assert isinstance(inst, str)
|
||||
assert inst.as_datetime_oapg.year == 2020
|
||||
assert inst.as_datetime_oapg.month == 1
|
||||
assert inst.as_datetime_oapg.day == 2
|
||||
assert inst.as_datetime_oapg.hour == 3
|
||||
assert inst.as_datetime_oapg.minute == 4
|
||||
assert inst.as_datetime_oapg.second == 5
|
||||
utc_tz = tzutc()
|
||||
assert inst.as_datetime_oapg.tzinfo == utc_tz
|
||||
|
||||
# date-time
|
||||
inst = ComposedOneOfDifferentTypes(datetime(2020, 1, 2, 3, 4, 5, tzinfo=timezone.utc))
|
||||
assert isinstance(inst, ComposedOneOfDifferentTypes)
|
||||
assert isinstance(inst, DateTimeSchema)
|
||||
assert isinstance(inst, str)
|
||||
assert inst.as_datetime_oapg.year == 2020
|
||||
assert inst.as_datetime_oapg.month == 1
|
||||
assert inst.as_datetime_oapg.day == 2
|
||||
assert inst.as_datetime_oapg.hour == 3
|
||||
assert inst.as_datetime_oapg.minute == 4
|
||||
assert inst.as_datetime_oapg.second == 5
|
||||
assert inst.as_datetime_oapg.tzinfo == utc_tz
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,46 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import animal
|
||||
except ImportError:
|
||||
animal = sys.modules[
|
||||
'petstore_api.model.animal']
|
||||
from petstore_api.model.composed_one_of_number_with_validations import ComposedOneOfNumberWithValidations
|
||||
|
||||
|
||||
class TestComposedOneOfNumberWithValidations(unittest.TestCase):
|
||||
"""ComposedOneOfNumberWithValidations unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testComposedOneOfNumberWithValidations(self):
|
||||
"""Test ComposedOneOfNumberWithValidations"""
|
||||
# we can make an instance that stores float data
|
||||
inst = ComposedOneOfNumberWithValidations(10.0)
|
||||
from petstore_api.model import number_with_validations
|
||||
assert isinstance(inst, number_with_validations.NumberWithValidations)
|
||||
# we can make an instance that stores object (dict) data
|
||||
inst = ComposedOneOfNumberWithValidations(class_name="Cat", color="black")
|
||||
assert isinstance(inst, ComposedOneOfNumberWithValidations)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,45 +0,0 @@
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.tag import Tag
|
||||
globals()['Tag'] = Tag
|
||||
from petstore_api.model.composed_schema_with_props_and_no_add_props import ComposedSchemaWithPropsAndNoAddProps
|
||||
|
||||
|
||||
class TestComposedSchemaWithPropsAndNoAddProps(unittest.TestCase):
|
||||
"""ComposedSchemaWithPropsAndNoAddProps unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testComposedSchemaWithPropsAndNoAddProps(self):
|
||||
"""Test ComposedSchemaWithPropsAndNoAddProps"""
|
||||
|
||||
inst = ComposedSchemaWithPropsAndNoAddProps(color='red')
|
||||
|
||||
# ComposedSchemaWithPropsAndNoAddProps should only allow in the color property
|
||||
# once https://github.com/OpenAPITools/openapi-generator/pull/8816 lands
|
||||
# this will no longer work
|
||||
# TODO update the test then
|
||||
inst = ComposedSchemaWithPropsAndNoAddProps(color='red', id=1, name='foo')
|
||||
|
||||
with self.assertRaises(petstore_api.ApiAttributeError):
|
||||
inst = ComposedSchemaWithPropsAndNoAddProps(color='red', id=1, name='foo', additional=5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,42 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.composed_string import ComposedString
|
||||
|
||||
|
||||
class TestComposedString(unittest.TestCase):
|
||||
"""ComposedString unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_ComposedString(self):
|
||||
"""Test ComposedString"""
|
||||
valid_values = ['']
|
||||
all_values = [None, True, False, 2, 3.14, '', {}, []]
|
||||
for value in all_values:
|
||||
if value not in valid_values:
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
model = ComposedString(value)
|
||||
continue
|
||||
model = ComposedString(value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,67 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd OpenAPIetstore-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
from unittest.mock import patch
|
||||
import urllib3
|
||||
from urllib3._collections import HTTPHeaderDict
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.api_client import ApiClient
|
||||
from petstore_api.apis.tags import pet_api
|
||||
|
||||
|
||||
class ConfigurationTests(unittest.TestCase):
|
||||
|
||||
def test_configuration(self):
|
||||
config = petstore_api.Configuration()
|
||||
config.host = 'https://localhost/'
|
||||
|
||||
config.disabled_client_side_validations = ("multipleOf,maximum,exclusiveMaximum,minimum,exclusiveMinimum,"
|
||||
"maxLength,minLength,pattern,maxItems,minItems")
|
||||
with self.assertRaisesRegex(ValueError, "Invalid keyword: 'foo'"):
|
||||
config.disabled_client_side_validations = 'foo'
|
||||
config.disabled_client_side_validations = ""
|
||||
|
||||
def test_servers(self):
|
||||
config = petstore_api.Configuration(server_index=1, server_variables={'version': 'v1'})
|
||||
client = ApiClient(configuration=config)
|
||||
api = pet_api.PetApi(client)
|
||||
|
||||
with patch.object(ApiClient, 'request') as mock_request:
|
||||
mock_request.return_value = urllib3.HTTPResponse(status=200)
|
||||
api.add_pet({'name': 'pet', 'photoUrls': []})
|
||||
mock_request.assert_called_with(
|
||||
'POST',
|
||||
'https://path-server-test.petstore.local/v2/pet',
|
||||
headers=HTTPHeaderDict({
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'OpenAPI-Generator/1.0.0/python'
|
||||
}),
|
||||
fields=None,
|
||||
body=b'{"photoUrls":[],"name":"pet"}',
|
||||
stream=False,
|
||||
timeout=None,
|
||||
)
|
||||
|
||||
with patch.object(ApiClient, 'request') as mock_request:
|
||||
mock_request.return_value = urllib3.HTTPResponse(status=200)
|
||||
api.delete_pet(path_params=dict(petId=123456789))
|
||||
mock_request.assert_called_with(
|
||||
'DELETE',
|
||||
'https://localhost:8080/v1/pet/123456789',
|
||||
headers={'User-Agent': 'OpenAPI-Generator/1.0.0/python'},
|
||||
fields=None,
|
||||
body=None,
|
||||
stream=False,
|
||||
timeout=None,
|
||||
)
|
||||
@@ -1,42 +0,0 @@
|
||||
from copy import deepcopy
|
||||
import unittest
|
||||
from petstore_api.model.mammal import Mammal
|
||||
from petstore_api.model.triangle import Triangle
|
||||
from petstore_api.model.dog import Dog
|
||||
|
||||
class TestCopy(unittest.TestCase):
|
||||
"""TestCopy unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testDeepCopyOneOf(self):
|
||||
"""test deepcopy"""
|
||||
obj = deepcopy(Mammal(class_name="whale"))
|
||||
assert id(deepcopy(obj)) != id(obj)
|
||||
assert deepcopy(obj) == obj
|
||||
|
||||
def testDeepCopyAllOf(self):
|
||||
"""test deepcopy"""
|
||||
obj = Triangle(shape_type="Triangle", triangle_type="EquilateralTriangle", foo="blah")
|
||||
assert id(deepcopy(obj)) != id(obj)
|
||||
assert deepcopy(obj) == obj
|
||||
|
||||
obj = Triangle._new_from_openapi_data(shape_type="Triangle", triangle_type="EquilateralTriangle", foo="blah")
|
||||
assert id(deepcopy(obj)) != id(obj)
|
||||
assert deepcopy(obj) == obj
|
||||
|
||||
obj = Dog._new_from_openapi_data(class_name='Dog', color='white', breed='Jack Russel Terrier')
|
||||
assert id(deepcopy(obj)) != id(obj)
|
||||
assert deepcopy(obj) == obj
|
||||
|
||||
obj = Dog(class_name='Dog', color='white', breed='Jack Russel Terrier')
|
||||
assert id(deepcopy(obj)) != id(obj)
|
||||
assert deepcopy(obj) == obj
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,88 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.date_time_with_validations import DateTimeWithValidations
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
|
||||
class TestDateTimeWithValidations(unittest.TestCase):
|
||||
"""DateTimeWithValidations unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testDateTimeWithValidations(self):
|
||||
"""Test DateTimeWithValidations"""
|
||||
|
||||
# works with datetime input
|
||||
valid_values = [datetime(2020, 1, 1), '2020-01-01T00:00:00']
|
||||
expected_datetime = '2020-01-01T00:00:00'
|
||||
for valid_value in valid_values:
|
||||
inst = DateTimeWithValidations(valid_value)
|
||||
assert inst == expected_datetime
|
||||
|
||||
# when passing data in with from_openapi_data_oapg one must use str
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiTypeError,
|
||||
r"Invalid type. Required value type is str and passed "
|
||||
r"type was <class 'datetime.datetime'> at \('args\[0\]',\)"
|
||||
):
|
||||
DateTimeWithValidations.from_openapi_data_oapg(datetime(2020, 1, 1))
|
||||
|
||||
# when passing data from_openapi_data_oapg we can use str
|
||||
input_value_to_datetime = {
|
||||
"2020-01-01T00:00:00": datetime(2020, 1, 1, tzinfo=None),
|
||||
"2020-01-01T00:00:00Z": datetime(2020, 1, 1, tzinfo=timezone.utc),
|
||||
"2020-01-01T00:00:00+00:00": datetime(2020, 1, 1, tzinfo=timezone.utc)
|
||||
}
|
||||
for input_value, expected_datetime in input_value_to_datetime.items():
|
||||
inst = DateTimeWithValidations.from_openapi_data_oapg(input_value)
|
||||
assert inst.as_datetime_oapg == expected_datetime
|
||||
|
||||
# value error is raised if an invalid string is passed in
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
r"Value does not conform to the required ISO-8601 datetime format. Invalid value 'abcd' for type datetime at \('args\[0\]',\)"
|
||||
):
|
||||
DateTimeWithValidations.from_openapi_data_oapg("abcd")
|
||||
|
||||
# value error is raised if a date is passed in
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
r"Value does not conform to the required ISO-8601 datetime format. Invalid value '2020-01-01' for type datetime at \('args\[0\]',\)"
|
||||
):
|
||||
DateTimeWithValidations(date(2020, 1, 1))
|
||||
|
||||
# pattern checking with string input
|
||||
error_regex = r"Invalid value `2019-01-01T00:00:00Z`, must match regular expression `.+?` at \('args\[0\]',\)"
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
error_regex
|
||||
):
|
||||
DateTimeWithValidations.from_openapi_data_oapg("2019-01-01T00:00:00Z")
|
||||
# pattern checking with date input
|
||||
error_regex = r"Invalid value `2019-01-01T00:00:00`, must match regular expression `.+?` at \('args\[0\]',\)"
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
error_regex
|
||||
):
|
||||
DateTimeWithValidations(datetime(2019, 1, 1))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,92 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.date_with_validations import DateWithValidations
|
||||
from datetime import date, datetime
|
||||
|
||||
|
||||
class TestDateWithValidations(unittest.TestCase):
|
||||
"""DateWithValidations unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testDateWithValidations(self):
|
||||
"""Test DateWithValidations"""
|
||||
|
||||
# client side date inputs
|
||||
valid_values = [date(2020, 1, 1), '2020-01-01']
|
||||
expected_date = '2020-01-01'
|
||||
for valid_value in valid_values:
|
||||
inst = DateWithValidations(valid_value)
|
||||
assert inst == expected_date
|
||||
|
||||
# when passing data in with from_openapi_data_oapg one must use str
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiTypeError,
|
||||
r"Invalid type. Required value type is str and passed "
|
||||
r"type was <class 'datetime.date'> at \('args\[0\]',\)"
|
||||
|
||||
):
|
||||
DateWithValidations.from_openapi_data_oapg(date(2020, 1, 1))
|
||||
|
||||
# when passing data in from the server we can use str
|
||||
valid_values = ["2020-01-01", "2020-01", "2020"]
|
||||
expected_date = date(2020, 1, 1)
|
||||
for valid_value in valid_values:
|
||||
inst = DateWithValidations.from_openapi_data_oapg(valid_value)
|
||||
assert inst.as_date_oapg == expected_date
|
||||
|
||||
# value error is raised if an invalid string is passed in
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
r"Value does not conform to the required ISO-8601 date format. Invalid value '2020-01-01T00:00:00Z' for type date at \('args\[0\]',\)"
|
||||
):
|
||||
DateWithValidations.from_openapi_data_oapg("2020-01-01T00:00:00Z")
|
||||
|
||||
# value error is raised if a datetime is passed in
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
r"Value does not conform to the required ISO-8601 date format. Invalid value '2020-01-01T00:00:00' for type date at \('args\[0\]',\)"
|
||||
):
|
||||
DateWithValidations(datetime(2020, 1, 1))
|
||||
|
||||
# value error is raised if an invalid string is passed in
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
r"Value does not conform to the required ISO-8601 date format. Invalid value 'abcd' for type date at \('args\[0\]',\)"
|
||||
):
|
||||
DateWithValidations.from_openapi_data_oapg("abcd")
|
||||
|
||||
# pattern checking for str input
|
||||
error_regex = r"Invalid value `2019-01-01`, must match regular expression `.+?` at \('args\[0\]',\)"
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
error_regex
|
||||
):
|
||||
DateWithValidations.from_openapi_data_oapg("2019-01-01")
|
||||
# pattern checking for date input
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
error_regex
|
||||
):
|
||||
DateWithValidations(date(2019, 1, 1))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,46 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import decimal
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.schemas import DecimalSchema
|
||||
from petstore_api.model.decimal_payload import DecimalPayload
|
||||
|
||||
|
||||
class TestDecimalPayload(unittest.TestCase):
|
||||
"""DecimalPayload unit test stubs"""
|
||||
|
||||
def test_DecimalPayload(self):
|
||||
"""Test DecimalPayload"""
|
||||
|
||||
m = DecimalPayload('12')
|
||||
assert isinstance(m, DecimalPayload)
|
||||
assert isinstance(m, DecimalSchema)
|
||||
assert isinstance(m, str)
|
||||
assert m == '12'
|
||||
assert m.as_decimal_oapg == decimal.Decimal('12')
|
||||
|
||||
m = DecimalPayload('12.34')
|
||||
assert isinstance(m, DecimalPayload)
|
||||
assert isinstance(m, DecimalSchema)
|
||||
assert isinstance(m, str)
|
||||
assert m == '12.34'
|
||||
assert m.as_decimal_oapg == decimal.Decimal('12.34')
|
||||
|
||||
# passing in a Decimal does not work
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
DecimalPayload(decimal.Decimal('12.34'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -9,38 +9,32 @@ $ cd OpenAPIPetstore-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
from collections import namedtuple
|
||||
from decimal import Decimal
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import typing
|
||||
import unittest
|
||||
import datetime
|
||||
|
||||
import urllib3
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model import (
|
||||
shape,
|
||||
equilateral_triangle,
|
||||
animal,
|
||||
dog,
|
||||
apple,
|
||||
mammal,
|
||||
whale,
|
||||
zebra,
|
||||
banana,
|
||||
fruit_req,
|
||||
drawing,
|
||||
banana_req,
|
||||
number_with_validations,
|
||||
)
|
||||
from petstore_api import api_client
|
||||
from petstore_api.schemas import NoneClass
|
||||
|
||||
|
||||
MockResponse = namedtuple('MockResponse', 'data')
|
||||
|
||||
|
||||
class DeserializationTests(unittest.TestCase):
|
||||
json_content_type = 'application/json'
|
||||
json_content_type_headers = {'content-type': json_content_type}
|
||||
configuration = petstore_api.Configuration()
|
||||
|
||||
def setUp(self):
|
||||
self.api_client = petstore_api.ApiClient()
|
||||
self.deserialize = self.api_client.deserialize
|
||||
@classmethod
|
||||
def __response(cls, data: typing.Any) -> urllib3.HTTPResponse:
|
||||
return urllib3.HTTPResponse(
|
||||
json.dumps(data).encode('utf-8'),
|
||||
headers=cls.json_content_type_headers
|
||||
)
|
||||
|
||||
def test_deserialize_shape(self):
|
||||
"""
|
||||
@@ -54,35 +48,36 @@ class DeserializationTests(unittest.TestCase):
|
||||
- SimpleQuadrilateral
|
||||
by traveling through 2 discriminators
|
||||
"""
|
||||
shape_type, triangle_type = ['Triangle', 'EquilateralTriangle']
|
||||
data = {
|
||||
'shapeType': shape_type,
|
||||
'triangleType': triangle_type,
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, (shape.Shape,), True)
|
||||
self.assertTrue(isinstance(deserialized, equilateral_triangle.EquilateralTriangle))
|
||||
self.assertEqual(deserialized.shape_type, shape_type)
|
||||
self.assertEqual(deserialized.triangle_type, triangle_type)
|
||||
|
||||
# invalid second discriminator value
|
||||
shape_type, quadrilateral_type = ['Quadrilateral', 'Triangle']
|
||||
data = {
|
||||
'shapeType': shape_type,
|
||||
'quadrilateralType': quadrilateral_type,
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
err_msg = ("Cannot deserialize input data due to invalid discriminator "
|
||||
"value. The OpenAPI document has no mapping for discriminator "
|
||||
"property '{}'='{}' at path: ()"
|
||||
from petstore_api.model import shape, equilateral_triangle
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=shape.Shape),
|
||||
},
|
||||
)
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
err_msg.format("quadrilateralType", "Triangle")
|
||||
):
|
||||
self.deserialize(response, (shape.Shape,), True)
|
||||
data = {
|
||||
'shapeType': 'Triangle',
|
||||
'triangleType': 'EquilateralTriangle',
|
||||
}
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, equilateral_triangle.EquilateralTriangle))
|
||||
self.assertEqual(body['shapeType'], 'Triangle')
|
||||
self.assertEqual(body['triangleType'], 'EquilateralTriangle')
|
||||
|
||||
# invalid quadrilateralType, second discriminator value
|
||||
data = {
|
||||
'shapeType': 'Quadrilateral',
|
||||
'quadrilateralType': 'Triangle',
|
||||
}
|
||||
response = self.__response(data)
|
||||
|
||||
err_msg = (
|
||||
r"Invalid discriminator value was passed in to Quadrilateral.quadrilateralType Only the values "
|
||||
r"\['ComplexQuadrilateral', 'SimpleQuadrilateral'\] are allowed at \('args\[0\]', 'quadrilateralType'\)"
|
||||
)
|
||||
with self.assertRaisesRegex(petstore_api.ApiValueError, err_msg):
|
||||
_response_for_200.deserialize(response, self.configuration)
|
||||
|
||||
def test_deserialize_animal(self):
|
||||
"""
|
||||
@@ -91,26 +86,30 @@ class DeserializationTests(unittest.TestCase):
|
||||
that inherrit from Animal
|
||||
This is the swagger (v2) way of doing something like oneOf composition
|
||||
"""
|
||||
class_name = 'Dog'
|
||||
color = 'white'
|
||||
breed = 'Jack Russel Terrier'
|
||||
from petstore_api.model import animal, dog
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=animal.Animal),
|
||||
},
|
||||
)
|
||||
data = {
|
||||
'className': class_name,
|
||||
'color': color,
|
||||
'breed': breed
|
||||
'className': 'Dog',
|
||||
'color': 'white',
|
||||
'breed': 'Jack Russel Terrier'
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, (animal.Animal,), True)
|
||||
self.assertTrue(isinstance(deserialized, dog.Dog))
|
||||
self.assertEqual(deserialized.class_name, class_name)
|
||||
self.assertEqual(deserialized.color, color)
|
||||
self.assertEqual(deserialized.breed, breed)
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, dog.Dog))
|
||||
self.assertEqual(body['className'], 'Dog')
|
||||
self.assertEqual(body['color'], 'white')
|
||||
self.assertEqual(body['breed'], 'Jack Russel Terrier')
|
||||
|
||||
def test_regex_constraint(self):
|
||||
"""
|
||||
Test regex pattern validation.
|
||||
"""
|
||||
from petstore_api.model import apple
|
||||
|
||||
# Test with valid regex pattern.
|
||||
inst = apple.Apple(
|
||||
@@ -118,24 +117,29 @@ class DeserializationTests(unittest.TestCase):
|
||||
)
|
||||
assert isinstance(inst, apple.Apple)
|
||||
|
||||
# Test with invalid regex pattern in cultivar
|
||||
err_msg = ("Invalid value for `{}`, must match regular expression `{}`$")
|
||||
inst = apple.Apple(
|
||||
cultivar="Golden Delicious",
|
||||
origin="cHiLe"
|
||||
)
|
||||
assert isinstance(inst, apple.Apple)
|
||||
|
||||
# Test with invalid regex pattern.
|
||||
err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'cultivar'\)"
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
err_msg.format("cultivar", "[^`]*")
|
||||
err_regex
|
||||
):
|
||||
inst = apple.Apple(
|
||||
cultivar="!@#%@$#Akane"
|
||||
)
|
||||
|
||||
# Test with invalid regex pattern in origin
|
||||
err_msg = ("Invalid value for `{}`, must match regular expression `{}` with flags")
|
||||
err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'origin'\)"
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
err_msg.format("origin", "[^`]*")
|
||||
err_regex
|
||||
):
|
||||
inst = apple.Apple(
|
||||
cultivar="Akane",
|
||||
cultivar="Golden Delicious",
|
||||
origin="!@#%@$#Chile"
|
||||
)
|
||||
|
||||
@@ -146,6 +150,12 @@ class DeserializationTests(unittest.TestCase):
|
||||
"""
|
||||
|
||||
# whale test
|
||||
from petstore_api.model import mammal, zebra, whale
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=mammal.Mammal),
|
||||
},
|
||||
)
|
||||
has_baleen = True
|
||||
has_teeth = False
|
||||
class_name = 'whale'
|
||||
@@ -154,12 +164,13 @@ class DeserializationTests(unittest.TestCase):
|
||||
'hasTeeth': has_teeth,
|
||||
'className': class_name
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (mammal.Mammal,), True)
|
||||
self.assertTrue(isinstance(deserialized, whale.Whale))
|
||||
self.assertEqual(deserialized.has_baleen, has_baleen)
|
||||
self.assertEqual(deserialized.has_teeth, has_teeth)
|
||||
self.assertEqual(deserialized.class_name, class_name)
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, whale.Whale))
|
||||
self.assertEqual(bool(body['hasBaleen']), has_baleen)
|
||||
self.assertEqual(bool(body['hasTeeth']), has_teeth)
|
||||
self.assertEqual(body.className, class_name)
|
||||
|
||||
# zebra test
|
||||
zebra_type = 'plains'
|
||||
@@ -168,47 +179,64 @@ class DeserializationTests(unittest.TestCase):
|
||||
'type': zebra_type,
|
||||
'className': class_name
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (mammal.Mammal,), True)
|
||||
self.assertTrue(isinstance(deserialized, zebra.Zebra))
|
||||
self.assertEqual(deserialized.type, zebra_type)
|
||||
self.assertEqual(deserialized.class_name, class_name)
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, zebra.Zebra))
|
||||
self.assertEqual(body['type'], zebra_type)
|
||||
self.assertEqual(body.className, class_name)
|
||||
|
||||
def test_deserialize_float_value(self):
|
||||
"""
|
||||
Deserialize floating point values.
|
||||
"""
|
||||
from petstore_api.model import banana
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=banana.Banana),
|
||||
},
|
||||
)
|
||||
data = {
|
||||
'lengthCm': 3.1415
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (banana.Banana,), True)
|
||||
self.assertTrue(isinstance(deserialized, banana.Banana))
|
||||
self.assertEqual(deserialized.length_cm, 3.1415)
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, banana.Banana))
|
||||
self.assertTrue(isinstance(body.lengthCm, Decimal))
|
||||
self.assertEqual(body.lengthCm, 3.1415)
|
||||
|
||||
# Float value is serialized without decimal point
|
||||
"""
|
||||
Float value is serialized without decimal point
|
||||
The client receive it as an integer, which work because Banana.lengthCm is type number without format
|
||||
Which accepts int AND float
|
||||
"""
|
||||
data = {
|
||||
'lengthCm': 3
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (banana.Banana,), True)
|
||||
self.assertTrue(isinstance(deserialized, banana.Banana))
|
||||
self.assertEqual(deserialized.length_cm, 3.0)
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, banana.Banana))
|
||||
self.assertTrue(isinstance(body.lengthCm, Decimal))
|
||||
self.assertEqual(body.lengthCm, 3)
|
||||
|
||||
def test_deserialize_fruit_null_value(self):
|
||||
"""
|
||||
deserialize fruit with null value.
|
||||
fruitReq is a oneOf composed schema model with discriminator, including 'null' type.
|
||||
"""
|
||||
|
||||
# Unmarshal 'null' value
|
||||
from petstore_api.model import fruit_req
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=fruit_req.FruitReq),
|
||||
},
|
||||
)
|
||||
data = None
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (fruit_req.FruitReq, type(None)), True)
|
||||
self.assertEqual(type(deserialized), type(None))
|
||||
|
||||
inst = fruit_req.FruitReq(None)
|
||||
self.assertIsNone(inst)
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
self.assertTrue(isinstance(deserialized.body, fruit_req.FruitReq))
|
||||
self.assertTrue(isinstance(deserialized.body, NoneClass))
|
||||
|
||||
def test_deserialize_with_additional_properties(self):
|
||||
"""
|
||||
@@ -223,6 +251,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
# The additionalProperties keyword is used to control the handling of extra stuff,
|
||||
# that is, properties whose names are not listed in the properties keyword.
|
||||
# By default any additional properties are allowed.
|
||||
from petstore_api.model import dog, mammal, zebra, banana_req
|
||||
data = {
|
||||
'className': 'Dog',
|
||||
'color': 'brown',
|
||||
@@ -231,37 +260,56 @@ class DeserializationTests(unittest.TestCase):
|
||||
'group': 'Terrier Group',
|
||||
'size': 'medium',
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (dog.Dog,), True)
|
||||
self.assertEqual(type(deserialized), dog.Dog)
|
||||
self.assertEqual(deserialized.class_name, 'Dog')
|
||||
self.assertEqual(deserialized.breed, 'golden retriever')
|
||||
response = self.__response(data)
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=dog.Dog),
|
||||
},
|
||||
)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, dog.Dog))
|
||||
self.assertEqual(body['className'], 'Dog')
|
||||
self.assertEqual(body['color'], 'brown')
|
||||
self.assertEqual(body['breed'], 'golden retriever')
|
||||
self.assertEqual(body['group'], 'Terrier Group')
|
||||
self.assertEqual(body['size'], 'medium')
|
||||
|
||||
# The 'zebra' schema allows additional properties by explicitly setting
|
||||
# additionalProperties: true.
|
||||
# This is equivalent to 'additionalProperties' not being present.
|
||||
data = {
|
||||
'class_name': 'zebra',
|
||||
'className': 'zebra',
|
||||
'type': 'plains',
|
||||
# Below are additional, undeclared properties
|
||||
'group': 'abc',
|
||||
'size': 3,
|
||||
'p1': True,
|
||||
'p2': [ 'a', 'b', 123],
|
||||
'p2': ['a', 'b', 123],
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (mammal.Mammal,), True)
|
||||
self.assertEqual(type(deserialized), zebra.Zebra)
|
||||
self.assertEqual(deserialized.class_name, 'zebra')
|
||||
self.assertEqual(deserialized.type, 'plains')
|
||||
self.assertEqual(deserialized.p1, True)
|
||||
response = self.__response(data)
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=mammal.Mammal),
|
||||
},
|
||||
)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
body = deserialized.body
|
||||
self.assertTrue(isinstance(body, zebra.Zebra))
|
||||
self.assertEqual(body['className'], 'zebra')
|
||||
self.assertEqual(body['type'], 'plains')
|
||||
self.assertEqual(bool(body['p1']), True)
|
||||
|
||||
# The 'bananaReq' schema disallows additional properties by explicitly setting
|
||||
# additionalProperties: false
|
||||
err_msg = ("{} has no attribute '{}' at ")
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=banana_req.BananaReq),
|
||||
},
|
||||
)
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.exceptions.ApiAttributeError,
|
||||
err_msg.format("BananaReq", "unknown-group")
|
||||
petstore_api.exceptions.ApiTypeError,
|
||||
r"BananaReq was passed 1 invalid argument: \['unknown-group'\]"
|
||||
):
|
||||
data = {
|
||||
'lengthCm': 21.2,
|
||||
@@ -270,58 +318,141 @@ class DeserializationTests(unittest.TestCase):
|
||||
# an exception must be raised.
|
||||
'unknown-group': 'abc',
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (banana_req.BananaReq,), True)
|
||||
self.assertEqual(type(deserialized), banana_req.BananaReq)
|
||||
self.assertEqual(deserialized.lengthCm, 21)
|
||||
self.assertEqual(deserialized.p1, True)
|
||||
response = self.__response(data)
|
||||
_response_for_200.deserialize(response, self.configuration)
|
||||
|
||||
def test_deserialize_with_additional_properties_and_reference(self):
|
||||
"""
|
||||
Deserialize data with schemas that has the additionalProperties keyword
|
||||
and the schema is specified as a reference ($ref).
|
||||
"""
|
||||
from petstore_api.model import drawing
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=drawing.Drawing),
|
||||
},
|
||||
)
|
||||
data = {
|
||||
'main_shape': {
|
||||
'shape_type': 'Triangle',
|
||||
'triangle_type': 'EquilateralTriangle',
|
||||
'mainShape': {
|
||||
'shapeType': 'Triangle',
|
||||
'triangleType': 'EquilateralTriangle',
|
||||
},
|
||||
'shapes': [
|
||||
{
|
||||
'shape_type': 'Triangle',
|
||||
'triangle_type': 'IsoscelesTriangle',
|
||||
'shapeType': 'Triangle',
|
||||
'triangleType': 'IsoscelesTriangle',
|
||||
},
|
||||
{
|
||||
'shape_type': 'Quadrilateral',
|
||||
'quadrilateral_type': 'ComplexQuadrilateral',
|
||||
'shapeType': 'Quadrilateral',
|
||||
'quadrilateralType': 'ComplexQuadrilateral',
|
||||
},
|
||||
],
|
||||
'an_additional_prop': {
|
||||
'lengthCm': 4,
|
||||
'color': 'yellow'
|
||||
}
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = self.deserialize(response, (drawing.Drawing,), True)
|
||||
response = self.__response(data)
|
||||
_response_for_200.deserialize(response, self.configuration)
|
||||
|
||||
def test_deserialize_NumberWithValidations(self):
|
||||
""" deserialize NumberWithValidations """
|
||||
from petstore_api.model.number_with_validations import NumberWithValidations
|
||||
from petstore_api.paths.fake_refs_number.post import _response_for_200
|
||||
|
||||
# make sure that an exception is thrown on an invalid type value
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
self.deserialize(
|
||||
MockResponse(data=json.dumps("test str")),
|
||||
(number_with_validations.NumberWithValidations,),
|
||||
True
|
||||
)
|
||||
response = self.__response('test str')
|
||||
_response_for_200.deserialize(response, self.configuration)
|
||||
|
||||
# make sure that an exception is thrown on an invalid value
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
self.deserialize(
|
||||
MockResponse(data=json.dumps(21.0)),
|
||||
(number_with_validations.NumberWithValidations,),
|
||||
True
|
||||
)
|
||||
response = self.__response(21.0)
|
||||
_response_for_200.deserialize(response, self.configuration)
|
||||
|
||||
# valid value works
|
||||
number_val = 11.0
|
||||
response = MockResponse(data=json.dumps(number_val))
|
||||
number = self.deserialize(response,
|
||||
(number_with_validations.NumberWithValidations,), True)
|
||||
self.assertTrue(isinstance(number, number_with_validations.NumberWithValidations))
|
||||
self.assertTrue(number.value == number_val)
|
||||
response = self.__response(number_val)
|
||||
response = _response_for_200.deserialize(response, self.configuration)
|
||||
self.assertTrue(isinstance(response.body, NumberWithValidations))
|
||||
self.assertEqual(response.body, number_val)
|
||||
|
||||
def test_array_of_enums(self):
|
||||
from petstore_api.model.array_of_enums import ArrayOfEnums
|
||||
from petstore_api.paths.fake_refs_array_of_enums.post import _response_for_200
|
||||
from petstore_api.model import string_enum
|
||||
data = ["placed", None]
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
assert isinstance(deserialized.body, ArrayOfEnums)
|
||||
expected_results = ArrayOfEnums([string_enum.StringEnum(v) for v in data])
|
||||
assert expected_results == deserialized.body
|
||||
|
||||
def test_multiple_of_deserialization(self):
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 30,
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
from petstore_api.model import format_test
|
||||
_response_for_200 = api_client.OpenApiResponse(
|
||||
content={
|
||||
self.json_content_type: api_client.MediaType(schema=format_test.FormatTest),
|
||||
},
|
||||
)
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, self.configuration)
|
||||
self.assertTrue(isinstance(deserialized.body, format_test.FormatTest))
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.exceptions.ApiValueError,
|
||||
r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)"
|
||||
):
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 31, # Value is supposed to be multiple of '2'. An error must be raised
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
response = self.__response(data)
|
||||
_response_for_200.deserialize(response, self.configuration)
|
||||
|
||||
# Disable JSON schema validation. No error should be raised during deserialization.
|
||||
configuration = petstore_api.Configuration()
|
||||
configuration.disabled_client_side_validations = "multipleOf"
|
||||
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 31, # Value is supposed to be multiple of '2'
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
response = self.__response(data)
|
||||
deserialized = _response_for_200.deserialize(response, configuration)
|
||||
self.assertTrue(isinstance(deserialized.body, format_test.FormatTest))
|
||||
|
||||
# Disable JSON schema validation but for a different keyword.
|
||||
# An error should be raised during deserialization.
|
||||
configuration = petstore_api.Configuration()
|
||||
configuration.disabled_client_side_validations = "maxItems"
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.exceptions.ApiValueError,
|
||||
r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)"
|
||||
):
|
||||
data = {
|
||||
'byte': '3',
|
||||
'date': '1970-01-01',
|
||||
'password': "abcdefghijkl",
|
||||
'integer': 31, # Value is supposed to be multiple of '2'
|
||||
'number': 65.0,
|
||||
'float': 62.4,
|
||||
}
|
||||
response = self.__response(data)
|
||||
_response_for_200.deserialize(response, configuration)
|
||||
|
||||
@@ -1,173 +1,157 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ docker pull swaggerapi/petstore
|
||||
$ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
|
||||
$ pip install nose (optional)
|
||||
$ cd petstore_api-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
from collections import namedtuple
|
||||
import json
|
||||
import re
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model import cat, dog, isosceles_triangle, banana_req, fruit_req
|
||||
from petstore_api import Configuration, signing
|
||||
|
||||
from petstore_api.model_utils import (
|
||||
file_type,
|
||||
model_to_dict,
|
||||
)
|
||||
|
||||
MockResponse = namedtuple('MockResponse', 'data')
|
||||
|
||||
class DiscardUnknownPropertiesTests(unittest.TestCase):
|
||||
|
||||
def test_deserialize_banana_req_do_not_discard_unknown_properties(self):
|
||||
"""
|
||||
deserialize bananaReq with unknown properties.
|
||||
Strict validation is enabled.
|
||||
Simple (non-composed) schema scenario.
|
||||
"""
|
||||
config = Configuration(discard_unknown_keys=False)
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
data = {
|
||||
'lengthCm': 21.3,
|
||||
'sweet': False,
|
||||
# Below is an unknown property not explicitly declared in the OpenAPI document.
|
||||
# It should not be in the payload because additional properties (undeclared) are
|
||||
# not allowed in the bananaReq schema (additionalProperties: false).
|
||||
'unknown_property': 'a-value'
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
# Deserializing with strict validation raises an exception because the 'unknown_property'
|
||||
# is undeclared.
|
||||
with self.assertRaises(petstore_api.exceptions.ApiAttributeError) as cm:
|
||||
deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True)
|
||||
self.assertTrue(re.match("BananaReq has no attribute 'unknown_property' at.*", str(cm.exception)),
|
||||
'Exception message: {0}'.format(str(cm.exception)))
|
||||
|
||||
|
||||
def test_deserialize_fruit_req_do_not_discard_unknown_properties(self):
|
||||
"""
|
||||
deserialize FruitReq with unknown properties.
|
||||
Strict validation is enabled.
|
||||
Composed schema scenario.
|
||||
"""
|
||||
config = Configuration(discard_unknown_keys=False)
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
data = {
|
||||
'lengthCm': 21.3,
|
||||
'sweet': False,
|
||||
# Below is an unknown property not explicitly declared in the OpenAPI document.
|
||||
# It should not be in the payload because additional properties (undeclared) are
|
||||
# not allowed in the schema (additionalProperties: false).
|
||||
'unknown_property': 'a-value'
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
# Deserializing with strict validation raises an exception because the 'unknown_property'
|
||||
# is undeclared.
|
||||
with self.assertRaisesRegex(petstore_api.ApiValueError, "Invalid inputs given to generate an instance of FruitReq. None of the oneOf schemas matched the input data."):
|
||||
deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True)
|
||||
|
||||
|
||||
def test_deserialize_fruit_req_discard_unknown_properties(self):
|
||||
"""
|
||||
deserialize FruitReq with unknown properties.
|
||||
Strict validation is enabled.
|
||||
Composed schema scenario.
|
||||
"""
|
||||
config = Configuration(discard_unknown_keys=True)
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
data = {
|
||||
'lengthCm': 21.3,
|
||||
'sweet': False,
|
||||
# Below is an unknown property not explicitly declared in the OpenAPI document.
|
||||
# It should not be in the payload because additional properties (undeclared) are
|
||||
# not allowed in BananaReq
|
||||
'unknown_property': 'a-value'
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True)
|
||||
self.assertNotIn("unknown_property", deserialized.to_dict().keys())
|
||||
|
||||
|
||||
def test_deserialize_banana_req_discard_unknown_properties(self):
|
||||
"""
|
||||
Deserialize bananaReq with unknown properties.
|
||||
Discard unknown properties.
|
||||
"""
|
||||
config = Configuration(discard_unknown_keys=True)
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
data = {
|
||||
'lengthCm': 21.3,
|
||||
'sweet': False,
|
||||
# Below are additional (undeclared) properties not specified in the bananaReq schema.
|
||||
'unknown_property': 'a-value',
|
||||
'more-unknown': [
|
||||
'a'
|
||||
]
|
||||
}
|
||||
# The 'unknown_property' is undeclared, which would normally raise an exception, but
|
||||
# when discard_unknown_keys is set to True, the unknown properties are discarded.
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True)
|
||||
self.assertTrue(isinstance(deserialized, banana_req.BananaReq))
|
||||
# Check the 'unknown_property' and 'more-unknown' properties are not present in the
|
||||
# output.
|
||||
self.assertIn("length_cm", deserialized.to_dict().keys())
|
||||
self.assertNotIn("unknown_property", deserialized.to_dict().keys())
|
||||
self.assertNotIn("more-unknown", deserialized.to_dict().keys())
|
||||
|
||||
def test_deserialize_cat_do_not_discard_unknown_properties(self):
|
||||
"""
|
||||
Deserialize Cat with unknown properties.
|
||||
Strict validation is enabled.
|
||||
"""
|
||||
config = Configuration(discard_unknown_keys=False)
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
data = {
|
||||
"class_name": "Cat",
|
||||
"color": "black",
|
||||
"declawed": True,
|
||||
"dynamic-property": 12345,
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
# Deserializing with strict validation does not raise an exception because the even though
|
||||
# the 'dynamic-property' is undeclared, the 'Cat' schema defines the additionalProperties
|
||||
# attribute.
|
||||
deserialized = api_client.deserialize(response, ((cat.Cat),), True)
|
||||
self.assertTrue(isinstance(deserialized, cat.Cat))
|
||||
self.assertIn('color', deserialized.to_dict())
|
||||
self.assertEqual(deserialized['color'], 'black')
|
||||
|
||||
def test_deserialize_cat_discard_unknown_properties(self):
|
||||
"""
|
||||
Deserialize Cat with unknown properties.
|
||||
Request to discard unknown properties, but Cat is composed schema
|
||||
with one inner schema that has 'additionalProperties' set to true.
|
||||
"""
|
||||
config = Configuration(discard_unknown_keys=True)
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
data = {
|
||||
"class_name": "Cat",
|
||||
"color": "black",
|
||||
"declawed": True,
|
||||
# Below are additional (undeclared) properties.
|
||||
"my_additional_property": 123,
|
||||
}
|
||||
# The 'my_additional_property' is undeclared
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = api_client.deserialize(response, ((cat.Cat),), True)
|
||||
self.assertTrue(isinstance(deserialized, cat.Cat))
|
||||
# Check the 'my_additional_property' is present
|
||||
self.assertIn("my_additional_property", deserialized.to_dict().keys())
|
||||
|
||||
# # coding: utf-8
|
||||
#
|
||||
# # flake8: noqa
|
||||
#
|
||||
# """
|
||||
# Run the tests.
|
||||
# $ docker pull swaggerapi/petstore
|
||||
# $ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
|
||||
# $ pip install nose (optional)
|
||||
# $ cd petstore_api-python
|
||||
# $ nosetests -v
|
||||
# """
|
||||
# from collections import namedtuple
|
||||
# import json
|
||||
# import re
|
||||
# import unittest
|
||||
#
|
||||
# import petstore_api
|
||||
# from petstore_api.model import cat, dog, isosceles_triangle, banana_req
|
||||
# from petstore_api import Configuration, signing
|
||||
#
|
||||
# from petstore_api.schemas import (
|
||||
# file_type,
|
||||
# model_to_dict,
|
||||
# )
|
||||
#
|
||||
# MockResponse = namedtuple('MockResponse', 'data')
|
||||
#
|
||||
# class DiscardUnknownPropertiesTests(unittest.TestCase):
|
||||
#
|
||||
# def test_deserialize_banana_req_do_not_discard_unknown_properties(self):
|
||||
# """
|
||||
# deserialize bananaReq with unknown properties.
|
||||
# Strict validation is enabled.
|
||||
# Simple (non-composed) schema scenario.
|
||||
# """
|
||||
# config = Configuration(discard_unknown_keys=False)
|
||||
# api_client = petstore_api.ApiClient(config)
|
||||
# data = {
|
||||
# 'lengthCm': 21.3,
|
||||
# 'sweet': False,
|
||||
# # Below is an unknown property not explicitly declared in the OpenAPI document.
|
||||
# # It should not be in the payload because additional properties (undeclared) are
|
||||
# # not allowed in the bananaReq schema (additionalProperties: false).
|
||||
# 'unknown_property': 'a-value'
|
||||
# }
|
||||
# response = MockResponse(data=json.dumps(data))
|
||||
#
|
||||
# # Deserializing with strict validation raises an exception because the 'unknown_property'
|
||||
# # is undeclared.
|
||||
# with self.assertRaises(petstore_api.exceptions.ApiAttributeError) as cm:
|
||||
# deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True)
|
||||
# self.assertTrue(re.match("BananaReq has no attribute 'unknown_property' at.*", str(cm.exception)),
|
||||
# 'Exception message: {0}'.format(str(cm.exception)))
|
||||
#
|
||||
#
|
||||
# def test_deserialize_isosceles_triangle_do_not_discard_unknown_properties(self):
|
||||
# """
|
||||
# deserialize IsoscelesTriangle with unknown properties.
|
||||
# Strict validation is enabled.
|
||||
# Composed schema scenario.
|
||||
# """
|
||||
# config = Configuration(discard_unknown_keys=False)
|
||||
# api_client = petstore_api.ApiClient(config)
|
||||
# data = {
|
||||
# 'shape_type': 'Triangle',
|
||||
# 'triangle_type': 'EquilateralTriangle',
|
||||
# # Below is an unknown property not explicitly declared in the OpenAPI document.
|
||||
# # It should not be in the payload because additional properties (undeclared) are
|
||||
# # not allowed in the schema (additionalProperties: false).
|
||||
# 'unknown_property': 'a-value'
|
||||
# }
|
||||
# response = MockResponse(data=json.dumps(data))
|
||||
#
|
||||
# # Deserializing with strict validation raises an exception because the 'unknown_property'
|
||||
# # is undeclared.
|
||||
# with self.assertRaises(petstore_api.ApiValueError) as cm:
|
||||
# deserialized = api_client.deserialize(response, ((isosceles_triangle.IsoscelesTriangle),), True)
|
||||
# self.assertTrue(re.match('.*Not all inputs were used.*unknown_property.*', str(cm.exception)),
|
||||
# 'Exception message: {0}'.format(str(cm.exception)))
|
||||
#
|
||||
#
|
||||
# def test_deserialize_banana_req_discard_unknown_properties(self):
|
||||
# """
|
||||
# Deserialize bananaReq with unknown properties.
|
||||
# Discard unknown properties.
|
||||
# """
|
||||
# config = Configuration(discard_unknown_keys=True)
|
||||
# api_client = petstore_api.ApiClient(config)
|
||||
# data = {
|
||||
# 'lengthCm': 21.3,
|
||||
# 'sweet': False,
|
||||
# # Below are additional (undeclared) properties not specified in the bananaReq schema.
|
||||
# 'unknown_property': 'a-value',
|
||||
# 'more-unknown': [
|
||||
# 'a'
|
||||
# ]
|
||||
# }
|
||||
# # The 'unknown_property' is undeclared, which would normally raise an exception, but
|
||||
# # when discard_unknown_keys is set to True, the unknown properties are discarded.
|
||||
# response = MockResponse(data=json.dumps(data))
|
||||
# deserialized = api_client.deserialize(response, ((banana_req.BananaReq),), True)
|
||||
# self.assertTrue(isinstance(deserialized, banana_req.BananaReq))
|
||||
# # Check the 'unknown_property' and 'more-unknown' properties are not present in the
|
||||
# # output.
|
||||
# self.assertIn("length_cm", deserialized.to_dict().keys())
|
||||
# self.assertNotIn("unknown_property", deserialized.to_dict().keys())
|
||||
# self.assertNotIn("more-unknown", deserialized.to_dict().keys())
|
||||
#
|
||||
# def test_deserialize_cat_do_not_discard_unknown_properties(self):
|
||||
# """
|
||||
# Deserialize Cat with unknown properties.
|
||||
# Strict validation is enabled.
|
||||
# """
|
||||
# config = Configuration(discard_unknown_keys=False)
|
||||
# api_client = petstore_api.ApiClient(config)
|
||||
# data = {
|
||||
# "class_name": "Cat",
|
||||
# "color": "black",
|
||||
# "declawed": True,
|
||||
# "dynamic-property": 12345,
|
||||
# }
|
||||
# response = MockResponse(data=json.dumps(data))
|
||||
#
|
||||
# # Deserializing with strict validation does not raise an exception because the even though
|
||||
# # the 'dynamic-property' is undeclared, the 'Cat' schema defines the additionalProperties
|
||||
# # attribute.
|
||||
# deserialized = api_client.deserialize(response, ((cat.Cat),), True)
|
||||
# self.assertTrue(isinstance(deserialized, cat.Cat))
|
||||
# self.assertIn('color', deserialized.to_dict())
|
||||
# self.assertEqual(deserialized['color'], 'black')
|
||||
#
|
||||
# def test_deserialize_cat_discard_unknown_properties(self):
|
||||
# """
|
||||
# Deserialize Cat with unknown properties.
|
||||
# Request to discard unknown properties, but Cat is composed schema
|
||||
# with one inner schema that has 'additionalProperties' set to true.
|
||||
# """
|
||||
# config = Configuration(discard_unknown_keys=True)
|
||||
# api_client = petstore_api.ApiClient(config)
|
||||
# data = {
|
||||
# "class_name": "Cat",
|
||||
# "color": "black",
|
||||
# "declawed": True,
|
||||
# # Below are additional (undeclared) properties.
|
||||
# "my_additional_property": 123,
|
||||
# }
|
||||
# # The 'my_additional_property' is undeclared, but 'Cat' has a 'Address' type through
|
||||
# # the allOf: [ $ref: '#/components/schemas/Address' ].
|
||||
# response = MockResponse(data=json.dumps(data))
|
||||
# deserialized = api_client.deserialize(response, ((cat.Cat),), True)
|
||||
# self.assertTrue(isinstance(deserialized, cat.Cat))
|
||||
# # Check the 'unknown_property' and 'more-unknown' properties are not present in the
|
||||
# # output.
|
||||
# self.assertIn("declawed", deserialized.to_dict().keys())
|
||||
# self.assertIn("my_additional_property", deserialized.to_dict().keys())
|
||||
#
|
||||
|
||||
@@ -14,21 +14,9 @@ import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import nullable_shape
|
||||
except ImportError:
|
||||
nullable_shape = sys.modules[
|
||||
'petstore_api.model.nullable_shape']
|
||||
try:
|
||||
from petstore_api.model import shape
|
||||
except ImportError:
|
||||
shape = sys.modules[
|
||||
'petstore_api.model.shape']
|
||||
try:
|
||||
from petstore_api.model import shape_or_null
|
||||
except ImportError:
|
||||
shape_or_null = sys.modules[
|
||||
'petstore_api.model.shape_or_null']
|
||||
from petstore_api.schemas import NoneClass
|
||||
from petstore_api.model import shape
|
||||
from petstore_api.model import shape_or_null
|
||||
from petstore_api.model.drawing import Drawing
|
||||
|
||||
|
||||
@@ -43,88 +31,95 @@ class TestDrawing(unittest.TestCase):
|
||||
|
||||
def test_create_instances(self):
|
||||
"""
|
||||
Validate instance can be created using pythonic name or OAS names.
|
||||
Validate instance can be created
|
||||
"""
|
||||
|
||||
# Validate object can be created using pythonic names.
|
||||
inst = shape.Shape(
|
||||
shape_type="Triangle",
|
||||
triangle_type="IsoscelesTriangle"
|
||||
shapeType="Triangle",
|
||||
triangleType="IsoscelesTriangle"
|
||||
)
|
||||
from petstore_api.model.isosceles_triangle import IsoscelesTriangle
|
||||
assert isinstance(inst, IsoscelesTriangle)
|
||||
|
||||
# Validate object can be created using OAS names.
|
||||
# For example, this can be used to construct objects on the client
|
||||
# when the input data is available as JSON documents.
|
||||
data = {
|
||||
'shapeType': "Triangle",
|
||||
'triangleType': "IsoscelesTriangle"
|
||||
}
|
||||
inst = shape.Shape(_spec_property_naming=True, **data)
|
||||
assert isinstance(inst, IsoscelesTriangle)
|
||||
|
||||
def test_deserialize_oneof_reference(self):
|
||||
"""
|
||||
Validate the scenario when the type of a OAS property is 'oneOf', and the 'oneOf'
|
||||
schema is specified as a reference ($ref), not an inline 'oneOf' schema.
|
||||
"""
|
||||
isosceles_triangle = shape.Shape(
|
||||
shape_type="Triangle",
|
||||
triangle_type="IsoscelesTriangle"
|
||||
shapeType="Triangle",
|
||||
triangleType="IsoscelesTriangle"
|
||||
)
|
||||
from petstore_api.model.isosceles_triangle import IsoscelesTriangle
|
||||
from petstore_api.model.triangle import Triangle
|
||||
assert isinstance(isosceles_triangle, IsoscelesTriangle)
|
||||
from petstore_api.model.equilateral_triangle import EquilateralTriangle
|
||||
|
||||
assert isinstance(isosceles_triangle, IsoscelesTriangle)
|
||||
inst = Drawing(
|
||||
# 'main_shape' has type 'Shape', which is a oneOf [triangle, quadrilateral]
|
||||
# composed schema. So we should be able to assign a petstore_api.Triangle
|
||||
# to a 'main_shape'.
|
||||
main_shape=isosceles_triangle,
|
||||
mainShape=isosceles_triangle,
|
||||
shapes=[
|
||||
shape.Shape(
|
||||
shape_type="Triangle",
|
||||
triangle_type="EquilateralTriangle"
|
||||
),
|
||||
Triangle(
|
||||
shape_type="Triangle",
|
||||
triangle_type="IsoscelesTriangle"
|
||||
),
|
||||
EquilateralTriangle(
|
||||
shape_type="Triangle",
|
||||
triangle_type="EquilateralTriangle"
|
||||
shapeType="Triangle",
|
||||
triangleType="EquilateralTriangle"
|
||||
),
|
||||
shape.Shape(
|
||||
shape_type="Quadrilateral",
|
||||
quadrilateral_type="ComplexQuadrilateral"
|
||||
shapeType="Triangle",
|
||||
triangleType="IsoscelesTriangle"
|
||||
),
|
||||
shape.Shape(
|
||||
shapeType="Triangle",
|
||||
triangleType="EquilateralTriangle"
|
||||
),
|
||||
shape.Shape(
|
||||
shapeType="Quadrilateral",
|
||||
quadrilateralType="ComplexQuadrilateral"
|
||||
)
|
||||
],
|
||||
)
|
||||
from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral
|
||||
assert isinstance(inst, Drawing)
|
||||
assert isinstance(inst.main_shape, IsoscelesTriangle)
|
||||
self.assertEqual(len(inst.shapes), 4)
|
||||
assert isinstance(inst.shapes[0], EquilateralTriangle)
|
||||
assert isinstance(inst.shapes[1], IsoscelesTriangle)
|
||||
assert isinstance(inst.shapes[2], EquilateralTriangle)
|
||||
assert isinstance(inst.shapes[3], ComplexQuadrilateral)
|
||||
assert isinstance(inst["mainShape"], IsoscelesTriangle)
|
||||
self.assertEqual(len(inst["shapes"]), 4)
|
||||
from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral
|
||||
assert isinstance(inst["shapes"][0], EquilateralTriangle)
|
||||
assert isinstance(inst["shapes"][1], IsoscelesTriangle)
|
||||
assert isinstance(inst["shapes"][2], EquilateralTriangle)
|
||||
assert isinstance(inst["shapes"][3], ComplexQuadrilateral)
|
||||
|
||||
# Validate we cannot assign the None value to main_shape because the 'null' type
|
||||
# Validate we cannot assign the None value to mainShape because the 'null' type
|
||||
# is not one of the allowed types in the 'Shape' schema.
|
||||
err_msg = (r"Invalid type for variable '{}'. "
|
||||
r"Required value type is {} and passed type was {} at {}")
|
||||
err_msg = (r"Invalid inputs given to generate an instance of .+?Shape.+? "
|
||||
r"None of the oneOf schemas matched the input data.")
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiTypeError,
|
||||
err_msg.format(r"main_shape", r"one of \[ComplexQuadrilateral, EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle, SimpleQuadrilateral\]", r"NoneType", r"\['main_shape'\]")
|
||||
petstore_api.ApiValueError,
|
||||
err_msg
|
||||
):
|
||||
inst = Drawing(
|
||||
# 'main_shape' has type 'Shape', which is a oneOf [triangle, quadrilateral]
|
||||
Drawing(
|
||||
# 'mainShape' has type 'Shape', which is a oneOf [triangle, quadrilateral]
|
||||
# So the None value should not be allowed and an exception should be raised.
|
||||
main_shape=None,
|
||||
mainShape=None,
|
||||
)
|
||||
|
||||
"""
|
||||
We can pass in a Triangle instance in shapes
|
||||
Under the hood it is converted into a dict, and that dict payload
|
||||
does validate as a Shape, so this works
|
||||
"""
|
||||
from petstore_api.model.triangle import Triangle
|
||||
inst = Drawing(
|
||||
mainShape=isosceles_triangle,
|
||||
shapes=[
|
||||
Triangle(
|
||||
shapeType="Triangle",
|
||||
triangleType="EquilateralTriangle"
|
||||
)
|
||||
]
|
||||
)
|
||||
self.assertEqual(len(inst["shapes"]), 1)
|
||||
from petstore_api.model.triangle_interface import TriangleInterface
|
||||
shapes = inst["shapes"]
|
||||
assert isinstance(shapes[0], shape.Shape)
|
||||
assert isinstance(shapes[0], Triangle)
|
||||
assert isinstance(shapes[0], EquilateralTriangle)
|
||||
assert isinstance(shapes[0], TriangleInterface)
|
||||
|
||||
def test_deserialize_oneof_reference_with_null_type(self):
|
||||
"""
|
||||
@@ -137,14 +132,13 @@ class TestDrawing(unittest.TestCase):
|
||||
# Validate we can assign the None value to shape_or_null, because the 'null' type
|
||||
# is one of the allowed types in the 'ShapeOrNull' schema.
|
||||
inst = Drawing(
|
||||
# 'shape_or_null' has type 'ShapeOrNull', which is a oneOf [null, triangle, quadrilateral]
|
||||
shape_or_null=None,
|
||||
# 'shapeOrNull' has type 'ShapeOrNull', which is a oneOf [null, triangle, quadrilateral]
|
||||
shapeOrNull=None,
|
||||
)
|
||||
assert isinstance(inst, Drawing)
|
||||
self.assertFalse(hasattr(inst, 'main_shape'))
|
||||
self.assertTrue(hasattr(inst, 'shape_or_null'))
|
||||
self.assertIsNone(inst.shape_or_null)
|
||||
|
||||
self.assertFalse('mainShape' in inst)
|
||||
self.assertTrue('shapeOrNull' in inst)
|
||||
self.assertTrue(isinstance(inst["shapeOrNull"], NoneClass))
|
||||
|
||||
def test_deserialize_oneof_reference_with_nullable_type(self):
|
||||
"""
|
||||
@@ -154,17 +148,18 @@ class TestDrawing(unittest.TestCase):
|
||||
OpenAPI 3.0 and deprecated in 3.1).
|
||||
"""
|
||||
|
||||
# Validate we can assign the None value to nullable_shape, because the NullableShape
|
||||
# Validate we can assign the None value to nullableShape, because the NullableShape
|
||||
# has the 'nullable: true' attribute.
|
||||
inst = Drawing(
|
||||
# 'nullable_shape' has type 'NullableShape', which is a oneOf [triangle, quadrilateral]
|
||||
# 'nullableShape' has type 'NullableShape', which is a oneOf [triangle, quadrilateral]
|
||||
# and the 'nullable: true' attribute.
|
||||
nullable_shape=None,
|
||||
nullableShape=None,
|
||||
)
|
||||
assert isinstance(inst, Drawing)
|
||||
self.assertFalse(hasattr(inst, 'main_shape'))
|
||||
self.assertTrue(hasattr(inst, 'nullable_shape'))
|
||||
self.assertIsNone(inst.nullable_shape)
|
||||
self.assertFalse('mainShape' in inst)
|
||||
self.assertTrue('nullableShape' in inst)
|
||||
self.assertTrue(isinstance(inst["nullableShape"], NoneClass))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.enum_test import EnumTest
|
||||
from petstore_api.model.string_enum import StringEnum
|
||||
from petstore_api.model.array_of_enums import ArrayOfEnums
|
||||
from petstore_api.model.boolean_enum import BooleanEnum
|
||||
|
||||
|
||||
class TestEnumTest(unittest.TestCase):
|
||||
"""EnumTest unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testEnumTest(self):
|
||||
"""Test EnumTest"""
|
||||
required_kwargs = dict(enum_string_required='lower')
|
||||
|
||||
# inline array of enums
|
||||
model = EnumTest(
|
||||
inline_array_of_str_enum=[StringEnum('approved')],
|
||||
**required_kwargs
|
||||
)
|
||||
# refed array of enums
|
||||
model = EnumTest(
|
||||
array_of_str_enum=ArrayOfEnums([StringEnum('approved')]),
|
||||
**required_kwargs
|
||||
)
|
||||
|
||||
# inline bool enum
|
||||
model = EnumTest(
|
||||
enum_bool=False,
|
||||
**required_kwargs
|
||||
)
|
||||
# refed bool enum
|
||||
model = EnumTest(
|
||||
bool_enum=BooleanEnum(True),
|
||||
**required_kwargs
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -48,9 +48,9 @@ class TestExtraOptionsForPools(unittest.TestCase):
|
||||
|
||||
socket_options = ["extra", "socket", "options"]
|
||||
|
||||
config = petstore_api.Configuration(host="http://somehost.local:8080")
|
||||
config = petstore_api.Configuration(host="HOST")
|
||||
config.socket_options = socket_options
|
||||
config.proxy = "http://proxy.local:8080/"
|
||||
config.proxy = True
|
||||
|
||||
with patch("petstore_api.rest.urllib3.ProxyManager", StubProxyManager):
|
||||
api_client = petstore_api.ApiClient(config)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,137 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
from decimal import Decimal
|
||||
import datetime
|
||||
import unittest
|
||||
|
||||
import frozendict
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.format_test import FormatTest
|
||||
from petstore_api.schemas import BinarySchema, BytesSchema, Singleton
|
||||
|
||||
|
||||
class TestFormatTest(unittest.TestCase):
|
||||
"""FormatTest unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_FormatTest(self):
|
||||
"""Test FormatTest"""
|
||||
|
||||
required_args = dict(
|
||||
number=32.5,
|
||||
byte='a',
|
||||
date='2021-01-01',
|
||||
password='abcdefghij'
|
||||
)
|
||||
# int32
|
||||
# under min
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
model = FormatTest(int32=-2147483649, **required_args)
|
||||
# over max
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
model = FormatTest(int32=2147483648, **required_args)
|
||||
# valid values in range work
|
||||
valid_values = [-2147483648, 2147483647]
|
||||
for valid_value in valid_values:
|
||||
model = FormatTest(int32=valid_value, **required_args)
|
||||
assert model["int32"] == valid_value
|
||||
|
||||
# int64
|
||||
# under min
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
FormatTest(int64=-9223372036854775809, **required_args)
|
||||
# over max
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
FormatTest(int64=9223372036854775808, **required_args)
|
||||
# valid values in range work
|
||||
valid_values = [-9223372036854775808, 9223372036854775807]
|
||||
for valid_value in valid_values:
|
||||
model = FormatTest(int64=valid_value, **required_args)
|
||||
assert model["int64"] == valid_value
|
||||
|
||||
# float32
|
||||
# under min
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
FormatTest(float32=-3.402823466385289e+38, **required_args)
|
||||
# over max
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
FormatTest(float32=3.402823466385289e+38, **required_args)
|
||||
# valid values in range work
|
||||
valid_values = [-3.4028234663852886e+38, 3.4028234663852886e+38]
|
||||
for valid_value in valid_values:
|
||||
model = FormatTest(float32=valid_value, **required_args)
|
||||
assert model["float32"] == valid_value
|
||||
|
||||
# float64
|
||||
# under min, Decimal is used because flat can only store 64bit numbers and the max and min
|
||||
# take up more space than 64bit
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
FormatTest(float64=Decimal('-1.7976931348623157082e+308'), **required_args)
|
||||
# over max
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
FormatTest(float64=Decimal('1.7976931348623157082e+308'), **required_args)
|
||||
valid_values = [-1.7976931348623157E+308, 1.7976931348623157E+308]
|
||||
for valid_value in valid_values:
|
||||
model = FormatTest(float64=valid_value, **required_args)
|
||||
assert model["float64"] == valid_value
|
||||
|
||||
# unique_items with duplicates throws exception
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
FormatTest(arrayWithUniqueItems=[0, 1, 1], **required_args)
|
||||
# no duplicates works
|
||||
values = [0, 1, 2]
|
||||
model = FormatTest(arrayWithUniqueItems=values, **required_args)
|
||||
assert model["arrayWithUniqueItems"] == tuple(values)
|
||||
|
||||
# __bool__ value of noneProp is False
|
||||
model = FormatTest(noneProp=None, **required_args)
|
||||
assert isinstance(model["noneProp"], Singleton)
|
||||
self.assertFalse(model["noneProp"])
|
||||
self.assertTrue(model["noneProp"].is_none_oapg())
|
||||
|
||||
# binary check
|
||||
model = FormatTest(binary=b'123', **required_args)
|
||||
assert isinstance(model["binary"], BinarySchema)
|
||||
assert isinstance(model["binary"], BytesSchema)
|
||||
assert isinstance(model["binary"], bytes)
|
||||
assert model == frozendict.frozendict(
|
||||
binary=b'123',
|
||||
number=Decimal(32.5),
|
||||
byte='a',
|
||||
date='2021-01-01',
|
||||
password='abcdefghij'
|
||||
)
|
||||
|
||||
def test_multiple_of(self):
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.exceptions.ApiValueError,
|
||||
r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)"
|
||||
):
|
||||
FormatTest(
|
||||
byte='3',
|
||||
date=datetime.date(2000, 1, 1),
|
||||
password="abcdefghijkl",
|
||||
integer=31, # Value is supposed to be multiple of '2'. An error must be raised
|
||||
number=65.0,
|
||||
float=62.4
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -9,238 +9,125 @@
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model import apple
|
||||
from petstore_api.model import banana
|
||||
from petstore_api.model.fruit import Fruit
|
||||
from petstore_api import schemas
|
||||
|
||||
|
||||
class TestFruit(unittest.TestCase):
|
||||
"""Fruit unit test stubs"""
|
||||
|
||||
length_cm = 20.3
|
||||
color = 'yellow'
|
||||
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_fruit_with_additional_props(self):
|
||||
# including extra parameters works because the oneOf models include additionalProperties
|
||||
some_value = 'some_value'
|
||||
some_fruit = Fruit(
|
||||
color=self.color,
|
||||
length_cm=self.length_cm,
|
||||
unknown_property=some_value
|
||||
)
|
||||
assert some_fruit['unknown_property'] == some_value
|
||||
|
||||
def test_fruit_assigning_additional_props_in_client(self):
|
||||
# setting a value that doesn't exist works because additional_properties_type allows any type
|
||||
other_fruit = Fruit(length_cm=self.length_cm, color=self.color)
|
||||
blah = 'blah'
|
||||
other_fruit['a'] = blah
|
||||
assert other_fruit.a == blah
|
||||
|
||||
# with setattr
|
||||
setattr(other_fruit, 'b', blah)
|
||||
assert other_fruit.b == blah
|
||||
|
||||
self.assertEqual(
|
||||
other_fruit.to_dict(),
|
||||
{
|
||||
'a': 'blah',
|
||||
'b': 'blah',
|
||||
'length_cm': self.length_cm,
|
||||
'color': self.color
|
||||
}
|
||||
)
|
||||
|
||||
def test_fruit_access_errors(self):
|
||||
fruit = Fruit(length_cm=self.length_cm, color=self.color)
|
||||
|
||||
# getting a value that doesn't exist raises an exception
|
||||
# with a key
|
||||
with self.assertRaises(AttributeError):
|
||||
invalid_variable = fruit['cultivar']
|
||||
|
||||
# Per Python doc, if the named attribute does not exist,
|
||||
# default is returned if provided, otherwise AttributeError is raised.
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(fruit, 'cultivar')
|
||||
|
||||
def test_fruit_attribute_access(self):
|
||||
fruit = Fruit(length_cm=self.length_cm, color=self.color)
|
||||
|
||||
# Assert that we can call the builtin hasattr() function.
|
||||
# hasattr should return False for non-existent attribute.
|
||||
# Internally hasattr catches the AttributeError exception.
|
||||
self.assertFalse(hasattr(fruit, 'invalid_variable'))
|
||||
|
||||
# Assert that we can call the builtin hasattr() function.
|
||||
# hasattr should return True for existent attribute.
|
||||
self.assertTrue(hasattr(fruit, 'color'))
|
||||
|
||||
# with getattr
|
||||
# Per Python doc, if the named attribute does not exist,
|
||||
# default is returned if provided.
|
||||
self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value')
|
||||
self.assertEqual(fruit.get('cultivar'), None)
|
||||
self.assertEqual(fruit.get('cultivar', 'some value'), 'some value')
|
||||
|
||||
def test_banana_fruit(self):
|
||||
def testFruit(self):
|
||||
"""Test Fruit"""
|
||||
|
||||
# make an instance of Fruit, a composed schema oneOf model
|
||||
# banana test
|
||||
fruit = Fruit(length_cm=self.length_cm, color=self.color)
|
||||
length_cm = 20.3
|
||||
color = 'yellow'
|
||||
fruit = Fruit(lengthCm=length_cm, color=color)
|
||||
# check its properties
|
||||
self.assertEqual(fruit.length_cm, self.length_cm)
|
||||
self.assertEqual(fruit['length_cm'], self.length_cm)
|
||||
self.assertEqual(fruit.get('length_cm'), self.length_cm)
|
||||
self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm)
|
||||
self.assertEqual(fruit.color, self.color)
|
||||
self.assertEqual(fruit['color'], self.color)
|
||||
self.assertEqual(getattr(fruit, 'color'), self.color)
|
||||
self.assertEqual(fruit['lengthCm'], length_cm)
|
||||
self.assertEqual(fruit.get('lengthCm'), length_cm)
|
||||
self.assertEqual(fruit['color'], color)
|
||||
self.assertEqual(fruit.get('color'), color)
|
||||
|
||||
# check the dict representation
|
||||
self.assertEqual(
|
||||
fruit.to_dict(),
|
||||
fruit,
|
||||
{
|
||||
'length_cm': self.length_cm,
|
||||
'color': self.color
|
||||
'lengthCm': length_cm,
|
||||
'color': color
|
||||
}
|
||||
)
|
||||
# setting values after instance creation is not allowed
|
||||
with self.assertRaises(TypeError):
|
||||
fruit['color'] = 'some value'
|
||||
|
||||
# getting a value that doesn't exist raises an exception
|
||||
# with a key
|
||||
with self.assertRaises(KeyError):
|
||||
assert fruit['cultivar']
|
||||
assert fruit.get_item_oapg('cultivar') is schemas.unset
|
||||
|
||||
# make sure that the ModelComposed class properties are correct
|
||||
# model._composed_schemas stores the anyOf/allOf/oneOf info
|
||||
self.assertEqual(
|
||||
fruit._composed_schemas,
|
||||
{
|
||||
'anyOf': [],
|
||||
'allOf': [],
|
||||
'oneOf': [
|
||||
apple.Apple,
|
||||
banana.Banana,
|
||||
],
|
||||
}
|
||||
)
|
||||
# model._composed_instances is a list of the instances that were
|
||||
# made from the anyOf/allOf/OneOf classes in model._composed_schemas
|
||||
self.assertEqual(len(fruit._composed_instances), 1)
|
||||
for composed_instance in fruit._composed_instances:
|
||||
if composed_instance.__class__ == banana.Banana:
|
||||
banana_instance = composed_instance
|
||||
self.assertEqual(
|
||||
fruit._composed_instances,
|
||||
[banana_instance]
|
||||
)
|
||||
# model._var_name_to_model_instances maps the variable name to the
|
||||
# model instances which store that variable
|
||||
print(fruit._var_name_to_model_instances)
|
||||
self.assertEqual(
|
||||
fruit._var_name_to_model_instances,
|
||||
{
|
||||
'color': [fruit],
|
||||
'length_cm': [fruit, banana_instance],
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
fruit._additional_properties_model_instances, [fruit]
|
||||
Fruit.MetaOapg.one_of(),
|
||||
[
|
||||
apple.Apple,
|
||||
banana.Banana,
|
||||
],
|
||||
)
|
||||
|
||||
# if we modify one of the properties owned by multiple
|
||||
# model_instances we get an exception when we try to access that
|
||||
# property because the retrieved values are not all the same
|
||||
banana_instance.length_cm = 4.56
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
some_length_cm = fruit.length_cm
|
||||
"""
|
||||
including extra parameters does not raise an exception
|
||||
because objects support additional properties by default
|
||||
"""
|
||||
kwargs = dict(
|
||||
color=color,
|
||||
lengthCm=length_cm,
|
||||
additional_string='some value',
|
||||
additional_date='2021-01-02',
|
||||
)
|
||||
|
||||
fruit = Fruit.from_openapi_data_oapg(**kwargs)
|
||||
self.assertEqual(
|
||||
fruit,
|
||||
kwargs
|
||||
)
|
||||
|
||||
fruit = Fruit(**kwargs)
|
||||
self.assertEqual(
|
||||
fruit,
|
||||
kwargs
|
||||
)
|
||||
|
||||
# including input parameters for two oneOf instances raise an exception
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
fruit = Fruit(
|
||||
length_cm=self.length_cm,
|
||||
Fruit(
|
||||
lengthCm=length_cm,
|
||||
cultivar='granny smith'
|
||||
)
|
||||
|
||||
def test_apple_fruit(self):
|
||||
|
||||
# make an instance of Fruit, a composed schema oneOf model
|
||||
# apple test
|
||||
color = 'red'
|
||||
cultivar = 'golden delicious'
|
||||
fruit = Fruit(color=color, cultivar=cultivar)
|
||||
# check its properties
|
||||
self.assertEqual(fruit.color, color)
|
||||
self.assertEqual(fruit['color'], color)
|
||||
self.assertEqual(getattr(fruit, 'color'), color)
|
||||
self.assertEqual(fruit.cultivar, cultivar)
|
||||
self.assertEqual(fruit['cultivar'], cultivar)
|
||||
self.assertEqual(getattr(fruit, 'cultivar'), cultivar)
|
||||
# check the dict representation
|
||||
self.assertEqual(
|
||||
fruit.to_dict(),
|
||||
fruit,
|
||||
{
|
||||
'color': color,
|
||||
'cultivar': cultivar
|
||||
}
|
||||
)
|
||||
|
||||
# model._composed_instances is a list of the instances that were
|
||||
# made from the anyOf/allOf/OneOf classes in model._composed_schemas
|
||||
for composed_instance in fruit._composed_instances:
|
||||
if composed_instance.__class__ == apple.Apple:
|
||||
apple_instance = composed_instance
|
||||
self.assertEqual(
|
||||
fruit._composed_instances,
|
||||
[apple_instance]
|
||||
)
|
||||
# model._var_name_to_model_instances maps the variable name to the
|
||||
# model instances which store that variable
|
||||
self.assertEqual(
|
||||
fruit._var_name_to_model_instances,
|
||||
{
|
||||
'color': [fruit],
|
||||
'cultivar': [fruit, apple_instance],
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
fruit._additional_properties_model_instances, [fruit]
|
||||
)
|
||||
|
||||
def test_null_fruit(self):
|
||||
def testFruitNullValue(self):
|
||||
# Since 'apple' is nullable, validate we can create an apple with the 'null' value.
|
||||
fruit = apple.Apple(None)
|
||||
self.assertIsNone(fruit)
|
||||
assert isinstance(fruit, schemas.Singleton)
|
||||
assert isinstance(fruit, apple.Apple)
|
||||
assert fruit.is_none_oapg() is True
|
||||
|
||||
# 'banana' is not nullable.
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
# TODO cast this into ApiTypeError?
|
||||
with self.assertRaises(TypeError):
|
||||
banana.Banana(None)
|
||||
|
||||
# Since 'fruit' has oneOf 'apple', 'banana' and 'apple' is nullable,
|
||||
# validate we can create a fruit with the 'null' value.
|
||||
fruit = Fruit(None)
|
||||
self.assertIsNone(fruit)
|
||||
|
||||
# Redo the same thing, this time passing a null Apple to the Fruit constructor.
|
||||
fruit = Fruit(apple.Apple(None))
|
||||
self.assertIsNone(fruit)
|
||||
|
||||
def test_fruit_with_invalid_input_type(self):
|
||||
|
||||
"""
|
||||
color must be a str, color's str type is only defined at the Fruit level
|
||||
Banana + Apple would allow color to be assigned with any type of value
|
||||
"""
|
||||
invalid_value = 1
|
||||
with self.assertRaises(petstore_api.ApiTypeError):
|
||||
fruit = Fruit(color=invalid_value, length_cm=self.length_cm)
|
||||
assert isinstance(fruit, schemas.Singleton)
|
||||
assert isinstance(fruit, apple.Apple)
|
||||
assert isinstance(fruit, Fruit)
|
||||
assert fruit.is_none_oapg() is True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -10,18 +10,17 @@
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model import apple_req
|
||||
from petstore_api.model import banana_req
|
||||
from petstore_api.model.fruit_req import FruitReq
|
||||
from petstore_api import schemas
|
||||
|
||||
|
||||
class TestFruitReq(unittest.TestCase):
|
||||
"""FruitReq unit test stubs"""
|
||||
length_cm = 20.3
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
@@ -29,106 +28,71 @@ class TestFruitReq(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_fruit_access_errors(self):
|
||||
fruit = FruitReq(length_cm=self.length_cm)
|
||||
|
||||
# setting a value that doesn't exist raises an exception
|
||||
# with a key
|
||||
with self.assertRaises(AttributeError):
|
||||
fruit['invalid_variable'] = 'some value'
|
||||
# with setattr
|
||||
with self.assertRaises(AttributeError):
|
||||
setattr(fruit, 'invalid_variable', 'some value')
|
||||
|
||||
# getting a value that doesn't exist raises an exception
|
||||
# with a key
|
||||
with self.assertRaises(AttributeError):
|
||||
invalid_variable = fruit['cultivar']
|
||||
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(fruit, 'cultivar')
|
||||
|
||||
def test_FruitReq_banana(self):
|
||||
def testFruitReq(self):
|
||||
"""Test FruitReq"""
|
||||
|
||||
# make an instance of Fruit, a composed schema oneOf model
|
||||
# banana test
|
||||
fruit = FruitReq(length_cm=self.length_cm)
|
||||
length_cm = 20.3
|
||||
fruit = FruitReq(lengthCm=length_cm)
|
||||
# check its properties
|
||||
self.assertEqual(fruit.length_cm, self.length_cm)
|
||||
self.assertEqual(fruit['length_cm'], self.length_cm)
|
||||
self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm)
|
||||
self.assertEqual(fruit.lengthCm, length_cm)
|
||||
self.assertEqual(fruit['lengthCm'], length_cm)
|
||||
self.assertEqual(getattr(fruit, 'lengthCm'), length_cm)
|
||||
# check the dict representation
|
||||
self.assertEqual(
|
||||
fruit.to_dict(),
|
||||
fruit,
|
||||
{
|
||||
'length_cm': self.length_cm,
|
||||
'lengthCm': length_cm,
|
||||
}
|
||||
)
|
||||
# setting values after instance creation is not allowed
|
||||
with self.assertRaises(TypeError):
|
||||
fruit['lengthCm'] = 'some value'
|
||||
|
||||
# setting values after instance creation is not allowed
|
||||
with self.assertRaises(AttributeError):
|
||||
setattr(fruit, 'lengthCm', 'some value')
|
||||
|
||||
# getting a value that doesn't exist raises an exception
|
||||
# with a key
|
||||
with self.assertRaises(KeyError):
|
||||
fruit['cultivar']
|
||||
with self.assertRaises(AttributeError):
|
||||
fruit.cultivar
|
||||
assert fruit.get_item_oapg('cultivar') is schemas.unset
|
||||
|
||||
# with getattr
|
||||
self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value')
|
||||
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(fruit, 'cultivar')
|
||||
|
||||
# make sure that the ModelComposed class properties are correct
|
||||
# model._composed_schemas stores the anyOf/allOf/oneOf info
|
||||
self.assertEqual(
|
||||
fruit._composed_schemas,
|
||||
{
|
||||
'anyOf': [],
|
||||
'allOf': [],
|
||||
'oneOf': [
|
||||
apple_req.AppleReq,
|
||||
banana_req.BananaReq,
|
||||
type(None),
|
||||
],
|
||||
}
|
||||
)
|
||||
# model._composed_instances is a list of the instances that were
|
||||
# made from the anyOf/allOf/OneOf classes in model._composed_schemas
|
||||
for composed_instance in fruit._composed_instances:
|
||||
if composed_instance.__class__ == banana_req.BananaReq:
|
||||
banana_instance = composed_instance
|
||||
self.assertEqual(
|
||||
fruit._composed_instances,
|
||||
[banana_instance]
|
||||
)
|
||||
# model._var_name_to_model_instances maps the variable name to the
|
||||
# model instances which store that variable
|
||||
self.assertEqual(
|
||||
fruit._var_name_to_model_instances,
|
||||
{
|
||||
'length_cm': [fruit, banana_instance],
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
fruit._additional_properties_model_instances, [fruit]
|
||||
FruitReq.MetaOapg.one_of(),
|
||||
[
|
||||
schemas.NoneSchema,
|
||||
apple_req.AppleReq,
|
||||
banana_req.BananaReq,
|
||||
],
|
||||
)
|
||||
|
||||
# if we modify one of the properties owned by multiple
|
||||
# model_instances we get an exception when we try to access that
|
||||
# property because the retrieved values are not all the same
|
||||
banana_instance.length_cm = 4.56
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
some_length_cm = fruit.length_cm
|
||||
|
||||
def test_invalid_inputs(self):
|
||||
# including extra parameters raises an exception
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
fruit = FruitReq(
|
||||
length_cm=self.length_cm,
|
||||
FruitReq(
|
||||
length_cm=length_cm,
|
||||
unknown_property='some value'
|
||||
)
|
||||
|
||||
# including input parameters for two oneOf instances raise an exception
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
fruit = FruitReq(
|
||||
length_cm=self.length_cm,
|
||||
FruitReq(
|
||||
length_cm=length_cm,
|
||||
cultivar='granny smith'
|
||||
)
|
||||
|
||||
def test_FruitReq_apple(self):
|
||||
"""Test FruitReq"""
|
||||
|
||||
# make an instance of Fruit, a composed schema oneOf model
|
||||
# apple test
|
||||
cultivar = 'golden delicious'
|
||||
fruit = FruitReq(cultivar=cultivar)
|
||||
@@ -138,37 +102,18 @@ class TestFruitReq(unittest.TestCase):
|
||||
self.assertEqual(getattr(fruit, 'cultivar'), cultivar)
|
||||
# check the dict representation
|
||||
self.assertEqual(
|
||||
fruit.to_dict(),
|
||||
fruit,
|
||||
{
|
||||
'cultivar': cultivar
|
||||
}
|
||||
)
|
||||
|
||||
# model._composed_instances is a list of the instances that were
|
||||
# made from the anyOf/allOf/OneOf classes in model._composed_schemas
|
||||
for composed_instance in fruit._composed_instances:
|
||||
if composed_instance.__class__ == apple_req.AppleReq:
|
||||
apple_instance = composed_instance
|
||||
self.assertEqual(
|
||||
fruit._composed_instances,
|
||||
[apple_instance]
|
||||
)
|
||||
# model._var_name_to_model_instances maps the variable name to the
|
||||
# model instances which store that variable
|
||||
self.assertEqual(
|
||||
fruit._var_name_to_model_instances,
|
||||
{
|
||||
'cultivar': [fruit, apple_instance],
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
fruit._additional_properties_model_instances, [fruit]
|
||||
)
|
||||
|
||||
def test_null_fruit(self):
|
||||
# we can pass in None
|
||||
fruit = FruitReq(None)
|
||||
assert fruit is None
|
||||
assert isinstance(fruit, schemas.Singleton)
|
||||
assert isinstance(fruit, FruitReq)
|
||||
assert isinstance(fruit, schemas.NoneSchema)
|
||||
assert fruit.is_none_oapg() is True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -10,19 +10,17 @@
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
import frozendict
|
||||
|
||||
from petstore_api.model import apple
|
||||
from petstore_api.model import banana
|
||||
from petstore_api.model.gm_fruit import GmFruit
|
||||
|
||||
from petstore_api import schemas
|
||||
|
||||
class TestGmFruit(unittest.TestCase):
|
||||
"""GmFruit unit test stubs"""
|
||||
length_cm = 20.3
|
||||
color = 'yellow'
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
@@ -30,159 +28,88 @@ class TestGmFruit(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_set_addprop_attributes(self):
|
||||
# setting a value that doesn't exist works because additional_properties_type allows any type
|
||||
other_fruit = GmFruit(length_cm=self.length_cm, color=self.color)
|
||||
blah = 'blah'
|
||||
other_fruit['a'] = blah
|
||||
assert other_fruit.a == blah
|
||||
|
||||
# with setattr
|
||||
setattr(other_fruit, 'b', blah)
|
||||
assert other_fruit.b == blah
|
||||
|
||||
self.assertEqual(
|
||||
other_fruit.to_dict(),
|
||||
{
|
||||
'a': 'blah',
|
||||
'b': 'blah',
|
||||
'length_cm': self.length_cm,
|
||||
'color': self.color
|
||||
}
|
||||
)
|
||||
|
||||
def test_banana_fruit(self):
|
||||
def testGmFruit(self):
|
||||
"""Test GmFruit"""
|
||||
|
||||
# make an instance of GmFruit, a composed schema anyOf model
|
||||
# banana test
|
||||
fruit = GmFruit(length_cm=self.length_cm, color=self.color)
|
||||
length_cm = 20.3
|
||||
color = 'yellow'
|
||||
cultivar = 'banaple'
|
||||
fruit = GmFruit(lengthCm=length_cm, color=color, cultivar=cultivar)
|
||||
assert isinstance(fruit, banana.Banana)
|
||||
assert isinstance(fruit, apple.Apple)
|
||||
assert isinstance(fruit, frozendict.frozendict)
|
||||
assert isinstance(fruit, GmFruit)
|
||||
# check its properties
|
||||
self.assertEqual(fruit.length_cm, self.length_cm)
|
||||
self.assertEqual(fruit['length_cm'], self.length_cm)
|
||||
self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm)
|
||||
self.assertEqual(fruit.color, self.color)
|
||||
self.assertEqual(fruit['color'], self.color)
|
||||
self.assertEqual(getattr(fruit, 'color'), self.color)
|
||||
self.assertEqual(fruit['lengthCm'], length_cm)
|
||||
self.assertEqual(fruit['color'], color)
|
||||
|
||||
# check the dict representation
|
||||
self.assertEqual(
|
||||
fruit.to_dict(),
|
||||
fruit,
|
||||
{
|
||||
'length_cm': self.length_cm,
|
||||
'color': self.color
|
||||
'lengthCm': length_cm,
|
||||
'color': color,
|
||||
'cultivar': cultivar
|
||||
}
|
||||
)
|
||||
|
||||
# getting a value that doesn't exist raises an exception
|
||||
# with a key
|
||||
# unset key access raises KeyError
|
||||
with self.assertRaises(KeyError):
|
||||
fruit["origin"]
|
||||
with self.assertRaises(AttributeError):
|
||||
invalid_variable = fruit['cultivar']
|
||||
# with getattr
|
||||
self.assertTrue(getattr(fruit, 'cultivar', 'some value'), 'some value')
|
||||
fruit.origin
|
||||
assert fruit.get_item_oapg("origin") is schemas.unset
|
||||
|
||||
with self.assertRaises(AttributeError):
|
||||
invalid_variable = getattr(fruit, 'cultivar')
|
||||
with self.assertRaises(KeyError):
|
||||
fruit['unknown_variable']
|
||||
assert fruit.get_item_oapg("unknown_variable") is schemas.unset
|
||||
# with getattr
|
||||
self.assertTrue(getattr(fruit, 'origin', 'some value'), 'some value')
|
||||
|
||||
# make sure that the ModelComposed class properties are correct
|
||||
# model._composed_schemas stores the anyOf/allOf/oneOf info
|
||||
self.assertEqual(
|
||||
fruit._composed_schemas,
|
||||
{
|
||||
'anyOf': [
|
||||
apple.Apple,
|
||||
banana.Banana,
|
||||
],
|
||||
'allOf': [],
|
||||
'oneOf': [],
|
||||
}
|
||||
)
|
||||
# model._composed_instances is a list of the instances that were
|
||||
# made from the anyOf/allOf/OneOf classes in model._composed_schemas
|
||||
for composed_instance in fruit._composed_instances:
|
||||
if composed_instance.__class__ == banana.Banana:
|
||||
banana_instance = composed_instance
|
||||
self.assertEqual(
|
||||
fruit._composed_instances,
|
||||
[banana_instance]
|
||||
)
|
||||
# model._var_name_to_model_instances maps the variable name to the
|
||||
# model instances which store that variable
|
||||
self.assertEqual(
|
||||
fruit._var_name_to_model_instances,
|
||||
{
|
||||
'color': [fruit],
|
||||
'length_cm': [fruit, banana_instance],
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
fruit._additional_properties_model_instances, [fruit]
|
||||
GmFruit.MetaOapg.any_of(),
|
||||
[
|
||||
apple.Apple,
|
||||
banana.Banana,
|
||||
],
|
||||
)
|
||||
|
||||
# including extra parameters works
|
||||
GmFruit(
|
||||
color=color,
|
||||
length_cm=length_cm,
|
||||
cultivar=cultivar,
|
||||
unknown_property='some value'
|
||||
)
|
||||
|
||||
def test_combo_fruit(self):
|
||||
# including input parameters for both anyOf instances works
|
||||
cultivar = 'banaple'
|
||||
color = 'orange'
|
||||
fruit = GmFruit(
|
||||
color=color,
|
||||
cultivar=cultivar,
|
||||
length_cm=self.length_cm
|
||||
length_cm=length_cm
|
||||
)
|
||||
self.assertEqual(fruit.color, color)
|
||||
self.assertEqual(fruit['color'], color)
|
||||
self.assertEqual(getattr(fruit, 'color'), color)
|
||||
self.assertEqual(fruit.cultivar, cultivar)
|
||||
self.assertEqual(fruit['cultivar'], cultivar)
|
||||
self.assertEqual(getattr(fruit, 'cultivar'), cultivar)
|
||||
self.assertEqual(fruit.length_cm, self.length_cm)
|
||||
self.assertEqual(fruit['length_cm'], self.length_cm)
|
||||
self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm)
|
||||
self.assertEqual(fruit['length_cm'], length_cm)
|
||||
|
||||
# model._composed_instances is a list of the instances that were
|
||||
# made from the anyOf/allOf/OneOf classes in model._composed_schemas
|
||||
for composed_instance in fruit._composed_instances:
|
||||
if composed_instance.__class__ == apple.Apple:
|
||||
apple_instance = composed_instance
|
||||
elif composed_instance.__class__ == banana.Banana:
|
||||
banana_instance = composed_instance
|
||||
self.assertEqual(
|
||||
fruit._composed_instances,
|
||||
[apple_instance, banana_instance]
|
||||
)
|
||||
# model._var_name_to_model_instances maps the variable name to the
|
||||
# model instances which store that variable
|
||||
self.assertEqual(
|
||||
fruit._var_name_to_model_instances,
|
||||
{
|
||||
'color': [fruit],
|
||||
'length_cm': [fruit, banana_instance],
|
||||
'cultivar': [fruit, apple_instance],
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
fruit._additional_properties_model_instances, [fruit]
|
||||
)
|
||||
|
||||
def test_apple_fruit(self):
|
||||
# make an instance of GmFruit, a composed schema anyOf model
|
||||
# apple test
|
||||
color = 'red'
|
||||
cultivar = 'golden delicious'
|
||||
origin = 'California'
|
||||
fruit = GmFruit(color=color, cultivar=cultivar, origin=origin)
|
||||
# check its properties
|
||||
self.assertEqual(fruit.color, color)
|
||||
self.assertEqual(fruit['color'], color)
|
||||
self.assertEqual(getattr(fruit, 'color'), color)
|
||||
self.assertEqual(fruit.cultivar, cultivar)
|
||||
self.assertEqual(fruit['cultivar'], cultivar)
|
||||
self.assertEqual(getattr(fruit, 'cultivar'), cultivar)
|
||||
|
||||
self.assertEqual(fruit.origin, origin)
|
||||
self.assertEqual(fruit['origin'], origin)
|
||||
self.assertEqual(getattr(fruit, 'origin'), origin)
|
||||
|
||||
# check the dict representation
|
||||
self.assertEqual(
|
||||
fruit.to_dict(),
|
||||
fruit,
|
||||
{
|
||||
'color': color,
|
||||
'cultivar': cultivar,
|
||||
@@ -190,28 +117,6 @@ class TestGmFruit(unittest.TestCase):
|
||||
}
|
||||
)
|
||||
|
||||
# model._composed_instances is a list of the instances that were
|
||||
# made from the anyOf/allOf/OneOf classes in model._composed_schemas
|
||||
for composed_instance in fruit._composed_instances:
|
||||
if composed_instance.__class__ == apple.Apple:
|
||||
apple_instance = composed_instance
|
||||
self.assertEqual(
|
||||
fruit._composed_instances,
|
||||
[apple_instance]
|
||||
)
|
||||
# model._var_name_to_model_instances maps the variable name to the
|
||||
# model instances which store that variable
|
||||
self.assertEqual(
|
||||
fruit._var_name_to_model_instances,
|
||||
{
|
||||
'color': [fruit],
|
||||
'cultivar': [fruit, apple_instance],
|
||||
'origin': [fruit, apple_instance],
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
fruit._additional_properties_model_instances, [fruit]
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -28,15 +28,28 @@ class TestIntegerEnumOneValue(unittest.TestCase):
|
||||
|
||||
def testIntegerEnumOneValue(self):
|
||||
"""Test IntegerEnumOneValue"""
|
||||
model = IntegerEnumOneValue()
|
||||
assert model.value == 0, "With only one option, the value is assigned automatically"
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
"""
|
||||
a value must be passed in
|
||||
We cannot auto assign values because that would break composition if
|
||||
received payloads included this with no inputs and we the 0 value to the data to the incoming payload
|
||||
One is not allowed to mutate incoming payloads because then:
|
||||
- order of composed schema ingestion matters
|
||||
- one can have default value collisions
|
||||
- the added data will make expected schemas not match payloads
|
||||
"""
|
||||
model = IntegerEnumOneValue()
|
||||
|
||||
model = IntegerEnumOneValue(0)
|
||||
assert model.value == 0, "We can also pass in the value as a positional arg"
|
||||
assert model == 0, "We can also pass in the value as a positional arg"
|
||||
|
||||
model = IntegerEnumOneValue(value=0)
|
||||
assert model.value == 0, "We can also pass in the value as a named argument"
|
||||
# one cannot pass the value with the value keyword
|
||||
with self.assertRaises(TypeError):
|
||||
model = IntegerEnumOneValue(value=0)
|
||||
|
||||
# one can pass in the enum value
|
||||
model = IntegerEnumOneValue(IntegerEnumOneValue.POSITIVE_0)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
import json
|
||||
from collections import namedtuple
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.animal import Animal
|
||||
from petstore_api.model.dog import Dog
|
||||
|
||||
|
||||
class TestReadOnlyForComposedSchema(unittest.TestCase):
|
||||
"""TestReadOnlyForComposedSchema unit test"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testReadOnlyForComposedSchema(self):
|
||||
"""Test ReadOnlyForComposedSchema"""
|
||||
MockResponse = namedtuple('MockResponse', 'data')
|
||||
client = petstore_api.ApiClient()
|
||||
""" deserialize dict(str, Enum_Test) """
|
||||
data = {
|
||||
"Dog": {
|
||||
"class_name": "Dog",
|
||||
"breed": "BullDog",
|
||||
"color": "Black",
|
||||
"tail": True
|
||||
}
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
deserialized = client.deserialize(response, ({str: (Dog,)},), True)
|
||||
assert isinstance(deserialized, dict)
|
||||
assert isinstance(deserialized['Dog'], Dog)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,50 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api import schemas
|
||||
from petstore_api import api_client
|
||||
|
||||
|
||||
class TestJSONEncoder(unittest.TestCase):
|
||||
"""Fruit unit test stubs"""
|
||||
serializer = api_client.JSONEncoder()
|
||||
|
||||
def test_receive_encode_str_types(self):
|
||||
schema_to_value = {
|
||||
schemas.StrSchema: 'hi',
|
||||
schemas.DateSchema: '2021-05-09',
|
||||
schemas.DateTimeSchema: '2020-01-01T00:00:00'
|
||||
}
|
||||
for schema, value in schema_to_value.items():
|
||||
inst = schema.from_openapi_data_oapg(value)
|
||||
assert value == self.serializer.default(inst)
|
||||
|
||||
def test_receive_encode_numeric_types(self):
|
||||
value_to_schema = {
|
||||
1: schemas.IntSchema,
|
||||
1.0: schemas.Float32Schema,
|
||||
3.14: schemas.Float32Schema,
|
||||
4: schemas.NumberSchema,
|
||||
4.0: schemas.NumberSchema,
|
||||
7.14: schemas.NumberSchema,
|
||||
}
|
||||
for value, schema in value_to_schema.items():
|
||||
inst = schema.from_openapi_data_oapg(value)
|
||||
pre_serialize_value = self.serializer.default(inst)
|
||||
assert value == pre_serialize_value and type(value) == type(pre_serialize_value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -14,16 +14,6 @@ import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import whale
|
||||
except ImportError:
|
||||
whale = sys.modules[
|
||||
'petstore_api.model.whale']
|
||||
try:
|
||||
from petstore_api.model import zebra
|
||||
except ImportError:
|
||||
zebra = sys.modules[
|
||||
'petstore_api.model.zebra']
|
||||
from petstore_api.model.mammal import Mammal
|
||||
|
||||
|
||||
@@ -39,10 +29,26 @@ class TestMammal(unittest.TestCase):
|
||||
def testMammal(self):
|
||||
"""Test Mammal"""
|
||||
|
||||
# tests that we can make a BasquePig by traveling through descendant discriminator in Pig
|
||||
model = Mammal(class_name="BasquePig")
|
||||
# tests that we can make a BasquePig by traveling through discriminator in Pig
|
||||
m = Mammal(className="BasquePig")
|
||||
from petstore_api.model import pig
|
||||
from petstore_api.model import basque_pig
|
||||
assert isinstance(model, basque_pig.BasquePig)
|
||||
assert isinstance(m, Mammal)
|
||||
assert isinstance(m, basque_pig.BasquePig)
|
||||
assert isinstance(m, pig.Pig)
|
||||
|
||||
# can make a Whale
|
||||
m = Mammal(className="whale")
|
||||
from petstore_api.model import whale
|
||||
assert isinstance(m, whale.Whale)
|
||||
|
||||
# can use the enum value
|
||||
m = Mammal(className=whale.Whale.MetaOapg.properties.className.WHALE)
|
||||
assert isinstance(m, whale.Whale)
|
||||
|
||||
from petstore_api.model import zebra
|
||||
m = Mammal(className='zebra')
|
||||
assert isinstance(m, zebra.Zebra)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from petstore_api.exceptions import ApiAttributeError
|
||||
|
||||
import petstore_api
|
||||
|
||||
try:
|
||||
from petstore_api.model import mole
|
||||
except ImportError:
|
||||
mole = sys.modules["petstore_api.model.mole"]
|
||||
|
||||
|
||||
class TestMole(unittest.TestCase):
|
||||
"""Triangle unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testMole(self):
|
||||
# includes required parameters that are `readOnly=False` and not defined `readOnly`
|
||||
my_mole = mole.Mole(smell="dirt", hearing=False)
|
||||
assert my_mole.smell == "dirt"
|
||||
assert my_mole.hearing is False
|
||||
|
||||
# includes required parameters that `readOnly=False`, an optional `readOnly=False` and not defined `readOnly`
|
||||
my_mole = mole.Mole(smell="dirt", taste="kfc", hearing=True)
|
||||
assert my_mole.smell == "dirt"
|
||||
assert my_mole.taste == "kfc"
|
||||
assert my_mole.hearing is True
|
||||
|
||||
# includes required parameters that `readOnly=False`, and required not defined `readOnly`, and an optional not defined
|
||||
my_mole = mole.Mole(smell="dirt", seeing_ghosts=True, hearing=False)
|
||||
assert my_mole.smell == "dirt"
|
||||
assert my_mole.seeing_ghosts is True
|
||||
assert my_mole.hearing is False
|
||||
|
||||
# passing in required readOnly parameters raises an exception
|
||||
with self.assertRaises(ApiAttributeError):
|
||||
mole.Mole(smell="dirt", hearing=False, blind=True)
|
||||
|
||||
# passing in optional readOnly parameters raises an exception
|
||||
with self.assertRaises(ApiAttributeError):
|
||||
mole.Mole(smell="dirt", hearing=False, touch=True)
|
||||
|
||||
# passing in required an optional parameters with readOnly true or false works with from_openapi_data
|
||||
my_mole = mole.Mole._from_openapi_data(
|
||||
smell="dirt",
|
||||
taste="kfc",
|
||||
blind=True,
|
||||
touch=False,
|
||||
hearing=True,
|
||||
seeing_ghosts=False,
|
||||
)
|
||||
assert my_mole.smell == "dirt"
|
||||
assert my_mole.taste == "kfc"
|
||||
assert my_mole.blind is True
|
||||
assert my_mole.touch is False
|
||||
assert my_mole.hearing is True
|
||||
assert my_mole.seeing_ghosts is False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,34 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
import decimal
|
||||
import unittest
|
||||
|
||||
from petstore_api.model.money import Money
|
||||
|
||||
|
||||
class TestMoney(unittest.TestCase):
|
||||
"""Money unit test stubs"""
|
||||
|
||||
def test_Money(self):
|
||||
"""Test Money"""
|
||||
price = Money(
|
||||
currency='usd',
|
||||
amount='10.99'
|
||||
)
|
||||
self.assertEqual(price.amount.as_decimal_oapg, decimal.Decimal('10.99'))
|
||||
self.assertEqual(
|
||||
price,
|
||||
dict(currency='usd', amount='10.99')
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,73 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import decimal
|
||||
import unittest
|
||||
|
||||
from petstore_api.model.no_additional_properties import NoAdditionalProperties
|
||||
from petstore_api import schemas
|
||||
|
||||
class TestNoAdditionalProperties(unittest.TestCase):
|
||||
"""NoAdditionalProperties unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testNoAdditionalProperties(self):
|
||||
"""Test NoAdditionalProperties"""
|
||||
|
||||
# works with only required
|
||||
inst = NoAdditionalProperties(id=1)
|
||||
id_by_items = inst["id"]
|
||||
assert id_by_items == 1
|
||||
assert isinstance(id_by_items, (schemas.Int64Schema, decimal.Decimal))
|
||||
id_by_property = inst.id
|
||||
assert id_by_property == 1
|
||||
assert isinstance(id_by_property, (schemas.Int64Schema, decimal.Decimal))
|
||||
with self.assertRaises(AttributeError):
|
||||
inst.petId
|
||||
with self.assertRaises(KeyError):
|
||||
inst["petId"]
|
||||
assert inst.get_item_oapg("petId") is schemas.unset
|
||||
|
||||
# works with required + optional
|
||||
inst = NoAdditionalProperties(id=1, petId=2)
|
||||
|
||||
# needs required
|
||||
# TODO cast this to ApiTypeError?
|
||||
with self.assertRaisesRegex(
|
||||
TypeError,
|
||||
r"missing 1 required keyword-only argument: 'id'"
|
||||
):
|
||||
NoAdditionalProperties(petId=2)
|
||||
|
||||
# may not be passed additional properties
|
||||
# TODO cast this to ApiTypeError?
|
||||
with self.assertRaisesRegex(
|
||||
TypeError,
|
||||
r"got an unexpected keyword argument 'invalidArg'"
|
||||
):
|
||||
NoAdditionalProperties(id=2, invalidArg=2)
|
||||
|
||||
# plural example
|
||||
# TODO cast this to ApiTypeError?
|
||||
with self.assertRaisesRegex(
|
||||
TypeError,
|
||||
r"got an unexpected keyword argument 'firstInvalidArg'"
|
||||
):
|
||||
NoAdditionalProperties(id=2, firstInvalidArg=1, secondInvalidArg=1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,55 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.nullable_string import NullableString
|
||||
from petstore_api.schemas import Schema, Singleton
|
||||
|
||||
|
||||
class TestNullableString(unittest.TestCase):
|
||||
"""NullableString unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testNullableString(self):
|
||||
"""Test NullableString"""
|
||||
inst = NullableString(None)
|
||||
assert isinstance(inst, Singleton)
|
||||
assert isinstance(inst, NullableString)
|
||||
assert isinstance(inst, Schema)
|
||||
assert inst.is_none_oapg() is True
|
||||
assert repr(inst) == '<DynamicSchema: None>'
|
||||
|
||||
inst = NullableString('approved')
|
||||
assert inst.is_none_oapg() is False
|
||||
assert isinstance(inst, NullableString)
|
||||
assert isinstance(inst, Schema)
|
||||
assert isinstance(inst, str)
|
||||
assert inst == 'approved'
|
||||
|
||||
invalid_values = [1]
|
||||
for invalid_value in invalid_values:
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiTypeError,
|
||||
r"Invalid type. Required value type is one of \[NoneClass, str\] and passed type was Decimal at \['args\[0\]'\]"
|
||||
):
|
||||
NullableString(invalid_value)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -31,11 +31,14 @@ class TestNumberWithValidations(unittest.TestCase):
|
||||
valid_values = [10.0, 15.0, 20.0]
|
||||
for valid_value in valid_values:
|
||||
model = NumberWithValidations(valid_value)
|
||||
assert model.value == valid_value
|
||||
assert model == valid_value
|
||||
|
||||
invalid_values = [9.0, 21.0]
|
||||
for invalid_value in invalid_values:
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
value_error_msg_pairs = (
|
||||
(9.0, r"Invalid value `9.0`, must be a value greater than or equal to `10` at \('args\[0\]',\)"),
|
||||
(21.0, r"Invalid value `21.0`, must be a value less than or equal to `20` at \('args\[0\]',\)"),
|
||||
)
|
||||
for invalid_value, error_msg in value_error_msg_pairs:
|
||||
with self.assertRaisesRegex(petstore_api.ApiValueError, error_msg):
|
||||
NumberWithValidations(invalid_value)
|
||||
|
||||
|
||||
|
||||
@@ -9,18 +9,13 @@
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import number_with_validations
|
||||
except ImportError:
|
||||
number_with_validations = sys.modules[
|
||||
'petstore_api.model.number_with_validations']
|
||||
import frozendict
|
||||
|
||||
from petstore_api.schemas import BoolClass
|
||||
from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps
|
||||
from petstore_api.model.readonly import Readonly
|
||||
from petstore_api.model.number_with_validations import NumberWithValidations
|
||||
|
||||
|
||||
class TestObjectModelWithRefProps(unittest.TestCase):
|
||||
@@ -34,16 +29,17 @@ class TestObjectModelWithRefProps(unittest.TestCase):
|
||||
|
||||
def testObjectModelWithRefProps(self):
|
||||
"""Test ObjectModelWithRefProps"""
|
||||
from petstore_api.model.number_with_validations import NumberWithValidations
|
||||
self.assertEqual(
|
||||
ObjectModelWithRefProps.openapi_types,
|
||||
{
|
||||
'my_number': (NumberWithValidations,),
|
||||
'my_readonly': (Readonly,),
|
||||
'my_string': (str,),
|
||||
'my_boolean': (bool,),
|
||||
}
|
||||
)
|
||||
inst = ObjectModelWithRefProps(myNumber=15.0, myString="a", myBoolean=True)
|
||||
assert isinstance(inst, ObjectModelWithRefProps)
|
||||
assert isinstance(inst, frozendict.frozendict)
|
||||
assert set(inst.keys()) == {"myNumber", "myString", "myBoolean"}
|
||||
assert inst["myNumber"] == 15.0
|
||||
assert isinstance(inst["myNumber"], NumberWithValidations)
|
||||
assert inst["myString"] == 'a'
|
||||
assert isinstance(inst["myString"], ObjectModelWithRefProps.MetaOapg.properties.myString)
|
||||
assert bool(inst["myBoolean"]) is True
|
||||
assert isinstance(inst["myBoolean"], ObjectModelWithRefProps.MetaOapg.properties.myBoolean)
|
||||
assert isinstance(inst["myBoolean"], BoolClass)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -14,11 +14,11 @@ import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.tag import Tag
|
||||
from petstore_api.model.object_with_difficultly_named_props import ObjectWithDifficultlyNamedProps
|
||||
|
||||
|
||||
class TestTag(unittest.TestCase):
|
||||
"""Tag unit test stubs"""
|
||||
class TestObjectWithDifficultlyNamedProps(unittest.TestCase):
|
||||
"""ObjectWithDifficultlyNamedProps unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
@@ -26,9 +26,11 @@ class TestTag(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_can_ingest_additional_properties_in_tag(self):
|
||||
t = Tag(a='abc')
|
||||
assert t.a == 'abc'
|
||||
def test_ObjectWithDifficultlyNamedProps(self):
|
||||
"""Test ObjectWithDifficultlyNamedProps"""
|
||||
# FIXME: construct object with mandatory attributes with example values
|
||||
# model = ObjectWithDifficultlyNamedProps() # noqa: E501
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -0,0 +1,38 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
from petstore_api import schemas, exceptions
|
||||
from petstore_api.model.object_with_inline_composition_property import ObjectWithInlineCompositionProperty
|
||||
|
||||
|
||||
class TestObjectWithInlineCompositionProperty(unittest.TestCase):
|
||||
"""ObjectWithInlineCompositionProperty unit test stubs"""
|
||||
|
||||
def test_ObjectWithInlineCompositionProperty(self):
|
||||
"""Test ObjectWithInlineCompositionProperty"""
|
||||
model = ObjectWithInlineCompositionProperty(someProp='a')
|
||||
self.assertTrue(
|
||||
isinstance(
|
||||
model["someProp"],
|
||||
ObjectWithInlineCompositionProperty.MetaOapg.properties.someProp
|
||||
)
|
||||
)
|
||||
self.assertTrue(isinstance(model["someProp"], schemas.StrSchema))
|
||||
|
||||
# error thrown on length < 1
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
ObjectWithInlineCompositionProperty(someProp='')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,52 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.object_with_validations import ObjectWithValidations
|
||||
|
||||
|
||||
class TestObjectWithValidations(unittest.TestCase):
|
||||
"""ObjectWithValidations unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_ObjectWithValidations(self):
|
||||
"""Test ObjectWithValidations"""
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
r"Invalid value `frozendict.frozendict\({}\)`, number of properties must be greater than or equal to `2` at \('args\[0\]',\)"
|
||||
):
|
||||
ObjectWithValidations({})
|
||||
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
r"Invalid value `frozendict.frozendict\({'a': 'a'}\)`, number of properties must be greater than or equal to `2` at \('args\[0\]',\)"
|
||||
):
|
||||
# number of properties less than 2 fails
|
||||
model = ObjectWithValidations(a='a')
|
||||
|
||||
# 2 or more properties succeeds
|
||||
model = ObjectWithValidations(a='a', b='b')
|
||||
model = ObjectWithValidations(a='a', b='b', c='c')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,16 +14,7 @@ import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import child_cat
|
||||
except ImportError:
|
||||
child_cat = sys.modules[
|
||||
'petstore_api.model.child_cat']
|
||||
try:
|
||||
from petstore_api.model import grandparent_animal
|
||||
except ImportError:
|
||||
grandparent_animal = sys.modules[
|
||||
'petstore_api.model.grandparent_animal']
|
||||
from petstore_api.model.grandparent_animal import GrandparentAnimal
|
||||
from petstore_api.model.parent_pet import ParentPet
|
||||
|
||||
|
||||
@@ -44,6 +35,7 @@ class TestParentPet(unittest.TestCase):
|
||||
# GrandparentAnimal, and we use the descendant's discriminator to make ParentPet
|
||||
model = ParentPet(pet_type="ParentPet")
|
||||
assert isinstance(model, ParentPet)
|
||||
assert isinstance(model, GrandparentAnimal)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -14,16 +14,8 @@ import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import complex_quadrilateral
|
||||
except ImportError:
|
||||
complex_quadrilateral = sys.modules[
|
||||
'petstore_api.model.complex_quadrilateral']
|
||||
try:
|
||||
from petstore_api.model import simple_quadrilateral
|
||||
except ImportError:
|
||||
simple_quadrilateral = sys.modules[
|
||||
'petstore_api.model.simple_quadrilateral']
|
||||
from petstore_api.model import complex_quadrilateral
|
||||
from petstore_api.model import simple_quadrilateral
|
||||
from petstore_api.model.quadrilateral import Quadrilateral
|
||||
|
||||
|
||||
@@ -38,9 +30,9 @@ class TestQuadrilateral(unittest.TestCase):
|
||||
|
||||
def testQuadrilateral(self):
|
||||
"""Test Quadrilateral"""
|
||||
instance = Quadrilateral(shape_type="Quadrilateral", quadrilateral_type="ComplexQuadrilateral")
|
||||
instance = Quadrilateral(shapeType="Quadrilateral", quadrilateralType="ComplexQuadrilateral")
|
||||
assert isinstance(instance, complex_quadrilateral.ComplexQuadrilateral)
|
||||
instance = Quadrilateral(shape_type="Quadrilateral", quadrilateral_type="SimpleQuadrilateral")
|
||||
instance = Quadrilateral(shapeType="Quadrilateral", quadrilateralType="SimpleQuadrilateral")
|
||||
assert isinstance(instance, simple_quadrilateral.SimpleQuadrilateral)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import collections
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from petstore_api import api_client, exceptions, schemas
|
||||
|
||||
ParamTestCase = collections.namedtuple('ParamTestCase', 'payload expected_serialization')
|
||||
|
||||
|
||||
class TestParameter(unittest.TestCase):
|
||||
|
||||
def test_throws_exception_when_content_is_invalid_size(self):
|
||||
with self.assertRaises(ValueError):
|
||||
api_client.RequestBody(
|
||||
content={}
|
||||
)
|
||||
|
||||
def test_content_json_serialization(self):
|
||||
payloads = [
|
||||
None,
|
||||
1,
|
||||
3.14,
|
||||
'blue',
|
||||
'hello world',
|
||||
'',
|
||||
True,
|
||||
False,
|
||||
[],
|
||||
['blue', 'black', 'brown'],
|
||||
{},
|
||||
dict(R=100, G=200, B=150),
|
||||
]
|
||||
for payload in payloads:
|
||||
request_body = api_client.RequestBody(
|
||||
content={'application/json': api_client.MediaType(schema=schemas.AnyTypeSchema)}
|
||||
)
|
||||
serialization = request_body.serialize(payload, 'application/json')
|
||||
self.assertEqual(
|
||||
serialization,
|
||||
dict(body=json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode('utf-8'))
|
||||
)
|
||||
|
||||
def test_content_multipart_form_data_serialization(self):
|
||||
payload = dict(
|
||||
some_null=None,
|
||||
some_bool=True,
|
||||
some_str='a',
|
||||
some_int=1,
|
||||
some_float=3.14,
|
||||
some_list=[],
|
||||
some_dict={},
|
||||
some_bytes=b'abc'
|
||||
)
|
||||
request_body = api_client.RequestBody(
|
||||
content={'multipart/form-data': api_client.MediaType(schema=schemas.AnyTypeSchema)}
|
||||
)
|
||||
serialization = request_body.serialize(payload, 'multipart/form-data')
|
||||
self.assertEqual(
|
||||
serialization,
|
||||
dict(
|
||||
fields=(
|
||||
api_client.RequestField(
|
||||
name='some_null', data='null', headers={'Content-Type': 'application/json'}),
|
||||
api_client.RequestField(
|
||||
name='some_bool', data='true', headers={'Content-Type': 'application/json'}),
|
||||
api_client.RequestField(
|
||||
name='some_str', data='a', headers={'Content-Type': 'text/plain'}),
|
||||
api_client.RequestField(
|
||||
name='some_int', data='1', headers={'Content-Type': 'application/json'}),
|
||||
api_client.RequestField(
|
||||
name='some_float', data='3.14', headers={'Content-Type': 'application/json'}),
|
||||
api_client.RequestField(
|
||||
name='some_list', data='[]', headers={'Content-Type': 'application/json'}),
|
||||
api_client.RequestField(
|
||||
name='some_dict', data='{}', headers={'Content-Type': 'application/json'}),
|
||||
api_client.RequestField(
|
||||
name='some_bytes', data=b'abc', headers={'Content-Type': 'application/octet-stream'})
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def test_throws_error_for_nonexistant_content_type(self):
|
||||
request_body = api_client.RequestBody(
|
||||
content={'application/json': api_client.MediaType(schema=schemas.AnyTypeSchema)}
|
||||
)
|
||||
with self.assertRaises(KeyError):
|
||||
request_body.serialize(None, 'abc/def')
|
||||
|
||||
def test_throws_error_for_not_implemented_content_type(self):
|
||||
request_body = api_client.RequestBody(
|
||||
content={
|
||||
'application/json': api_client.MediaType(schema=schemas.AnyTypeSchema),
|
||||
'text/css': api_client.MediaType(schema=schemas.AnyTypeSchema)
|
||||
}
|
||||
)
|
||||
with self.assertRaises(NotImplementedError):
|
||||
request_body.serialize(None, 'text/css')
|
||||
|
||||
def test_application_x_www_form_urlencoded_serialization(self):
|
||||
payload = dict(
|
||||
some_null=None,
|
||||
some_str='a',
|
||||
some_int=1,
|
||||
some_float=3.14,
|
||||
some_list=[],
|
||||
some_dict={},
|
||||
)
|
||||
content_type = 'application/x-www-form-urlencoded'
|
||||
request_body = api_client.RequestBody(
|
||||
content={content_type: api_client.MediaType(schema=schemas.AnyTypeSchema)}
|
||||
)
|
||||
serialization = request_body.serialize(payload, content_type)
|
||||
self.assertEqual(
|
||||
serialization,
|
||||
dict(body='?some_str=a&some_int=1&some_float=3.14')
|
||||
)
|
||||
|
||||
serialization = request_body.serialize({}, content_type)
|
||||
self.assertEqual(
|
||||
serialization,
|
||||
dict(body='')
|
||||
)
|
||||
|
||||
invalid_payloads = [
|
||||
dict(some_bool=True),
|
||||
dict(some_bytes=b'abc'),
|
||||
dict(some_list_with_data=[0]),
|
||||
dict(some_dict_with_data={'a': 'b'}),
|
||||
]
|
||||
for invalid_payload in invalid_payloads:
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
request_body.serialize(invalid_payload, content_type)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -13,18 +13,18 @@
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import frozendict
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import quadrilateral
|
||||
except ImportError:
|
||||
quadrilateral = sys.modules[
|
||||
'petstore_api.model.quadrilateral']
|
||||
try:
|
||||
from petstore_api.model import triangle
|
||||
except ImportError:
|
||||
triangle = sys.modules[
|
||||
'petstore_api.model.triangle']
|
||||
from petstore_api.schemas import Singleton
|
||||
from petstore_api.model.shape import Shape
|
||||
from petstore_api.model import complex_quadrilateral
|
||||
from petstore_api.model import simple_quadrilateral
|
||||
from petstore_api.model import triangle
|
||||
from petstore_api.model import triangle_interface
|
||||
from petstore_api.model import equilateral_triangle
|
||||
from petstore_api.model import isosceles_triangle
|
||||
from petstore_api.model import scalene_triangle
|
||||
|
||||
|
||||
class TestShape(unittest.TestCase):
|
||||
@@ -44,71 +44,74 @@ class TestShape(unittest.TestCase):
|
||||
|
||||
def testShape(self):
|
||||
"""Test Shape"""
|
||||
from petstore_api.model import complex_quadrilateral
|
||||
from petstore_api.model import simple_quadrilateral
|
||||
from petstore_api.model import equilateral_triangle
|
||||
from petstore_api.model import isosceles_triangle
|
||||
from petstore_api.model import scalene_triangle
|
||||
|
||||
tri = triangle.Triangle(
|
||||
shape_type="Triangle",
|
||||
triangle_type="EquilateralTriangle"
|
||||
tri = Shape(
|
||||
shapeType="Triangle",
|
||||
triangleType="EquilateralTriangle"
|
||||
)
|
||||
assert isinstance(tri, equilateral_triangle.EquilateralTriangle)
|
||||
assert isinstance(tri, triangle.Triangle)
|
||||
assert isinstance(tri, triangle_interface.TriangleInterface)
|
||||
assert isinstance(tri, Shape)
|
||||
assert isinstance(tri, frozendict.frozendict)
|
||||
assert isinstance(tri.shapeType, str)
|
||||
assert isinstance(tri.shapeType, Singleton)
|
||||
|
||||
tri = triangle.Triangle(
|
||||
shape_type="Triangle",
|
||||
triangle_type="IsoscelesTriangle"
|
||||
tri = Shape(
|
||||
shapeType="Triangle",
|
||||
triangleType="IsoscelesTriangle"
|
||||
)
|
||||
assert isinstance(tri, isosceles_triangle.IsoscelesTriangle)
|
||||
|
||||
tri = triangle.Triangle(
|
||||
shape_type="Triangle",
|
||||
triangle_type="ScaleneTriangle"
|
||||
tri = Shape(
|
||||
shapeType="Triangle",
|
||||
triangleType="ScaleneTriangle"
|
||||
)
|
||||
assert isinstance(tri, scalene_triangle.ScaleneTriangle)
|
||||
|
||||
quad = Shape(
|
||||
shape_type="Quadrilateral",
|
||||
quadrilateral_type="ComplexQuadrilateral"
|
||||
shapeType="Quadrilateral",
|
||||
quadrilateralType="ComplexQuadrilateral"
|
||||
)
|
||||
assert isinstance(quad, complex_quadrilateral.ComplexQuadrilateral)
|
||||
|
||||
quad = Shape(
|
||||
shape_type="Quadrilateral",
|
||||
quadrilateral_type="SimpleQuadrilateral"
|
||||
shapeType="Quadrilateral",
|
||||
quadrilateralType="SimpleQuadrilateral"
|
||||
)
|
||||
assert isinstance(quad, simple_quadrilateral.SimpleQuadrilateral)
|
||||
|
||||
# No discriminator provided.
|
||||
err_msg = ("Cannot deserialize input data due to missing discriminator. "
|
||||
"The discriminator property '{}' is missing at path: ()"
|
||||
)
|
||||
# data missing
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
err_msg.format("shapeType")
|
||||
petstore_api.exceptions.ApiValueError,
|
||||
r"Cannot deserialize input data due to missing discriminator. The discriminator "
|
||||
r"property 'shapeType' is missing at path: \('args\[0\]',\)"
|
||||
):
|
||||
Shape()
|
||||
Shape({})
|
||||
|
||||
# invalid shape_type (first discriminator). 'Circle' does not exist in the model.
|
||||
err_msg = ("Cannot deserialize input data due to invalid discriminator "
|
||||
"value. The OpenAPI document has no mapping for discriminator "
|
||||
"property '{}'='{}' at path: ()"
|
||||
)
|
||||
err_msg = (
|
||||
r"Invalid discriminator value was passed in to Shape.shapeType Only the values "
|
||||
r"\['Quadrilateral', 'Triangle'\] are allowed at \('args\[0\]', 'shapeType'\)"
|
||||
)
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
err_msg.format("shapeType", "Circle")
|
||||
err_msg
|
||||
):
|
||||
Shape(shape_type="Circle")
|
||||
Shape(shapeType="Circle")
|
||||
|
||||
# invalid quadrilateral_type (second discriminator)
|
||||
err_msg = (
|
||||
r"Invalid discriminator value was passed in to Quadrilateral.quadrilateralType Only the values "
|
||||
r"\['ComplexQuadrilateral', 'SimpleQuadrilateral'\] are allowed at \('args\[0\]', 'quadrilateralType'\)"
|
||||
)
|
||||
with self.assertRaisesRegex(
|
||||
petstore_api.ApiValueError,
|
||||
err_msg.format("quadrilateralType", "Triangle")
|
||||
err_msg
|
||||
):
|
||||
Shape(
|
||||
shape_type="Quadrilateral",
|
||||
quadrilateral_type="Triangle"
|
||||
shapeType="Quadrilateral",
|
||||
quadrilateralType="Triangle"
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -10,11 +10,11 @@
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.model.string_enum import StringEnum
|
||||
from petstore_api.schemas import Singleton, NoneClass
|
||||
|
||||
|
||||
class TestStringEnum(unittest.TestCase):
|
||||
@@ -29,24 +29,28 @@ class TestStringEnum(unittest.TestCase):
|
||||
def testStringEnum(self):
|
||||
"""Test StringEnum"""
|
||||
inst = StringEnum(None)
|
||||
self.assertIsNone(inst)
|
||||
assert isinstance(inst, StringEnum)
|
||||
assert isinstance(inst, NoneClass)
|
||||
assert repr(inst) == '<DynamicSchema: None>'
|
||||
|
||||
inst = StringEnum('approved')
|
||||
assert isinstance(inst, StringEnum)
|
||||
assert isinstance(inst, Singleton)
|
||||
assert isinstance(inst, str)
|
||||
assert inst == 'approved'
|
||||
assert repr(inst) == "<DynamicSchema: 'approved'>"
|
||||
|
||||
with self.assertRaises(petstore_api.ApiValueError):
|
||||
StringEnum('garbage')
|
||||
|
||||
# make sure that we can access its allowed_values
|
||||
assert StringEnum.allowed_values[('value',)] == {
|
||||
'None': None,
|
||||
'PLACED': "placed",
|
||||
'APPROVED': "approved",
|
||||
'DELIVERED': "delivered",
|
||||
'DOUBLE_QUOTE_WITH_NEWLINE': "double quote \n with newline",
|
||||
'MULTIPLE_LINES': "multiple\nlines",
|
||||
'SINGLE_QUOTED': "single quoted"
|
||||
}
|
||||
assert isinstance(StringEnum.NONE, NoneClass)
|
||||
assert StringEnum.PLACED == 'placed'
|
||||
assert StringEnum.APPROVED == 'approved'
|
||||
assert StringEnum.DELIVERED == 'delivered'
|
||||
assert StringEnum.DOUBLE_QUOTE_WITH_NEWLINE == "double quote \n with newline"
|
||||
assert StringEnum.MULTIPLE_LINES == "multiple\nlines"
|
||||
assert StringEnum.SINGLE_QUOTED == "single quoted"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -10,45 +10,29 @@
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
try:
|
||||
from petstore_api.model import equilateral_triangle
|
||||
except ImportError:
|
||||
equilateral_triangle = sys.modules[
|
||||
'petstore_api.model.equilateral_triangle']
|
||||
try:
|
||||
from petstore_api.model import isosceles_triangle
|
||||
except ImportError:
|
||||
isosceles_triangle = sys.modules[
|
||||
'petstore_api.model.isosceles_triangle']
|
||||
try:
|
||||
from petstore_api.model import scalene_triangle
|
||||
except ImportError:
|
||||
scalene_triangle = sys.modules[
|
||||
'petstore_api.model.scalene_triangle']
|
||||
import frozendict
|
||||
|
||||
from petstore_api.model.equilateral_triangle import EquilateralTriangle
|
||||
from petstore_api.model.isosceles_triangle import IsoscelesTriangle
|
||||
from petstore_api.model.scalene_triangle import ScaleneTriangle
|
||||
from petstore_api.model.triangle import Triangle
|
||||
from petstore_api.model.triangle_interface import TriangleInterface
|
||||
|
||||
|
||||
class TestTriangle(unittest.TestCase):
|
||||
"""Triangle unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def testTriangle(self):
|
||||
"""Test Triangle"""
|
||||
tri = Triangle(shape_type="Triangle", triangle_type="EquilateralTriangle")
|
||||
assert isinstance(tri, equilateral_triangle.EquilateralTriangle)
|
||||
tri = Triangle(shape_type="Triangle", triangle_type="IsoscelesTriangle")
|
||||
assert isinstance(tri, isosceles_triangle.IsoscelesTriangle)
|
||||
tri = Triangle(shape_type="Triangle", triangle_type="ScaleneTriangle")
|
||||
assert isinstance(tri, scalene_triangle.ScaleneTriangle)
|
||||
tri_classes = [EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle]
|
||||
for tri_class in tri_classes:
|
||||
tri = Triangle(shapeType="Triangle", triangleType=tri_class.__name__)
|
||||
assert isinstance(tri, tri_class)
|
||||
assert isinstance(tri, Triangle)
|
||||
assert isinstance(tri, TriangleInterface)
|
||||
assert isinstance(tri, frozendict.frozendict)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import petstore_api
|
||||
from petstore_api import api_client
|
||||
from petstore_api.apis.tags.user_api import UserApi
|
||||
from petstore_api.rest import RESTClientObject
|
||||
|
||||
from . import ApiTestMixin
|
||||
|
||||
|
||||
class TestUserApi(ApiTestMixin):
|
||||
"""UserApi unit test stubs"""
|
||||
configuration = petstore_api.Configuration()
|
||||
api = UserApi(api_client=api_client.ApiClient(configuration=configuration))
|
||||
|
||||
def test_create_user(self):
|
||||
"""Test case for create_user
|
||||
|
||||
Create user # noqa: E501
|
||||
"""
|
||||
pass
|
||||
|
||||
def test_create_users_with_array_input(self):
|
||||
"""Test case for create_users_with_array_input
|
||||
|
||||
Creates list of users with given input array # noqa: E501
|
||||
"""
|
||||
pass
|
||||
|
||||
def test_create_users_with_list_input(self):
|
||||
"""Test case for create_users_with_list_input
|
||||
|
||||
Creates list of users with given input array # noqa: E501
|
||||
"""
|
||||
pass
|
||||
|
||||
def test_delete_user(self):
|
||||
"""Test case for delete_user
|
||||
|
||||
Delete user # noqa: E501
|
||||
"""
|
||||
pass
|
||||
|
||||
def test_get_user_by_name(self):
|
||||
from petstore_api.model import user
|
||||
|
||||
# serialization + deserialization works
|
||||
with patch.object(RESTClientObject, 'request') as mock_request:
|
||||
value_simple = dict(
|
||||
id=1,
|
||||
username='first last',
|
||||
firstName='first',
|
||||
lastName='last'
|
||||
)
|
||||
body = user.User(**value_simple)
|
||||
mock_request.return_value = self.response(
|
||||
self.json_bytes(value_simple)
|
||||
)
|
||||
|
||||
api_response = self.api.get_user_by_name(
|
||||
path_params=dict(username='first last')
|
||||
)
|
||||
self.assert_request_called_with(
|
||||
mock_request,
|
||||
'http://petstore.swagger.io:80/v2/user/first%20last',
|
||||
method='GET',
|
||||
accept_content_type='application/xml, application/json',
|
||||
content_type=None
|
||||
)
|
||||
|
||||
assert isinstance(api_response.body, user.User)
|
||||
assert api_response.body == body
|
||||
|
||||
def test_login_user(self):
|
||||
"""Test case for login_user
|
||||
|
||||
Logs user into the system # noqa: E501
|
||||
"""
|
||||
pass
|
||||
|
||||
def test_logout_user(self):
|
||||
"""Test case for logout_user
|
||||
|
||||
Logs out current logged in user session # noqa: E501
|
||||
"""
|
||||
pass
|
||||
|
||||
def test_update_user(self):
|
||||
"""Test case for update_user
|
||||
|
||||
Updated user # noqa: E501
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
from petstore_api import schemas, exceptions
|
||||
from petstore_api.model.uuid_string import UUIDString
|
||||
import uuid
|
||||
|
||||
|
||||
class TestUUIDString(unittest.TestCase):
|
||||
"""UUIDString unit test stubs"""
|
||||
|
||||
def test_UUIDString(self):
|
||||
"""Test UUIDString"""
|
||||
uuid_value = '12345678-1234-5678-1234-567812345678'
|
||||
u = UUIDString(uuid_value)
|
||||
self.assertEqual(u, uuid_value)
|
||||
self.assertTrue(isinstance(u, UUIDString))
|
||||
self.assertTrue(isinstance(u, schemas.UUIDSchema))
|
||||
self.assertTrue(isinstance(u, schemas.StrSchema))
|
||||
self.assertTrue(isinstance(u, str))
|
||||
self.assertEqual(u.as_uuid_oapg, uuid.UUID(uuid_value))
|
||||
|
||||
# passing in a uuid also works
|
||||
u = UUIDString(uuid.UUID(uuid_value))
|
||||
self.assertEqual(u, uuid_value)
|
||||
self.assertTrue(isinstance(u, UUIDString))
|
||||
self.assertTrue(isinstance(u, schemas.UUIDSchema))
|
||||
self.assertTrue(isinstance(u, schemas.StrSchema))
|
||||
self.assertTrue(isinstance(u, str))
|
||||
self.assertEqual(u.as_uuid_oapg, uuid.UUID(uuid_value))
|
||||
|
||||
# an invalid value does not work
|
||||
with self.assertRaises(exceptions.ApiValueError):
|
||||
UUIDString('1')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,286 @@
|
||||
# coding: utf-8
|
||||
import decimal
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch, call
|
||||
import unittest
|
||||
|
||||
import frozendict
|
||||
|
||||
from petstore_api.model.string_with_validation import StringWithValidation
|
||||
from petstore_api.model.string_enum import StringEnum
|
||||
from petstore_api.model.number_with_validations import NumberWithValidations
|
||||
from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType
|
||||
from petstore_api.model.array_with_validations_in_items import (
|
||||
ArrayWithValidationsInItems,
|
||||
)
|
||||
from petstore_api.model.foo import Foo
|
||||
from petstore_api.model.animal import Animal
|
||||
from petstore_api.model.dog import Dog
|
||||
from petstore_api.model.boolean_enum import BooleanEnum
|
||||
from petstore_api.model.pig import Pig
|
||||
from petstore_api.model.danish_pig import DanishPig
|
||||
from petstore_api.model.gm_fruit import GmFruit
|
||||
from petstore_api.model.apple import Apple
|
||||
from petstore_api.model.banana import Banana
|
||||
from petstore_api import schemas
|
||||
|
||||
from petstore_api.schemas import (
|
||||
AnyTypeSchema,
|
||||
BoolClass,
|
||||
NoneClass,
|
||||
StrSchema,
|
||||
NumberSchema,
|
||||
Schema,
|
||||
ValidationMetadata,
|
||||
)
|
||||
|
||||
|
||||
class TestValidateResults(unittest.TestCase):
|
||||
def test_str_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = StringWithValidation._validate_oapg(
|
||||
"abcdefg", validation_metadata=vm
|
||||
)
|
||||
assert path_to_schemas == {("args[0]",): {StringWithValidation, str}}
|
||||
|
||||
def test_number_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = NumberWithValidations._validate_oapg(
|
||||
Decimal(11), validation_metadata=vm
|
||||
)
|
||||
assert path_to_schemas == {("args[0]",): {NumberWithValidations, Decimal}}
|
||||
|
||||
def test_str_enum_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = StringEnum._validate_oapg("placed", validation_metadata=vm)
|
||||
assert path_to_schemas == {("args[0]",): {str, StringEnum}}
|
||||
|
||||
def test_nullable_enum_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = StringEnum._validate_oapg(NoneClass.NONE, validation_metadata=vm)
|
||||
assert path_to_schemas == {("args[0]",): {NoneClass, StringEnum}}
|
||||
|
||||
def test_empty_list_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = ArrayHoldingAnyType._validate_oapg((), validation_metadata=vm)
|
||||
assert path_to_schemas == {("args[0]",): {ArrayHoldingAnyType, tuple}}
|
||||
|
||||
def test_list_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = ArrayHoldingAnyType._validate_oapg(
|
||||
(Decimal(1), "a"), validation_metadata=vm
|
||||
)
|
||||
assert path_to_schemas == {
|
||||
("args[0]",): {ArrayHoldingAnyType, tuple},
|
||||
("args[0]", 0): {AnyTypeSchema, Decimal},
|
||||
("args[0]", 1): {AnyTypeSchema, str},
|
||||
}
|
||||
|
||||
def test_empty_dict_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = Foo._validate_oapg(frozendict.frozendict({}), validation_metadata=vm)
|
||||
assert path_to_schemas == {("args[0]",): {Foo, frozendict.frozendict}}
|
||||
|
||||
def test_dict_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = Foo._validate_oapg(
|
||||
frozendict.frozendict({"bar": "a", "additional": Decimal(0)}),
|
||||
validation_metadata=vm,
|
||||
)
|
||||
assert path_to_schemas == {
|
||||
("args[0]",): {Foo, frozendict.frozendict},
|
||||
("args[0]", "bar"): {StrSchema, str},
|
||||
("args[0]", "additional"): {schemas.UnsetAnyTypeSchema, decimal.Decimal},
|
||||
}
|
||||
|
||||
def test_discriminated_dict_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = Animal._validate_oapg(
|
||||
frozendict.frozendict(className="Dog", color="black"), validation_metadata=vm
|
||||
)
|
||||
for path, schema_classes in path_to_schemas.items():
|
||||
Animal._process_schema_classes_oapg(schema_classes)
|
||||
assert path_to_schemas == {
|
||||
("args[0]",): {Animal, Dog, Dog.MetaOapg.all_of()[1], frozendict.frozendict},
|
||||
("args[0]", "className"): {StrSchema, str},
|
||||
("args[0]", "color"): {StrSchema, str},
|
||||
}
|
||||
|
||||
def test_bool_enum_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = BooleanEnum._validate_oapg(BoolClass.TRUE, validation_metadata=vm)
|
||||
assert path_to_schemas == {("args[0]",): {BoolClass, BooleanEnum}}
|
||||
|
||||
def test_oneof_composition_pig_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = Pig._validate_oapg(
|
||||
frozendict.frozendict(className="DanishPig"), validation_metadata=vm
|
||||
)
|
||||
for path, schema_classes in path_to_schemas.items():
|
||||
Pig._process_schema_classes_oapg(schema_classes)
|
||||
assert path_to_schemas == {
|
||||
("args[0]",): {Pig, DanishPig, frozendict.frozendict},
|
||||
("args[0]", "className"): {DanishPig.MetaOapg.properties.className, str},
|
||||
}
|
||||
|
||||
def test_anyof_composition_gm_fruit_validate(self):
|
||||
vm = ValidationMetadata()
|
||||
path_to_schemas = GmFruit._validate_oapg(
|
||||
frozendict.frozendict(cultivar="GoldenDelicious", lengthCm=Decimal(10)),
|
||||
validation_metadata=vm,
|
||||
)
|
||||
for path, schema_classes in path_to_schemas.items():
|
||||
GmFruit._process_schema_classes_oapg(schema_classes)
|
||||
assert path_to_schemas == {
|
||||
("args[0]",): {GmFruit, Apple, Banana, frozendict.frozendict},
|
||||
("args[0]", "cultivar"): {Apple.MetaOapg.properties.cultivar, str},
|
||||
("args[0]", "lengthCm"): {NumberSchema, Decimal},
|
||||
}
|
||||
|
||||
|
||||
class TestValidateCalls(unittest.TestCase):
|
||||
def test_empty_list_validate(self):
|
||||
return_value = {("args[0]",): {ArrayHoldingAnyType, tuple}}
|
||||
with patch.object(
|
||||
Schema, "_validate_oapg", return_value=return_value
|
||||
) as mock_validate:
|
||||
ArrayHoldingAnyType([])
|
||||
assert mock_validate.call_count == 1
|
||||
|
||||
with patch.object(
|
||||
Schema, "_validate_oapg", return_value=return_value
|
||||
) as mock_validate:
|
||||
ArrayHoldingAnyType.from_openapi_data_oapg([])
|
||||
assert mock_validate.call_count == 1
|
||||
|
||||
def test_empty_dict_validate(self):
|
||||
return_value = {("args[0]",): {Foo, frozendict.frozendict}}
|
||||
with patch.object(
|
||||
Schema, "_validate_oapg", return_value=return_value
|
||||
) as mock_validate:
|
||||
Foo({})
|
||||
assert mock_validate.call_count == 1
|
||||
|
||||
with patch.object(
|
||||
Schema, "_validate_oapg", return_value=return_value
|
||||
) as mock_validate:
|
||||
Foo.from_openapi_data_oapg({})
|
||||
assert mock_validate.call_count == 1
|
||||
|
||||
def test_list_validate_direct_instantiation(self):
|
||||
results = [
|
||||
{("args[0]",): {ArrayWithValidationsInItems, tuple}},
|
||||
{("args[0]", 0): {ArrayWithValidationsInItems.MetaOapg.items, Decimal}}
|
||||
]
|
||||
with patch.object(Schema, "_validate_oapg", side_effect=results) as mock_validate:
|
||||
ArrayWithValidationsInItems([7])
|
||||
calls = [
|
||||
call(
|
||||
(Decimal("7"),),
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]",))
|
||||
),
|
||||
call(
|
||||
Decimal("7"),
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]", 0))
|
||||
)
|
||||
]
|
||||
mock_validate.assert_has_calls(
|
||||
calls
|
||||
)
|
||||
|
||||
def test_list_validate_direct_instantiation_cast_item(self):
|
||||
# item validation is skipped if items are of the correct type
|
||||
item = ArrayWithValidationsInItems.MetaOapg.items(7)
|
||||
return_value = {("args[0]",): {ArrayWithValidationsInItems, tuple}}
|
||||
with patch.object(Schema, "_validate_oapg", return_value=return_value) as mock_validate:
|
||||
ArrayWithValidationsInItems([item])
|
||||
mock_validate.assert_called_once_with(
|
||||
tuple([Decimal('7')]),
|
||||
validation_metadata=ValidationMetadata(
|
||||
validated_path_to_schemas={('args[0]', 0): {ArrayWithValidationsInItems.MetaOapg.items, Decimal}}
|
||||
)
|
||||
)
|
||||
|
||||
def test_list_validate_from_openai_data_instantiation(self):
|
||||
|
||||
results = [
|
||||
{("args[0]",): {ArrayWithValidationsInItems, tuple}},
|
||||
{("args[0]", 0): {ArrayWithValidationsInItems.MetaOapg.items, Decimal}}
|
||||
]
|
||||
with patch.object(Schema, "_validate_oapg", side_effect=results) as mock_validate:
|
||||
ArrayWithValidationsInItems.from_openapi_data_oapg([7])
|
||||
calls = [
|
||||
call(
|
||||
(Decimal("7"),),
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]",), from_server=True)
|
||||
),
|
||||
call(
|
||||
Decimal("7"),
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]", 0), from_server=True)
|
||||
)
|
||||
]
|
||||
mock_validate.assert_has_calls(
|
||||
calls
|
||||
)
|
||||
|
||||
def test_dict_validate_direct_instantiation(self):
|
||||
call_results = [
|
||||
{("args[0]",): {Foo, frozendict.frozendict}},
|
||||
{("args[0]", "bar"): {StrSchema, str}}
|
||||
]
|
||||
with patch.object(Schema, "_validate_oapg", side_effect=call_results) as mock_validate:
|
||||
Foo(bar="a")
|
||||
calls = [
|
||||
call(
|
||||
frozendict.frozendict({"bar": "a"}),
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]",)),
|
||||
),
|
||||
call(
|
||||
"a",
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]", "bar")),
|
||||
),
|
||||
]
|
||||
mock_validate.assert_has_calls(
|
||||
calls
|
||||
)
|
||||
|
||||
def test_dict_validate_direct_instantiation_cast_item(self):
|
||||
bar = StrSchema("a")
|
||||
return_value = {
|
||||
("args[0]",): {Foo, frozendict.frozendict}
|
||||
}
|
||||
# only the Foo dict is validated because the bar property value was already validated
|
||||
with patch.object(Schema, "_validate_oapg", return_value=return_value) as mock_validate:
|
||||
Foo(bar=bar)
|
||||
mock_validate.assert_called_once_with(
|
||||
frozendict.frozendict(dict(bar='a')),
|
||||
validation_metadata=ValidationMetadata(
|
||||
validated_path_to_schemas={('args[0]', 'bar'): {str, StrSchema}}
|
||||
)
|
||||
)
|
||||
|
||||
def test_dict_validate_from_openapi_data_instantiation(self):
|
||||
|
||||
return_values = [
|
||||
{("args[0]",): {Foo, frozendict.frozendict}},
|
||||
{("args[0]", 'bar'): {StrSchema, str}}
|
||||
]
|
||||
with patch.object(Schema, "_validate_oapg", side_effect=return_values) as mock_validate:
|
||||
Foo.from_openapi_data_oapg({"bar": "a"})
|
||||
calls = [
|
||||
call(
|
||||
frozendict.frozendict({"bar": "a"}),
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]",), from_server=True),
|
||||
),
|
||||
call(
|
||||
"a",
|
||||
validation_metadata=ValidationMetadata(path_to_item=("args[0]", "bar"), from_server=True),
|
||||
),
|
||||
]
|
||||
mock_validate.assert_has_calls(
|
||||
calls
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,49 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
OpenAPI Petstore
|
||||
|
||||
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
|
||||
|
||||
The version of the OpenAPI document: 1.0.0
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
||||
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.schemas import BoolClass
|
||||
from petstore_api.model.whale import Whale
|
||||
|
||||
|
||||
class TestWhale(unittest.TestCase):
|
||||
"""Whale unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test_Whale(self):
|
||||
# test that the hasBaleen __bool__ method is working, True input
|
||||
whale = Whale(
|
||||
className='whale',
|
||||
hasBaleen=True
|
||||
)
|
||||
assert isinstance(whale["hasBaleen"], BoolClass)
|
||||
self.assertTrue(whale["hasBaleen"])
|
||||
|
||||
# test that the hasBaleen __bool__ method is working, False input
|
||||
whale = Whale(
|
||||
className='whale',
|
||||
hasBaleen=False
|
||||
)
|
||||
assert isinstance(whale["hasBaleen"], BoolClass)
|
||||
self.assertFalse(whale["hasBaleen"])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user