python: enable more mypy checks 1/n (#17556)

* python: more mypy checks

* mypy: check_untyped_defs

* mypy: disallow_subclassing_any

* mypy: disallow_untyped_decorators

* mypy: disallow_any_generics
This commit is contained in:
Jonathan Ballet
2024-01-09 09:45:05 +01:00
committed by GitHub
parent c041d7e12f
commit df7976c1a3
234 changed files with 992 additions and 628 deletions

View File

@@ -125,48 +125,47 @@ class ApiClientTests(unittest.TestCase):
content_type = self.api_client.select_header_content_type(content_types)
self.assertEqual(content_type, None)
def test_sanitize_for_serialization(self):
# None
def test_sanitize_for_serialization_none(self):
data = None
result = self.api_client.sanitize_for_serialization(None)
self.assertEqual(result, data)
# str
def test_sanitize_for_serialization_str(self):
data = "test string"
result = self.api_client.sanitize_for_serialization(data)
self.assertEqual(result, data)
# int
def test_sanitize_for_serialization_int(self):
data = 1
result = self.api_client.sanitize_for_serialization(data)
self.assertEqual(result, data)
# bool
def test_sanitize_for_serialization_bool(self):
data = True
result = self.api_client.sanitize_for_serialization(data)
self.assertEqual(result, data)
# date
def test_sanitize_for_serialization_date(self):
data = parse("1997-07-16").date() # date
result = self.api_client.sanitize_for_serialization(data)
self.assertEqual(result, "1997-07-16")
# datetime
def test_sanitize_for_serialization_datetime(self):
data = parse("1997-07-16T19:20:30.45+01:00") # datetime
result = self.api_client.sanitize_for_serialization(data)
self.assertEqual(result, "1997-07-16T19:20:30.450000+01:00")
# list
def test_sanitize_for_serialization_list(self):
data = [1]
result = self.api_client.sanitize_for_serialization(data)
self.assertEqual(result, data)
# dict
def test_sanitize_for_serialization_dict(self):
data = {"test key": "test value"}
result = self.api_client.sanitize_for_serialization(data)
self.assertEqual(result, data)
# model
def test_sanitize_for_serialization_model(self):
pet_dict = {"id": 1, "name": "monkey",
"category": {"id": 1, "name": "test category"},
"tags": [{"id": 1, "name": "test tag1"},
@@ -174,20 +173,19 @@ class ApiClientTests(unittest.TestCase):
"status": "available",
"photoUrls": ["http://foo.bar.com/3",
"http://foo.bar.com/4"]}
pet = petstore_api.Pet(name=pet_dict["name"], photoUrls=pet_dict["photoUrls"])
pet.id = pet_dict["id"]
cate = petstore_api.Category(name="something")
cate.id = pet_dict["category"]["id"]
cate.name = pet_dict["category"]["name"]
pet = petstore_api.Pet(name="monkey", photoUrls=["http://foo.bar.com/3", "http://foo.bar.com/4"])
pet.id = 1
cate = petstore_api.Category(name="test category")
cate.id = 1
pet.category = cate
tag1 = petstore_api.Tag()
tag1.id = pet_dict["tags"][0]["id"]
tag1.name = pet_dict["tags"][0]["name"]
tag1.id = 1
tag1.name = "test tag1"
tag2 = petstore_api.Tag()
tag2.id = pet_dict["tags"][1]["id"]
tag2.name = pet_dict["tags"][1]["name"]
tag2.id = 2
tag2.name = "test tag2"
pet.tags = [tag1, tag2]
pet.status = pet_dict["status"]
pet.status = "available"
data = pet
result = self.api_client.sanitize_for_serialization(data)
@@ -195,11 +193,10 @@ class ApiClientTests(unittest.TestCase):
# list of models
list_of_pet_dict = [pet_dict]
data = [pet]
result = self.api_client.sanitize_for_serialization(data)
result = self.api_client.sanitize_for_serialization([pet])
self.assertEqual(result, list_of_pet_dict)
def test_parameters_to_url_query(self):
def test_parameters_to_url_query_simple_values(self):
data = 'value={"category": "example", "category2": "example2"}'
dictionary = {
"category": "example",
@@ -208,6 +205,7 @@ class ApiClientTests(unittest.TestCase):
result = self.api_client.parameters_to_url_query([('value', dictionary)], {})
self.assertEqual(result, "value=%7B%22category%22%3A%20%22example%22%2C%20%22category2%22%3A%20%22example2%22%7D")
def test_parameters_to_url_query_complex_values(self):
data='value={"number": 1, "string": "str", "bool": true, "dict": {"number": 1, "string": "str", "bool": true}}'
dictionary = {
"number": 1,
@@ -222,6 +220,7 @@ class ApiClientTests(unittest.TestCase):
result = self.api_client.parameters_to_url_query([('value', dictionary)], {})
self.assertEqual(result, 'value=%7B%22number%22%3A%201%2C%20%22string%22%3A%20%22str%22%2C%20%22bool%22%3A%20true%2C%20%22dict%22%3A%20%7B%22number%22%3A%201%2C%20%22string%22%3A%20%22str%22%2C%20%22bool%22%3A%20true%7D%7D')
def test_parameters_to_url_query_dict_values(self):
data='value={"strValues": ["one", "two", "three"], "dictValues": [{"name": "value1", "age": 14}, {"name": "value2", "age": 12}]}'
dictionary = {
"strValues": [

View File

@@ -41,6 +41,7 @@ class ApiExceptionTests(unittest.TestCase):
def test_404_error(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
self.pet_api.delete_pet(pet_id=self.pet.id)
with self.checkRaiseRegex(ApiException, "Pet not found"):
@@ -55,6 +56,7 @@ class ApiExceptionTests(unittest.TestCase):
def test_500_error(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
with self.checkRaiseRegex(ApiException, "Internal Server Error"):
self.pet_api.upload_file(

View File

@@ -48,14 +48,14 @@ class ApiExceptionTests(unittest.TestCase):
def test_required_param_validation(self):
try:
self.pet_api.get_pet_by_id()
self.pet_api.get_pet_by_id() # type: ignore
except ValidationError as e:
self.assertIn("1 validation error for get_pet_by_id", str(e))
self.assertIn("Missing required argument", str(e))
def test_integer_validation(self):
try:
self.pet_api.get_pet_by_id("123")
self.pet_api.get_pet_by_id("123") # type: ignore
except ValidationError as e:
# 1 validation error for get_pet_by_id
# pet_id
@@ -75,25 +75,32 @@ class ApiExceptionTests(unittest.TestCase):
self.assertIn("unexpected value; permitted: 'available', 'pending', 'sold'", str(e))
def test_request_timeout_validation(self):
assert self.pet.id is not None
try:
self.pet_api.get_pet_by_id(self.pet.id, _request_timeout="1.0")
# should be a number
self.pet_api.get_pet_by_id(self.pet.id, _request_timeout="1.0") # type: ignore
self.assertTrue(False)
except ValidationError as e:
pass
try:
self.pet_api.get_pet_by_id(self.pet.id, _request_timeout=())
# should be a number or a pair
self.pet_api.get_pet_by_id(self.pet.id, _request_timeout=()) # type: ignore
self.assertTrue(False)
except ValidationError as e:
pass
try:
self.pet_api.get_pet_by_id(self.pet.id, _request_timeout=(1.0, 1.0, 1.0))
# should be a a pair
self.pet_api.get_pet_by_id(self.pet.id, _request_timeout=(1.0, 1.0, 1.0)) # type: ignore
self.assertTrue(False)
except ValidationError as e:
pass
def test_host_index_validation(self):
assert self.pet.id is not None
try:
self.pet_api.get_pet_by_id(self.pet.id, _host_index="1")
# should be a number
self.pet_api.get_pet_by_id(self.pet.id, _host_index="1") # type: ignore
self.assertTrue(False)
except ValidationError as e:
pass

View File

@@ -17,11 +17,14 @@ import json
import os
import re
import shutil
from typing import Union
import unittest
from urllib.parse import urlencode, urlparse
from Crypto.Hash import SHA256, SHA512
from Crypto.PublicKey import ECC, RSA
from Crypto.Hash.SHA512 import SHA512Hash
from Crypto.Hash.SHA256 import SHA256Hash
from Crypto.Signature import pkcs1_15, pss, DSS
import petstore_api
@@ -73,7 +76,7 @@ class TimeoutWithEqual(urllib3.Timeout):
def __eq__(self, other):
return self._read == other._read and self._connect == other._connect and self.total == other.total
class MockPoolManager(object):
class MockPoolManager(urllib3.PoolManager):
def __init__(self, tc):
self._tc = tc
self._reqs = []
@@ -83,9 +86,9 @@ class MockPoolManager(object):
def set_signing_config(self, signing_cfg):
self.signing_cfg = signing_cfg
self._tc.assertIsNotNone(self.signing_cfg)
assert self.signing_cfg is not None
self.pubkey = self.signing_cfg.get_public_key()
self._tc.assertIsNotNone(self.pubkey)
assert self.pubkey is not None
def request(self, *actual_request_target, **actual_request_headers_and_body):
self._tc.assertTrue(len(self._reqs) > 0)
@@ -124,13 +127,13 @@ class MockPoolManager(object):
# Extract (created)
r1 = re.compile(r'created=([0-9]+)')
m1 = r1.search(authorization_header)
self._tc.assertIsNotNone(m1)
assert m1 is not None
created = m1.group(1)
# Extract list of signed headers
r1 = re.compile(r'headers="([^"]+)"')
m1 = r1.search(authorization_header)
self._tc.assertIsNotNone(m1)
assert m1 is not None
headers = m1.group(1).split(' ')
signed_headers_list = []
for h in headers:
@@ -142,25 +145,26 @@ class MockPoolManager(object):
signed_headers_list.append((h, "{0} {1}".format(request_target[0].lower(), target_path)))
else:
value = next((v for k, v in actual_headers.items() if k.lower() == h), None)
self._tc.assertIsNotNone(value)
assert value is not None
signed_headers_list.append((h, value))
header_items = [
"{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list]
string_to_sign = "\n".join(header_items)
digest = None
digest: Union[SHA512Hash, SHA256Hash]
if self.signing_cfg.hash_algorithm == signing.HASH_SHA512:
digest = SHA512.new()
elif self.signing_cfg.hash_algorithm == signing.HASH_SHA256:
digest = SHA256.new()
else:
self._tc.fail("Unsupported hash algorithm: {0}".format(self.signing_cfg.hash_algorithm))
digest.update(string_to_sign.encode())
b64_body_digest = base64.b64encode(digest.digest()).decode()
# Extract the signature
r2 = re.compile(r'signature="([^"]+)"')
m2 = r2.search(authorization_header)
self._tc.assertIsNotNone(m2)
assert m2 is not None
b64_signature = m2.group(1)
signature = base64.b64decode(b64_signature)
# Build the message
@@ -190,6 +194,12 @@ class MockPoolManager(object):
self._tc.fail("Unsupported signing algorithm: {0}".format(signing_alg))
class PetApiTests(unittest.TestCase):
rsa_key_path: str
rsa4096_key_path: str
ec_p521_key_path: str
pet: petstore_api.Pet
test_file_dir: str
private_key_passphrase: str
@classmethod
def setUpClass(cls):
@@ -208,19 +218,19 @@ class PetApiTests(unittest.TestCase):
@classmethod
def setUpModels(cls):
cls.category = petstore_api.Category(name="dog")
cls.category.id = id_gen()
cls.tag = petstore_api.Tag()
cls.tag.id = id_gen()
cls.tag.name = "python-pet-tag"
category = petstore_api.Category(name="dog")
category.id = id_gen()
tag = petstore_api.Tag()
tag.id = id_gen()
tag.name = "python-pet-tag"
cls.pet = petstore_api.Pet(
name="hello kity",
photoUrls=["http://foo.bar.com/1", "http://foo.bar.com/2"]
)
cls.pet.id = id_gen()
cls.pet.status = "sold"
cls.pet.category = cls.category
cls.pet.tags = [cls.tag]
cls.pet.category = category
cls.pet.tags = [tag]
@classmethod
def setUpFiles(cls):
@@ -239,6 +249,8 @@ class PetApiTests(unittest.TestCase):
with open(cls.rsa_key_path, 'w') as f:
f.write(RSA_TEST_PRIVATE_KEY)
key: Union[RSA.RsaKey, ECC.EccKey]
if not os.path.exists(cls.rsa4096_key_path):
key = RSA.generate(4096)
private_key = key.export_key(
@@ -250,13 +262,17 @@ class PetApiTests(unittest.TestCase):
if not os.path.exists(cls.ec_p521_key_path):
key = ECC.generate(curve='P-521')
private_key = key.export_key(
pkey = key.export_key(
format='PEM',
passphrase=cls.private_key_passphrase,
use_pkcs8=True,
protection='PBKDF2WithHMAC-SHA1AndAES128-CBC'
)
with open(cls.ec_p521_key_path, "wt") as f:
if isinstance(pkey, str):
private_key = pkey.encode("ascii")
else:
private_key = pkey
with open(cls.ec_p521_key_path, "wb") as f:
f.write(private_key)
def test_valid_http_signature(self):
@@ -459,7 +475,7 @@ class PetApiTests(unittest.TestCase):
signing_cfg = signing.HttpSigningConfiguration(
key_id="my-key-id",
private_key_path=self.ec_p521_key_path,
signing_scheme=None
signing_scheme=None # type: ignore
)
self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)),
'Exception message: {0}'.format(str(cm.exception)))

View File

@@ -2,6 +2,7 @@
# flake8: noqa
from datetime import date
import json
import os
import time
@@ -134,28 +135,36 @@ class ModelTests(unittest.TestCase):
p = petstore_api.Color.from_json(None)
self.assertEqual(p.actual_instance, None)
def test_oneof_enum_string(self):
enum_string1 = petstore_api.EnumString1('a')
def test_oneof_enum_string_from_json(self):
# test from_json
oneof_enum = petstore_api.OneOfEnumString.from_json('"a"')
def test_oneof_nested_from_enum_string(self):
# test from_dict
oneof_enum = petstore_api.OneOfEnumString.from_dict("a")
assert oneof_enum is not None
nested = petstore_api.WithNestedOneOf(size = 1, nested_oneof_enum_string = oneof_enum)
# test to_json
self.assertEqual(nested.to_json(), '{"size": 1, "nested_oneof_enum_string": "a"}')
# test from_json
def test_oneof_nested_from_json(self):
nested = petstore_api.WithNestedOneOf.from_json('{"size": 1, "nested_oneof_enum_string": "c"}')
assert nested is not None
self.assertEqual(nested.to_json(), '{"size": 1, "nested_oneof_enum_string": "c"}')
# test from_dict
def test_oneof_nested_from_dict(self):
nested = petstore_api.WithNestedOneOf.from_dict({"size": 1, "nested_oneof_enum_string": "c"})
assert nested is not None
# test to_dict
self.assertEqual(nested.to_dict(), {"size": 1, "nested_oneof_enum_string": "c"})
# invalid enum value
def test_oneof_nested_from_json_invalid(self):
try:
nested2 = petstore_api.WithNestedOneOf.from_json('{"size": 1, "nested_oneof_enum_string": "e"}')
except ValueError as e:
self.assertTrue("'e' is not a valid EnumString1, 'e' is not a valid EnumString" in str(e))
def test_oneof_enum_string(self):
# test the constructor
enum_string1 = petstore_api.EnumString1('a')
constructor1 = petstore_api.OneOfEnumString(actual_instance=enum_string1)
@@ -276,6 +285,7 @@ class ModelTests(unittest.TestCase):
nested_json = nested.to_json()
nested2 = petstore_api.WithNestedOneOf.from_json(nested_json)
assert nested2 is not None
self.assertEqual(nested2.to_json(), nested_json)
def test_anyOf(self):
@@ -328,30 +338,30 @@ class ModelTests(unittest.TestCase):
self.assertEqual(dog.to_dict(), {'breed': 'bulldog', 'className':
'dog', 'color': 'white'})
dog2 = petstore_api.Dog.from_json(dog.to_json())
assert dog2 is not None
self.assertEqual(dog2.breed, 'bulldog')
self.assertEqual(dog2.class_name, "dog")
self.assertEqual(dog2.color, 'white')
def test_list(self):
# should throw exception as var_123_list should be string
kw = {"123-list": 123}
try:
l3 = petstore_api.ListClass(**kw)
# Don't check the typing, because we are actually testing a typing error.
l3 = petstore_api.ListClass(**{"123-list": 123}) # type: ignore
self.assertTrue(False) # this line shouldn't execute
breakpoint()
except ValueError as e:
# var_123_list
# Input should be a valid string [type=string_type, input_value=123, input_type=int]
# For further information visit https://errors.pydantic.dev/2.3/v/string_type
self.assertTrue("Input should be a valid string" in str(e))
kw = {"123-list": "bulldog"}
l = petstore_api.ListClass(**kw)
l = petstore_api.ListClass(**{"123-list": "bulldog"}) # type: ignore
self.assertEqual(l.to_json(), '{"123-list": "bulldog"}')
self.assertEqual(l.to_dict(), {'123-list': 'bulldog'})
l2 = petstore_api.ListClass.from_json(l.to_json())
self.assertEqual(l2.var_123_list, 'bulldog')
l2 = petstore_api.ListClass.from_json(l.to_json())
assert l2 is not None
self.assertEqual(l2.var_123_list, 'bulldog')
self.assertTrue(isinstance(l2, petstore_api.ListClass))
def test_enum_ref_property(self):
@@ -363,6 +373,7 @@ class ModelTests(unittest.TestCase):
self.assertEqual(d2.to_json(), '{"str_value": "delivered", "value": 1}')
# test from_json (round trip)
d3 = petstore_api.OuterObjectWithEnumProperty.from_json(d2.to_json())
assert d3 is not None
self.assertEqual(d3.str_value, petstore_api.OuterEnum.DELIVERED)
self.assertEqual(d3.value, petstore_api.OuterEnumInteger.NUMBER_1)
self.assertEqual(d3.to_json(), '{"str_value": "delivered", "value": 1}')
@@ -376,7 +387,7 @@ class ModelTests(unittest.TestCase):
def test_valdiator(self):
# test regular expression
a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date="2013-09-17", password="testing09876")
a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date=date(2013, 9, 17), password="testing09876")
try:
a.pattern_with_digits_and_delimiter = "123"
self.assertTrue(False) # this line shouldn't execute
@@ -384,7 +395,7 @@ class ModelTests(unittest.TestCase):
self.assertTrue(r"must validate the regular expression /^image_\d{1,3}$/i" in str(e))
# test None with optional string (with regualr expression)
a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date="2013-09-17", password="testing09876")
a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date=date(2013, 9, 17), password="testing09876")
a.string = None # shouldn't throw an exception
a.pattern_with_digits_and_delimiter = "IMAGE_123"
@@ -475,11 +486,12 @@ class ModelTests(unittest.TestCase):
pet_ap_dict["array"] = ["a", "b"]
pet_ap_dict["dict"] = {"key999": "value999"}
pet_ap2 = petstore_api.Pet.from_dict(pet_ap_dict)
pet_ap3 = petstore_api.Pet.from_dict(pet_ap_dict)
assert pet_ap3 is not None
self.assertEqual(pet_ap2.additional_properties["array"], ["a", "b"])
self.assertEqual(pet_ap2.additional_properties["something-new"], 123)
self.assertEqual(pet_ap2.additional_properties["dict"], {"key999": "value999"})
self.assertEqual(pet_ap3.additional_properties["array"], ["a", "b"])
self.assertEqual(pet_ap3.additional_properties["something-new"], 123)
self.assertEqual(pet_ap3.additional_properties["dict"], {"key999": "value999"})
def test_nullable(self):
h = petstore_api.HealthCheckResult(NullableMessage="Not none")
@@ -507,10 +519,11 @@ class ModelTests(unittest.TestCase):
# for https://github.com/OpenAPITools/openapi-generator/issues/14913
# shouldn't throw exception by the optional dict property
a = petstore_api.ParentWithOptionalDict.from_dict({})
self.assertFalse(a is None)
b = petstore_api.ParentWithOptionalDict.from_dict({"optionalDict": {"key": {"aProperty": {"a": "b"}}}})
self.assertFalse(b is None)
assert b is not None
assert b.optional_dict is not None
assert b.optional_dict["key"].a_property is not None
self.assertEqual(b.optional_dict["key"].a_property["a"], "b")
def test_freeform_object(self):
@@ -530,6 +543,7 @@ class ModelTests(unittest.TestCase):
# for https://github.com/OpenAPITools/openapi-generator/issues/15135
d = {"optionalDict": {"a": {"b": {"aProperty": "value"}}}}
a = petstore_api.Parent.from_dict(d)
assert a is not None
self.assertEqual(a.to_dict(), d)
def test_eum_class(self):
@@ -561,6 +575,7 @@ class ModelTests(unittest.TestCase):
self.assertEqual(a.to_dict(), {'shopIdToOrgOnlineLipMap': {'somekey': [{'id': 123, 'name': 'tag name'}]}})
self.assertEqual(a.to_json(), '{"shopIdToOrgOnlineLipMap": {"somekey": [{"id": 123, "name": "tag name"}]}}')
a2 = petstore_api.MapOfArrayOfModel.from_dict(a.to_dict())
assert a2 is not None
self.assertEqual(a.to_dict(), a2.to_dict())
def test_array_of_array_of_model(self):
@@ -570,6 +585,7 @@ class ModelTests(unittest.TestCase):
self.assertEqual(a.to_dict(), {'another_property': [[ {'id': 123, 'name': 'tag name'} ]]})
self.assertEqual(a.to_json(), '{"another_property": [[{"id": 123, "name": "tag name"}]]}')
a2 = petstore_api.ArrayOfArrayOfModel.from_dict(a.to_dict())
assert a2 is not None
self.assertEqual(a.to_dict(), a2.to_dict())
def test_object_with_additional_properties(self):
@@ -581,12 +597,14 @@ class ModelTests(unittest.TestCase):
def test_first_ref(self):
# shouldn't throw "still a ForwardRef" error
a = petstore_api.FirstRef.from_dict({})
assert a is not None
self.assertEqual(a.to_json(), "{}")
def test_allof(self):
# for issue 16104
model = petstore_api.Tiger.from_json('{"skill": "none", "type": "tiger", "info": {"name": "creature info"}}')
# shouldn't throw NameError
assert model is not None
self.assertEqual(model.to_json(), '{"skill": "none", "type": "tiger", "info": {"name": "creature info"}}')
@@ -609,27 +627,29 @@ class TestdditionalPropertiesAnyType(unittest.TestCase):
class TestUnnamedDictWithAdditionalStringListProperties:
def test_empty_dict(self):
a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dict_property={})
a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dictProperty={})
assert a is not None
assert a.to_dict() == {"dictProperty": {}}
def test_empty_list(self):
a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dict_property={"b": []})
a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dictProperty={"b": []})
assert a is not None
assert a.to_dict() == {"dictProperty": {"b": []}}
def test_single_string_item(self):
a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dict_property={"b": ["c"]})
a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dictProperty={"b": ["c"]})
assert a.to_dict() == {"dictProperty": {"b": ["c"]}}
class TestUnnamedDictWithAdditionalModelListProperties:
def test_empty_dict(self):
a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dict_property={})
a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dictProperty={})
assert a.to_dict() == {"dictProperty": {}}
def test_empty_list(self):
a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dict_property={"b": []})
a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dictProperty={"b": []})
assert a.to_dict() == {"dictProperty": {"b": []}}
def test_single_string_item(self):
value = {"b": [petstore_api.CreatureInfo(name="creature_name")]}
a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dict_property=value)
a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dictProperty=value)
assert a.to_dict() == {"dictProperty": {"b": [{"name": "creature_name"}]}}

View File

@@ -35,7 +35,7 @@ class TimeoutWithEqual(urllib3.Timeout):
return self._read == other._read and self._connect == other._connect and self.total == other.total
class MockPoolManager(object):
class MockPoolManager(urllib3.PoolManager):
def __init__(self, tc):
self._tc = tc
self._reqs = []
@@ -117,16 +117,19 @@ class PetApiTests(unittest.TestCase):
def test_add_pet_and_get_pet_by_id(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id)
self.assertIsNotNone(fetched)
assert fetched is not None
self.assertEqual(self.pet.id, fetched.id)
self.assertIsNotNone(fetched.category)
assert fetched.category is not None
assert self.pet.category is not None
self.assertEqual(self.pet.category.name, fetched.category.name)
def test_add_pet_and_get_pet_by_id_without_preload_content_flag(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
fetched = self.pet_api.get_pet_by_id_without_preload_content(pet_id=self.pet.id)
self.assertIsInstance(fetched, urllib3.HTTPResponse)
@@ -141,30 +144,35 @@ class PetApiTests(unittest.TestCase):
def test_add_pet_and_get_pet_by_id_with_http_info(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
# fetched is an ApiResponse object
fetched = self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id)
self.assertIsNotNone(fetched.data)
assert fetched.data is not None
self.assertEqual(self.pet.id, fetched.data.id)
self.assertIsNotNone(fetched.data.category)
assert fetched.data.category is not None
assert self.pet.category is not None
self.assertEqual(self.pet.category.name, fetched.data.category.name)
def test_get_pet_by_id_serialize(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
fetched = self.pet_api._get_pet_by_id_serialize(self.pet.id, None, None, None, None)
self.assertIsNotNone(fetched)
assert fetched is not None
self.assertIsInstance(fetched, tuple)
def test_update_pet(self):
self.pet.name = "hello kity with updated"
self.pet_api.update_pet(self.pet)
assert self.pet.id is not None
fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id)
self.assertIsNotNone(fetched)
assert fetched is not None
self.assertEqual(self.pet.id, fetched.id)
self.assertEqual(self.pet.name, fetched.name)
self.assertIsNotNone(fetched.category)
assert fetched.category is not None
assert self.pet.category is not None
self.assertEqual(fetched.category.name, self.pet.category.name)
def test_find_pets_by_status(self):
@@ -180,6 +188,8 @@ class PetApiTests(unittest.TestCase):
def test_find_pets_by_tags(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
assert self.tag.name is not None
self.assertIn(
self.pet.id,
@@ -188,6 +198,7 @@ class PetApiTests(unittest.TestCase):
def test_update_pet_with_form(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
name = "hello kity with form updated abc"
status = "pending"
@@ -199,6 +210,7 @@ class PetApiTests(unittest.TestCase):
self.assertEqual(status, fetched.status)
def test_upload_file(self):
assert self.pet.id is not None
# upload file with form parameter
try:
additional_metadata = "special data 123"
@@ -218,6 +230,7 @@ class PetApiTests(unittest.TestCase):
def test_delete_pet(self):
self.pet_api.add_pet(self.pet)
assert self.pet.id is not None
self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key")
try:

View File

@@ -73,11 +73,14 @@ class PetModelTests(unittest.TestCase):
" \"status\": \"available\",\n"
" \"tags\": [{\"id\": 1, \"name\": \"None\"}]}")
pet = petstore_api.Pet.from_json(json_str)
assert pet is not None
self.assertEqual(pet.id, 1)
self.assertEqual(pet.status, "available")
self.assertEqual(pet.photo_urls, ["string"])
assert pet.tags is not None
self.assertEqual(pet.tags[0].id, 1)
self.assertEqual(pet.tags[0].name, "None")
assert pet.category is not None
self.assertEqual(pet.category.id, 1)
# test to_json
self.assertEqual(pet.to_json(),
@@ -91,16 +94,18 @@ class PetModelTests(unittest.TestCase):
# test from_dict
pet2 = petstore_api.Pet.from_dict(pet.to_dict())
assert pet2 is not None
self.assertEqual(pet2.id, 1)
self.assertEqual(pet2.status, "available")
self.assertEqual(pet2.photo_urls, ["string"])
assert pet2.tags is not None
self.assertEqual(pet2.tags[0].id, 1)
self.assertEqual(pet2.tags[0].name, "None")
assert pet2.category is not None
self.assertEqual(pet2.category.id, 1)
def test_unpack_operator(self):
d = {"name": "required name", "id": 123, "photoUrls": ["https://a.com", "https://b.com"]}
pet = petstore_api.Pet(**d)
pet = petstore_api.Pet(name="required name", id=123, photoUrls=["https://a.com", "https://b.com"])
self.assertEqual(pet.to_json(), '{"id": 123, "name": "required name", "photoUrls": ["https://a.com", "https://b.com"]}')
self.assertEqual(pet.to_dict(), {"id": 123, "name": "required name", "photoUrls": ["https://a.com", "https://b.com"]})