mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2025-12-10 01:56:09 +00:00
[python] Renames python generators (#7965)
* python->python-legacy, python-experimental->python * test with openjdk8 * test with openjdk11 * comment out rm * move kotlin tests to circleci * move kotlin tests * move tests to circleci * fix circleci * rearrange test * move tests * use wrapper Co-authored-by: Justin Black <justin.a.black@gmail.com>
This commit is contained in:
@@ -29,6 +29,7 @@ class ApiClientTests(unittest.TestCase):
|
||||
|
||||
def test_configuration(self):
|
||||
config = petstore_api.Configuration()
|
||||
config.host = 'http://localhost/'
|
||||
|
||||
config.api_key['api_key'] = '123456'
|
||||
config.api_key_prefix['api_key'] = 'PREFIX'
|
||||
@@ -45,7 +46,7 @@ class ApiClientTests(unittest.TestCase):
|
||||
self.assertEqual('PREFIX', client.configuration.api_key_prefix['api_key'])
|
||||
|
||||
# update parameters based on auth setting
|
||||
client.update_params_for_auth(header_params, query_params, auth_settings)
|
||||
client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None)
|
||||
|
||||
# test api key auth
|
||||
self.assertEqual(header_params['test1'], 'value1')
|
||||
@@ -56,6 +57,29 @@ class ApiClientTests(unittest.TestCase):
|
||||
self.assertEqual('test_username', client.configuration.username)
|
||||
self.assertEqual('test_password', client.configuration.password)
|
||||
|
||||
# test api key without prefix
|
||||
config.api_key['api_key'] = '123456'
|
||||
config.api_key_prefix['api_key'] = None
|
||||
# update parameters based on auth setting
|
||||
client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None)
|
||||
self.assertEqual(header_params['api_key'], '123456')
|
||||
|
||||
# test api key with empty prefix
|
||||
config.api_key['api_key'] = '123456'
|
||||
config.api_key_prefix['api_key'] = ''
|
||||
# update parameters based on auth setting
|
||||
client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None)
|
||||
self.assertEqual(header_params['api_key'], '123456')
|
||||
|
||||
# test api key with prefix specified in the api_key, useful when the prefix
|
||||
# must include '=' sign followed by the API key secret without space.
|
||||
config.api_key['api_key'] = 'PREFIX=123456'
|
||||
config.api_key_prefix['api_key'] = None
|
||||
# update parameters based on auth setting
|
||||
client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None)
|
||||
self.assertEqual(header_params['api_key'], 'PREFIX=123456')
|
||||
|
||||
|
||||
def test_select_header_accept(self):
|
||||
accepts = ['APPLICATION/JSON', 'APPLICATION/XML']
|
||||
accept = self.api_client.select_header_accept(accepts)
|
||||
@@ -142,23 +166,27 @@ class ApiClientTests(unittest.TestCase):
|
||||
# model
|
||||
pet_dict = {"id": 1, "name": "monkey",
|
||||
"category": {"id": 1, "name": "test category"},
|
||||
"tags": [{"id": 1, "name": "test tag1"},
|
||||
{"id": 2, "name": "test tag2"}],
|
||||
"tags": [{"id": 1, "fullName": "test tag1"},
|
||||
{"id": 2, "fullName": "test tag2"}],
|
||||
"status": "available",
|
||||
"photoUrls": ["http://foo.bar.com/3",
|
||||
"http://foo.bar.com/4"]}
|
||||
pet = petstore_api.Pet(name=pet_dict["name"], photo_urls=pet_dict["photoUrls"])
|
||||
from petstore_api.model.pet import Pet
|
||||
from petstore_api.model.category import Category
|
||||
from petstore_api.model.tag import Tag
|
||||
from petstore_api.model.string_boolean_map import StringBooleanMap
|
||||
pet = Pet(name=pet_dict["name"], photo_urls=pet_dict["photoUrls"])
|
||||
pet.id = pet_dict["id"]
|
||||
cate = petstore_api.Category()
|
||||
cate = Category()
|
||||
cate.id = pet_dict["category"]["id"]
|
||||
cate.name = pet_dict["category"]["name"]
|
||||
pet.category = cate
|
||||
tag1 = petstore_api.Tag()
|
||||
tag1 = Tag()
|
||||
tag1.id = pet_dict["tags"][0]["id"]
|
||||
tag1.name = pet_dict["tags"][0]["name"]
|
||||
tag2 = petstore_api.Tag()
|
||||
tag1.full_name = pet_dict["tags"][0]["fullName"]
|
||||
tag2 = Tag()
|
||||
tag2.id = pet_dict["tags"][1]["id"]
|
||||
tag2.name = pet_dict["tags"][1]["name"]
|
||||
tag2.full_name = pet_dict["tags"][1]["fullName"]
|
||||
pet.tags = [tag1, tag2]
|
||||
pet.status = pet_dict["status"]
|
||||
|
||||
@@ -172,6 +200,12 @@ class ApiClientTests(unittest.TestCase):
|
||||
result = self.api_client.sanitize_for_serialization(data)
|
||||
self.assertEqual(result, list_of_pet_dict)
|
||||
|
||||
# model with additional proerties
|
||||
model_dict = {'some_key': True}
|
||||
model = StringBooleanMap(**model_dict)
|
||||
result = self.api_client.sanitize_for_serialization(model)
|
||||
self.assertEqual(result, model_dict)
|
||||
|
||||
def test_context_manager_closes_threadpool(self):
|
||||
with petstore_api.ApiClient() as client:
|
||||
self.assertIsNotNone(client.pool)
|
||||
|
||||
@@ -15,7 +15,6 @@ import sys
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.rest import ApiException
|
||||
|
||||
from .util import id_gen
|
||||
|
||||
@@ -23,17 +22,19 @@ class ApiExceptionTests(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.api_client = petstore_api.ApiClient()
|
||||
self.pet_api = petstore_api.PetApi(self.api_client)
|
||||
from petstore_api.api.pet_api import PetApi
|
||||
self.pet_api = PetApi(self.api_client)
|
||||
self.setUpModels()
|
||||
|
||||
def setUpModels(self):
|
||||
self.category = petstore_api.Category()
|
||||
from petstore_api.model import category, tag, pet
|
||||
self.category = category.Category()
|
||||
self.category.id = id_gen()
|
||||
self.category.name = "dog"
|
||||
self.tag = petstore_api.Tag()
|
||||
self.tag = tag.Tag()
|
||||
self.tag.id = id_gen()
|
||||
self.tag.name = "blank"
|
||||
self.pet = petstore_api.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"])
|
||||
self.tag.full_name = "blank"
|
||||
self.pet = pet.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"])
|
||||
self.pet.id = id_gen()
|
||||
self.pet.status = "sold"
|
||||
self.pet.category = self.category
|
||||
@@ -43,12 +44,12 @@ class ApiExceptionTests(unittest.TestCase):
|
||||
self.pet_api.add_pet(self.pet)
|
||||
self.pet_api.delete_pet(pet_id=self.pet.id)
|
||||
|
||||
with self.checkRaiseRegex(ApiException, "Pet not found"):
|
||||
with self.checkRaiseRegex(petstore_api.ApiException, "Pet not found"):
|
||||
self.pet_api.get_pet_by_id(pet_id=self.pet.id)
|
||||
|
||||
try:
|
||||
self.pet_api.get_pet_by_id(pet_id=self.pet.id)
|
||||
except ApiException as e:
|
||||
except petstore_api.ApiException as e:
|
||||
self.assertEqual(e.status, 404)
|
||||
self.assertEqual(e.reason, "Not Found")
|
||||
self.checkRegex(e.body, "Pet not found")
|
||||
@@ -56,20 +57,18 @@ class ApiExceptionTests(unittest.TestCase):
|
||||
def test_500_error(self):
|
||||
self.pet_api.add_pet(self.pet)
|
||||
|
||||
with self.checkRaiseRegex(ApiException, "Internal Server Error"):
|
||||
with self.checkRaiseRegex(petstore_api.ApiException, "Internal Server Error"):
|
||||
self.pet_api.upload_file(
|
||||
pet_id=self.pet.id,
|
||||
additional_metadata="special",
|
||||
file=None
|
||||
additional_metadata="special"
|
||||
)
|
||||
|
||||
try:
|
||||
self.pet_api.upload_file(
|
||||
pet_id=self.pet.id,
|
||||
additional_metadata="special",
|
||||
file=None
|
||||
additional_metadata="special"
|
||||
)
|
||||
except ApiException as e:
|
||||
except petstore_api.ApiException as e:
|
||||
self.assertEqual(e.status, 500)
|
||||
self.assertEqual(e.reason, "Internal Server Error")
|
||||
self.checkRegex(e.body, "Error 500 Internal Server Error")
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd petstore_api-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
from __future__ import absolute_import
|
||||
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
|
||||
|
||||
class TestConfiguration(unittest.TestCase):
|
||||
"""Animal unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
# reset Configuration
|
||||
petstore_api.Configuration.set_default(None)
|
||||
|
||||
def testConfiguration(self):
|
||||
# check that different instances use different dictionaries
|
||||
c1 = petstore_api.Configuration()
|
||||
c2 = petstore_api.Configuration()
|
||||
self.assertNotEqual(id(c1.api_key), id(c2.api_key))
|
||||
self.assertNotEqual(id(c1.api_key_prefix), id(c2.api_key_prefix))
|
||||
|
||||
def testDefaultConfiguration(self):
|
||||
|
||||
# prepare default configuration
|
||||
c1 = petstore_api.Configuration(host="example.com")
|
||||
c1.debug = True
|
||||
petstore_api.Configuration.set_default(c1)
|
||||
|
||||
# get default configuration
|
||||
c2 = petstore_api.Configuration.get_default_copy()
|
||||
self.assertEqual(c2.host, "example.com")
|
||||
self.assertTrue(c2.debug)
|
||||
|
||||
self.assertNotEqual(id(c1.api_key), id(c2.api_key))
|
||||
self.assertNotEqual(id(c1.api_key_prefix), id(c2.api_key_prefix))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -15,12 +15,36 @@ import time
|
||||
import unittest
|
||||
import datetime
|
||||
|
||||
import six
|
||||
|
||||
import petstore_api
|
||||
|
||||
from petstore_api.exceptions import (
|
||||
ApiTypeError,
|
||||
ApiKeyError,
|
||||
ApiValueError,
|
||||
)
|
||||
from petstore_api.model import (
|
||||
enum_test,
|
||||
pet,
|
||||
animal,
|
||||
dog,
|
||||
parent_pet,
|
||||
child_lizard,
|
||||
category,
|
||||
string_enum,
|
||||
number_with_validations,
|
||||
string_boolean_map,
|
||||
)
|
||||
from petstore_api.model_utils import (
|
||||
file_type,
|
||||
model_to_dict,
|
||||
)
|
||||
|
||||
from petstore_api.rest import RESTResponse
|
||||
|
||||
MockResponse = namedtuple('MockResponse', 'data')
|
||||
|
||||
|
||||
class DeserializationTests(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
@@ -35,20 +59,27 @@ class DeserializationTests(unittest.TestCase):
|
||||
"enum_string_required": "lower",
|
||||
"enum_integer": 1,
|
||||
"enum_number": 1.1,
|
||||
"outerEnum": "placed"
|
||||
"stringEnum": "placed"
|
||||
}
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, 'dict(str, EnumTest)')
|
||||
deserialized = self.deserialize(response,
|
||||
({str: (enum_test.EnumTest,)},), True)
|
||||
self.assertTrue(isinstance(deserialized, dict))
|
||||
self.assertTrue(isinstance(deserialized['enum_test'], petstore_api.EnumTest))
|
||||
self.assertEqual(deserialized['enum_test'],
|
||||
petstore_api.EnumTest(enum_string="UPPER",
|
||||
enum_string_required="lower",
|
||||
enum_integer=1,
|
||||
enum_number=1.1,
|
||||
outer_enum=petstore_api.OuterEnum.PLACED))
|
||||
self.assertTrue(
|
||||
isinstance(deserialized['enum_test'], enum_test.EnumTest))
|
||||
value = (
|
||||
string_enum.StringEnum.allowed_values[('value',)]["PLACED"])
|
||||
string_enum_val = string_enum.StringEnum(value)
|
||||
sample_instance = enum_test.EnumTest(
|
||||
enum_string="UPPER",
|
||||
enum_string_required="lower",
|
||||
enum_integer=1,
|
||||
enum_number=1.1,
|
||||
string_enum=string_enum_val
|
||||
)
|
||||
self.assertEqual(deserialized['enum_test'], sample_instance)
|
||||
|
||||
def test_deserialize_dict_str_pet(self):
|
||||
""" deserialize dict(str, Pet) """
|
||||
@@ -66,7 +97,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
"tags": [
|
||||
{
|
||||
"id": 0,
|
||||
"name": "string"
|
||||
"fullName": "string"
|
||||
}
|
||||
],
|
||||
"status": "available"
|
||||
@@ -74,25 +105,44 @@ class DeserializationTests(unittest.TestCase):
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, 'dict(str, Pet)')
|
||||
deserialized = self.deserialize(response,
|
||||
({str: (pet.Pet,)},), True)
|
||||
self.assertTrue(isinstance(deserialized, dict))
|
||||
self.assertTrue(isinstance(deserialized['pet'], petstore_api.Pet))
|
||||
self.assertTrue(isinstance(deserialized['pet'], pet.Pet))
|
||||
|
||||
def test_deserialize_dict_str_dog(self):
|
||||
""" deserialize dict(str, Dog), use discriminator"""
|
||||
data = {
|
||||
'dog': {
|
||||
"id": 0,
|
||||
"className": "Dog",
|
||||
"color": "white",
|
||||
"bread": "Jack Russel Terrier"
|
||||
"breed": "Jack Russel Terrier"
|
||||
}
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, 'dict(str, Animal)')
|
||||
deserialized = self.deserialize(response,
|
||||
({str: (animal.Animal,)},), True)
|
||||
self.assertTrue(isinstance(deserialized, dict))
|
||||
self.assertTrue(isinstance(deserialized['dog'], petstore_api.Dog))
|
||||
dog_inst = deserialized['dog']
|
||||
self.assertTrue(isinstance(dog_inst, dog.Dog))
|
||||
self.assertEqual(dog_inst.class_name, "Dog")
|
||||
self.assertEqual(dog_inst.color, "white")
|
||||
self.assertEqual(dog_inst.breed, "Jack Russel Terrier")
|
||||
|
||||
def test_deserialize_lizard(self):
|
||||
""" deserialize ChildLizard, use discriminator"""
|
||||
data = {
|
||||
"pet_type": "ChildLizard",
|
||||
"lovesRocks": True
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
lizard = self.deserialize(response,
|
||||
(parent_pet.ParentPet,), True)
|
||||
self.assertTrue(isinstance(lizard, child_lizard.ChildLizard))
|
||||
self.assertEqual(lizard.pet_type, "ChildLizard")
|
||||
self.assertEqual(lizard.loves_rocks, True)
|
||||
|
||||
def test_deserialize_dict_str_int(self):
|
||||
""" deserialize dict(str, int) """
|
||||
@@ -101,7 +151,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, 'dict(str, int)')
|
||||
deserialized = self.deserialize(response, ({str: (int,)},), True)
|
||||
self.assertTrue(isinstance(deserialized, dict))
|
||||
self.assertTrue(isinstance(deserialized['integer'], int))
|
||||
|
||||
@@ -110,7 +160,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
data = "test str"
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, "str")
|
||||
deserialized = self.deserialize(response, (str,), True)
|
||||
self.assertTrue(isinstance(deserialized, str))
|
||||
|
||||
def test_deserialize_date(self):
|
||||
@@ -118,7 +168,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
data = "1997-07-16"
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, "date")
|
||||
deserialized = self.deserialize(response, (datetime.date,), True)
|
||||
self.assertTrue(isinstance(deserialized, datetime.date))
|
||||
|
||||
def test_deserialize_datetime(self):
|
||||
@@ -126,7 +176,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
data = "1997-07-16T19:20:30.45+01:00"
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, "datetime")
|
||||
deserialized = self.deserialize(response, (datetime.datetime,), True)
|
||||
self.assertTrue(isinstance(deserialized, datetime.datetime))
|
||||
|
||||
def test_deserialize_pet(self):
|
||||
@@ -144,21 +194,21 @@ class DeserializationTests(unittest.TestCase):
|
||||
"tags": [
|
||||
{
|
||||
"id": 0,
|
||||
"name": "string"
|
||||
"fullName": "string"
|
||||
}
|
||||
],
|
||||
"status": "available"
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, "Pet")
|
||||
self.assertTrue(isinstance(deserialized, petstore_api.Pet))
|
||||
deserialized = self.deserialize(response, (pet.Pet,), True)
|
||||
self.assertTrue(isinstance(deserialized, pet.Pet))
|
||||
self.assertEqual(deserialized.id, 0)
|
||||
self.assertEqual(deserialized.name, "doggie")
|
||||
self.assertTrue(isinstance(deserialized.category, petstore_api.Category))
|
||||
self.assertTrue(isinstance(deserialized.category, category.Category))
|
||||
self.assertEqual(deserialized.category.name, "string")
|
||||
self.assertTrue(isinstance(deserialized.tags, list))
|
||||
self.assertEqual(deserialized.tags[0].name, "string")
|
||||
self.assertEqual(deserialized.tags[0].full_name, "string")
|
||||
|
||||
def test_deserialize_list_of_pet(self):
|
||||
""" deserialize list[Pet] """
|
||||
@@ -176,7 +226,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
"tags": [
|
||||
{
|
||||
"id": 0,
|
||||
"name": "string"
|
||||
"fullName": "string"
|
||||
}
|
||||
],
|
||||
"status": "available"
|
||||
@@ -194,16 +244,17 @@ class DeserializationTests(unittest.TestCase):
|
||||
"tags": [
|
||||
{
|
||||
"id": 0,
|
||||
"name": "string"
|
||||
"fullName": "string"
|
||||
}
|
||||
],
|
||||
"status": "available"
|
||||
}]
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, "list[Pet]")
|
||||
deserialized = self.deserialize(response,
|
||||
([pet.Pet],), True)
|
||||
self.assertTrue(isinstance(deserialized, list))
|
||||
self.assertTrue(isinstance(deserialized[0], petstore_api.Pet))
|
||||
self.assertTrue(isinstance(deserialized[0], pet.Pet))
|
||||
self.assertEqual(deserialized[0].id, 0)
|
||||
self.assertEqual(deserialized[1].id, 1)
|
||||
self.assertEqual(deserialized[0].name, "doggie0")
|
||||
@@ -218,7 +269,8 @@ class DeserializationTests(unittest.TestCase):
|
||||
}
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, "dict(str, dict(str, int))")
|
||||
deserialized = self.deserialize(response,
|
||||
({str: ({str: (int,)},)},), True)
|
||||
self.assertTrue(isinstance(deserialized, dict))
|
||||
self.assertTrue(isinstance(deserialized["foo"], dict))
|
||||
self.assertTrue(isinstance(deserialized["foo"]["bar"], int))
|
||||
@@ -228,7 +280,7 @@ class DeserializationTests(unittest.TestCase):
|
||||
data = [["foo"]]
|
||||
response = MockResponse(data=json.dumps(data))
|
||||
|
||||
deserialized = self.deserialize(response, "list[list[str]]")
|
||||
deserialized = self.deserialize(response, ([[str]],), True)
|
||||
self.assertTrue(isinstance(deserialized, list))
|
||||
self.assertTrue(isinstance(deserialized[0], list))
|
||||
self.assertTrue(isinstance(deserialized[0][0], str))
|
||||
@@ -237,5 +289,153 @@ class DeserializationTests(unittest.TestCase):
|
||||
""" deserialize None """
|
||||
response = MockResponse(data=json.dumps(None))
|
||||
|
||||
deserialized = self.deserialize(response, "datetime")
|
||||
self.assertIsNone(deserialized)
|
||||
error_msg = (
|
||||
"Invalid type for variable 'received_data'. Required value type is "
|
||||
"datetime and passed type was NoneType at ['received_data']"
|
||||
)
|
||||
with self.assertRaises(ApiTypeError) as exc:
|
||||
deserialized = self.deserialize(response, (datetime.datetime,), True)
|
||||
self.assertEqual(str(exc.exception), error_msg)
|
||||
|
||||
def test_deserialize_OuterEnum(self):
|
||||
""" deserialize OuterEnum """
|
||||
# make sure that an exception is thrown on an invalid value
|
||||
with self.assertRaises(ApiValueError):
|
||||
self.deserialize(
|
||||
MockResponse(data=json.dumps("test str")),
|
||||
(string_enum.StringEnum,),
|
||||
True
|
||||
)
|
||||
|
||||
# valid value works
|
||||
placed_str = (
|
||||
string_enum.StringEnum.allowed_values[('value',)]["PLACED"]
|
||||
)
|
||||
response = MockResponse(data=json.dumps(placed_str))
|
||||
deserialized = self.deserialize(response,
|
||||
(string_enum.StringEnum,), True)
|
||||
self.assertTrue(isinstance(deserialized, string_enum.StringEnum))
|
||||
self.assertTrue(deserialized.value == placed_str)
|
||||
|
||||
def test_deserialize_NumberWithValidations(self):
|
||||
""" deserialize NumberWithValidations """
|
||||
# make sure that an exception is thrown on an invalid type value
|
||||
with self.assertRaises(ApiTypeError):
|
||||
deserialized = self.deserialize(
|
||||
MockResponse(data=json.dumps("test str")),
|
||||
(number_with_validations.NumberWithValidations,),
|
||||
True
|
||||
)
|
||||
|
||||
# make sure that an exception is thrown on an invalid value
|
||||
with self.assertRaises(ApiValueError):
|
||||
deserialized = self.deserialize(
|
||||
MockResponse(data=json.dumps(21.0)),
|
||||
(number_with_validations.NumberWithValidations,),
|
||||
True
|
||||
)
|
||||
|
||||
# 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)
|
||||
|
||||
def test_deserialize_file(self):
|
||||
"""Ensures that file deserialization works"""
|
||||
response_types_mixed = (file_type,)
|
||||
|
||||
# sample from http://www.jtricks.com/download-text
|
||||
HTTPResponse = namedtuple(
|
||||
'urllib3_response_HTTPResponse',
|
||||
['status', 'reason', 'data', 'getheaders', 'getheader']
|
||||
)
|
||||
headers = {'Content-Disposition': 'attachment; filename=content.txt'}
|
||||
def get_headers():
|
||||
return headers
|
||||
def get_header(name, default=None):
|
||||
return headers.get(name, default)
|
||||
file_data = (
|
||||
"You are reading text file that was supposed to be downloaded\r\n"
|
||||
"to your hard disk. If your browser offered to save you the file,"
|
||||
"\r\nthen it handled the Content-Disposition header correctly."
|
||||
)
|
||||
http_response = HTTPResponse(
|
||||
status=200,
|
||||
reason='OK',
|
||||
data=file_data,
|
||||
getheaders=get_headers,
|
||||
getheader=get_header
|
||||
)
|
||||
# response which is deserialized to a file
|
||||
mock_response = RESTResponse(http_response)
|
||||
file_path = None
|
||||
try:
|
||||
file_object = self.deserialize(
|
||||
mock_response, response_types_mixed, True)
|
||||
self.assertTrue(isinstance(file_object, file_type))
|
||||
file_path = file_object.name
|
||||
self.assertFalse(file_object.closed)
|
||||
file_object.close()
|
||||
if six.PY3:
|
||||
file_data = file_data.encode('utf-8')
|
||||
with open(file_path, 'rb') as other_file_object:
|
||||
self.assertEqual(other_file_object.read(), file_data)
|
||||
finally:
|
||||
os.unlink(file_path)
|
||||
|
||||
def test_deserialize_binary_to_str(self):
|
||||
"""Ensures that bytes deserialization works"""
|
||||
response_types_mixed = (str,)
|
||||
|
||||
# sample from http://www.jtricks.com/download-text
|
||||
HTTPResponse = namedtuple(
|
||||
'urllib3_response_HTTPResponse',
|
||||
['status', 'reason', 'data', 'getheaders', 'getheader']
|
||||
)
|
||||
headers = {}
|
||||
def get_headers():
|
||||
return headers
|
||||
def get_header(name, default=None):
|
||||
return headers.get(name, default)
|
||||
data = "str"
|
||||
|
||||
http_response = HTTPResponse(
|
||||
status=200,
|
||||
reason='OK',
|
||||
data=json.dumps(data).encode("utf-8") if six.PY3 else json.dumps(data),
|
||||
getheaders=get_headers,
|
||||
getheader=get_header
|
||||
)
|
||||
|
||||
mock_response = RESTResponse(http_response)
|
||||
|
||||
result = self.deserialize(mock_response, response_types_mixed, True)
|
||||
self.assertEqual(isinstance(result, str), True)
|
||||
self.assertEqual(result, data)
|
||||
|
||||
def test_deserialize_string_boolean_map(self):
|
||||
"""
|
||||
Ensures that string boolean (additional properties)
|
||||
deserialization works
|
||||
"""
|
||||
# make sure that an exception is thrown on an invalid type
|
||||
with self.assertRaises(ApiTypeError):
|
||||
deserialized = self.deserialize(
|
||||
MockResponse(data=json.dumps("test str")),
|
||||
(string_boolean_map.StringBooleanMap,),
|
||||
True
|
||||
)
|
||||
|
||||
# valid value works
|
||||
item_val = {'some_key': True}
|
||||
response = MockResponse(data=json.dumps(item_val))
|
||||
model = string_boolean_map.StringBooleanMap(**item_val)
|
||||
deserialized = self.deserialize(response,
|
||||
(string_boolean_map.StringBooleanMap,), True)
|
||||
self.assertTrue(isinstance(deserialized, string_boolean_map.StringBooleanMap))
|
||||
self.assertTrue(deserialized['some_key'] == True)
|
||||
self.assertTrue(deserialized == model)
|
||||
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd petstore_api-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
|
||||
|
||||
class EnumArraysTests(unittest.TestCase):
|
||||
|
||||
def test_enumarrays_init(self):
|
||||
#
|
||||
# Check various combinations of valid values.
|
||||
#
|
||||
fish_or_crab = petstore_api.EnumArrays(just_symbol=">=")
|
||||
self.assertEqual(fish_or_crab.just_symbol, ">=")
|
||||
self.assertEqual(fish_or_crab.array_enum, None)
|
||||
|
||||
fish_or_crab = petstore_api.EnumArrays(just_symbol="$", array_enum=["fish"])
|
||||
self.assertEqual(fish_or_crab.just_symbol, "$")
|
||||
self.assertEqual(fish_or_crab.array_enum, ["fish"])
|
||||
|
||||
fish_or_crab = petstore_api.EnumArrays(just_symbol=">=", array_enum=["fish"])
|
||||
self.assertEqual(fish_or_crab.just_symbol, ">=")
|
||||
self.assertEqual(fish_or_crab.array_enum, ["fish"])
|
||||
|
||||
fish_or_crab = petstore_api.EnumArrays("$", ["crab"])
|
||||
self.assertEqual(fish_or_crab.just_symbol, "$")
|
||||
self.assertEqual(fish_or_crab.array_enum, ["crab"])
|
||||
|
||||
|
||||
#
|
||||
# Check if setting invalid values fails
|
||||
#
|
||||
try:
|
||||
fish_or_crab = petstore_api.EnumArrays(just_symbol="<=")
|
||||
self.assertTrue(0)
|
||||
except ValueError:
|
||||
self.assertTrue(1)
|
||||
|
||||
try:
|
||||
fish_or_crab = petstore_api.EnumArrays(just_symbol="$", array_enum=["dog"])
|
||||
self.assertTrue(0)
|
||||
except ValueError:
|
||||
self.assertTrue(1)
|
||||
|
||||
try:
|
||||
fish_or_crab = petstore_api.EnumArrays(just_symbol=["$"], array_enum=["dog"])
|
||||
self.assertTrue(0)
|
||||
except ValueError:
|
||||
self.assertTrue(1)
|
||||
|
||||
|
||||
def test_enumarrays_setter(self):
|
||||
|
||||
#
|
||||
# Check various combinations of valid values
|
||||
#
|
||||
fish_or_crab = petstore_api.EnumArrays()
|
||||
|
||||
fish_or_crab.just_symbol = ">="
|
||||
self.assertEqual(fish_or_crab.just_symbol, ">=")
|
||||
|
||||
fish_or_crab.just_symbol = "$"
|
||||
self.assertEqual(fish_or_crab.just_symbol, "$")
|
||||
|
||||
fish_or_crab.array_enum = []
|
||||
self.assertEqual(fish_or_crab.array_enum, [])
|
||||
|
||||
fish_or_crab.array_enum = ["fish"]
|
||||
self.assertEqual(fish_or_crab.array_enum, ["fish"])
|
||||
|
||||
fish_or_crab.array_enum = ["fish", "fish", "fish"]
|
||||
self.assertEqual(fish_or_crab.array_enum, ["fish", "fish", "fish"])
|
||||
|
||||
fish_or_crab.array_enum = ["crab"]
|
||||
self.assertEqual(fish_or_crab.array_enum, ["crab"])
|
||||
|
||||
fish_or_crab.array_enum = ["crab", "fish"]
|
||||
self.assertEqual(fish_or_crab.array_enum, ["crab", "fish"])
|
||||
|
||||
fish_or_crab.array_enum = ["crab", "fish", "crab", "fish"]
|
||||
self.assertEqual(fish_or_crab.array_enum, ["crab", "fish", "crab", "fish"])
|
||||
|
||||
#
|
||||
# Check if setting invalid values fails
|
||||
#
|
||||
fish_or_crab = petstore_api.EnumArrays()
|
||||
try:
|
||||
fish_or_crab.just_symbol = "!="
|
||||
except ValueError:
|
||||
self.assertEqual(fish_or_crab.just_symbol, None)
|
||||
|
||||
try:
|
||||
fish_or_crab.just_symbol = ["fish"]
|
||||
except ValueError:
|
||||
self.assertEqual(fish_or_crab.just_symbol, None)
|
||||
|
||||
try:
|
||||
fish_or_crab.array_enum = ["cat"]
|
||||
except ValueError:
|
||||
self.assertEqual(fish_or_crab.array_enum, None)
|
||||
|
||||
try:
|
||||
fish_or_crab.array_enum = ["fish", "crab", "dog"]
|
||||
except ValueError:
|
||||
self.assertEqual(fish_or_crab.array_enum, None)
|
||||
|
||||
try:
|
||||
fish_or_crab.array_enum = "fish"
|
||||
except ValueError:
|
||||
self.assertEqual(fish_or_crab.array_enum, None)
|
||||
|
||||
|
||||
def test_todict(self):
|
||||
#
|
||||
# Check if dictionary serialization works
|
||||
#
|
||||
dollar_fish_crab_dict = {
|
||||
'just_symbol': "$",
|
||||
'array_enum': ["fish", "crab"]
|
||||
}
|
||||
|
||||
dollar_fish_crab = petstore_api.EnumArrays("$", ["fish", "crab"])
|
||||
|
||||
self.assertEqual(dollar_fish_crab_dict, dollar_fish_crab.to_dict())
|
||||
|
||||
#
|
||||
# Sanity check for different arrays
|
||||
#
|
||||
dollar_crab_fish_dict = {
|
||||
'just_symbol': "$",
|
||||
'array_enum': ["crab", "fish"]
|
||||
}
|
||||
|
||||
dollar_fish_crab = petstore_api.EnumArrays("$", ["fish", "crab"])
|
||||
|
||||
self.assertNotEqual(dollar_crab_fish_dict, dollar_fish_crab.to_dict())
|
||||
|
||||
|
||||
def test_equals(self):
|
||||
#
|
||||
# Check if object comparison works
|
||||
#
|
||||
fish1 = petstore_api.EnumArrays("$", ["fish"])
|
||||
fish2 = petstore_api.EnumArrays("$", ["fish"])
|
||||
self.assertEqual(fish1, fish2)
|
||||
|
||||
fish = petstore_api.EnumArrays("$", ["fish"])
|
||||
crab = petstore_api.EnumArrays("$", ["crab"])
|
||||
self.assertNotEqual(fish, crab)
|
||||
|
||||
dollar = petstore_api.EnumArrays("$")
|
||||
greater = petstore_api.EnumArrays(">=")
|
||||
self.assertNotEqual(dollar, greater)
|
||||
@@ -1,117 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd petstore_api-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
|
||||
|
||||
class MapTestTests(unittest.TestCase):
|
||||
|
||||
def test_maptest_init(self):
|
||||
#
|
||||
# Test MapTest construction with valid values
|
||||
#
|
||||
up_or_low_dict = {
|
||||
'UPPER': "UP",
|
||||
'lower': "low"
|
||||
}
|
||||
map_enum_test = petstore_api.MapTest(map_of_enum_string=up_or_low_dict)
|
||||
|
||||
self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict)
|
||||
|
||||
map_of_map_of_strings = {
|
||||
'val1': 1,
|
||||
'valText': "Text",
|
||||
'valueDict': up_or_low_dict
|
||||
}
|
||||
map_enum_test = petstore_api.MapTest(map_map_of_string=map_of_map_of_strings)
|
||||
|
||||
self.assertEqual(map_enum_test.map_map_of_string, map_of_map_of_strings)
|
||||
|
||||
#
|
||||
# Make sure that the init fails for invalid enum values
|
||||
#
|
||||
black_or_white_dict = {
|
||||
'black': "UP",
|
||||
'white': "low"
|
||||
}
|
||||
try:
|
||||
map_enum_test = petstore_api.MapTest(map_of_enum_string=black_or_white_dict)
|
||||
self.assertTrue(0)
|
||||
except ValueError:
|
||||
self.assertTrue(1)
|
||||
|
||||
def test_maptest_setter(self):
|
||||
#
|
||||
# Check with some valid values
|
||||
#
|
||||
map_enum_test = petstore_api.MapTest()
|
||||
up_or_low_dict = {
|
||||
'UPPER': "UP",
|
||||
'lower': "low"
|
||||
}
|
||||
map_enum_test.map_of_enum_string = up_or_low_dict
|
||||
self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict)
|
||||
|
||||
#
|
||||
# Check if the setter fails for invalid enum values
|
||||
#
|
||||
map_enum_test = petstore_api.MapTest()
|
||||
black_or_white_dict = {
|
||||
'black': "UP",
|
||||
'white': "low"
|
||||
}
|
||||
try:
|
||||
map_enum_test.map_of_enum_string = black_or_white_dict
|
||||
except ValueError:
|
||||
self.assertEqual(map_enum_test.map_of_enum_string, None)
|
||||
|
||||
def test_todict(self):
|
||||
#
|
||||
# Check dictionary serialization
|
||||
#
|
||||
map_enum_test = petstore_api.MapTest()
|
||||
up_or_low_dict = {
|
||||
'UPPER': "UP",
|
||||
'lower': "low"
|
||||
}
|
||||
map_of_map_of_strings = {
|
||||
'val1': 1,
|
||||
'valText': "Text",
|
||||
'valueDict': up_or_low_dict
|
||||
}
|
||||
indirect_map = {
|
||||
'option1': True
|
||||
}
|
||||
direct_map = {
|
||||
'option2': False
|
||||
}
|
||||
map_enum_test.map_of_enum_string = up_or_low_dict
|
||||
map_enum_test.map_map_of_string = map_of_map_of_strings
|
||||
map_enum_test.indirect_map = indirect_map
|
||||
map_enum_test.direct_map = direct_map
|
||||
|
||||
self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict)
|
||||
self.assertEqual(map_enum_test.map_map_of_string, map_of_map_of_strings)
|
||||
self.assertEqual(map_enum_test.indirect_map, indirect_map)
|
||||
self.assertEqual(map_enum_test.direct_map, direct_map)
|
||||
|
||||
expected_dict = {
|
||||
'map_of_enum_string': up_or_low_dict,
|
||||
'map_map_of_string': map_of_map_of_strings,
|
||||
'indirect_map': indirect_map,
|
||||
'direct_map': direct_map
|
||||
}
|
||||
|
||||
self.assertEqual(map_enum_test.to_dict(), expected_dict)
|
||||
@@ -1,27 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd petstore_api-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
|
||||
|
||||
class OrderModelTests(unittest.TestCase):
|
||||
|
||||
def test_status(self):
|
||||
order = petstore_api.Order()
|
||||
order.status = "placed"
|
||||
self.assertEqual("placed", order.status)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
order.status = "invalid"
|
||||
@@ -11,20 +11,37 @@ $ cd petstore_api-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
|
||||
from collections import namedtuple
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api import Configuration
|
||||
from petstore_api.rest import ApiException
|
||||
from petstore_api.rest import (
|
||||
RESTClientObject,
|
||||
RESTResponse
|
||||
)
|
||||
|
||||
import six
|
||||
|
||||
from petstore_api.exceptions import (
|
||||
ApiException,
|
||||
ApiValueError,
|
||||
ApiTypeError,
|
||||
)
|
||||
from petstore_api.api.pet_api import PetApi
|
||||
from petstore_api.model import pet
|
||||
from .util import id_gen
|
||||
|
||||
import json
|
||||
|
||||
import urllib3
|
||||
|
||||
HOST = 'http://petstore.swagger.io/v2'
|
||||
if six.PY3:
|
||||
from unittest.mock import patch
|
||||
else:
|
||||
from mock import patch
|
||||
|
||||
HOST = 'http://localhost/v2'
|
||||
|
||||
|
||||
class TimeoutWithEqual(urllib3.Timeout):
|
||||
@@ -59,18 +76,19 @@ class PetApiTests(unittest.TestCase):
|
||||
config.host = HOST
|
||||
config.access_token = 'ACCESS_TOKEN'
|
||||
self.api_client = petstore_api.ApiClient(config)
|
||||
self.pet_api = petstore_api.PetApi(self.api_client)
|
||||
self.pet_api = PetApi(self.api_client)
|
||||
self.setUpModels()
|
||||
self.setUpFiles()
|
||||
|
||||
def setUpModels(self):
|
||||
self.category = petstore_api.Category()
|
||||
from petstore_api.model import category, tag
|
||||
self.category = category.Category()
|
||||
self.category.id = id_gen()
|
||||
self.category.name = "dog"
|
||||
self.tag = petstore_api.Tag()
|
||||
self.tag = tag.Tag()
|
||||
self.tag.id = id_gen()
|
||||
self.tag.name = "python-pet-tag"
|
||||
self.pet = petstore_api.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"])
|
||||
self.pet = pet.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"])
|
||||
self.pet.id = id_gen()
|
||||
self.pet.status = "sold"
|
||||
self.pet.category = self.category
|
||||
@@ -79,7 +97,6 @@ class PetApiTests(unittest.TestCase):
|
||||
def setUpFiles(self):
|
||||
self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles")
|
||||
self.test_file_dir = os.path.realpath(self.test_file_dir)
|
||||
self.foo = os.path.join(self.test_file_dir, "foo.png")
|
||||
|
||||
def test_preload_content_flag(self):
|
||||
self.pet_api.add_pet(self.pet)
|
||||
@@ -101,17 +118,42 @@ class PetApiTests(unittest.TestCase):
|
||||
resp.close()
|
||||
resp.release_conn()
|
||||
|
||||
def test_config(self):
|
||||
config = Configuration(host=HOST)
|
||||
self.assertIsNotNone(config.get_host_settings())
|
||||
self.assertEqual(config.get_basic_auth_token(),
|
||||
urllib3.util.make_headers(basic_auth=":").get('authorization'))
|
||||
# No authentication scheme has been configured at this point, so auth_settings()
|
||||
# should return an empty list.
|
||||
self.assertEqual(len(config.auth_settings()), 0)
|
||||
# Configure OAuth2 access token and verify the auth_settings have OAuth2 parameters.
|
||||
config.access_token = 'MY-ACCESS_TOKEN'
|
||||
self.assertEqual(len(config.auth_settings()), 1)
|
||||
self.assertIn("petstore_auth", config.auth_settings().keys())
|
||||
config.username = "user"
|
||||
config.password = "password"
|
||||
self.assertEqual(
|
||||
config.get_basic_auth_token(),
|
||||
urllib3.util.make_headers(basic_auth="user:password").get('authorization'))
|
||||
self.assertEqual(len(config.auth_settings()), 2)
|
||||
self.assertIn("petstore_auth", config.auth_settings().keys())
|
||||
self.assertIn("http_basic_test", config.auth_settings().keys())
|
||||
config.username = None
|
||||
config.password = None
|
||||
self.assertEqual(len(config.auth_settings()), 1)
|
||||
self.assertIn("petstore_auth", config.auth_settings().keys())
|
||||
|
||||
def test_timeout(self):
|
||||
mock_pool = MockPoolManager(self)
|
||||
self.api_client.rest_client.pool_manager = mock_pool
|
||||
|
||||
mock_pool.expect_request('POST', HOST + '/pet',
|
||||
mock_pool.expect_request('POST', 'http://localhost/v2/pet',
|
||||
body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)),
|
||||
headers={'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ACCESS_TOKEN',
|
||||
'User-Agent': 'OpenAPI-Generator/1.0.0/python'},
|
||||
preload_content=True, timeout=TimeoutWithEqual(total=5))
|
||||
mock_pool.expect_request('POST', HOST + '/pet',
|
||||
mock_pool.expect_request('POST', 'http://localhost/v2/pet',
|
||||
body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)),
|
||||
headers={'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ACCESS_TOKEN',
|
||||
@@ -121,33 +163,9 @@ class PetApiTests(unittest.TestCase):
|
||||
self.pet_api.add_pet(self.pet, _request_timeout=5)
|
||||
self.pet_api.add_pet(self.pet, _request_timeout=(1, 2))
|
||||
|
||||
def test_auth_settings(self):
|
||||
mock_pool = MockPoolManager(self)
|
||||
self.api_client.rest_client.pool_manager = mock_pool
|
||||
|
||||
mock_pool.expect_request('POST', HOST + '/pet',
|
||||
body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)),
|
||||
headers={'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ACCESS_TOKEN',
|
||||
'User-Agent': 'OpenAPI-Generator/1.0.0/python'},
|
||||
preload_content=True, timeout=None)
|
||||
mock_pool.expect_request('POST', HOST + '/pet',
|
||||
body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)),
|
||||
headers={'Content-Type': 'application/json',
|
||||
'Authorization': 'Prefix ANOTHER_TOKEN',
|
||||
'User-Agent': 'OpenAPI-Generator/1.0.0/python'},
|
||||
preload_content=True, timeout=None)
|
||||
|
||||
self.pet_api.add_pet(self.pet, _request_auth=None)
|
||||
self.pet_api.add_pet(self.pet, _request_auth={
|
||||
'in': 'header',
|
||||
'key': 'Authorization',
|
||||
'value': 'Prefix ANOTHER_TOKEN'
|
||||
})
|
||||
|
||||
def test_separate_default_client_instances(self):
|
||||
pet_api = petstore_api.PetApi()
|
||||
pet_api2 = petstore_api.PetApi()
|
||||
pet_api = PetApi()
|
||||
pet_api2 = PetApi()
|
||||
self.assertNotEqual(pet_api.api_client, pet_api2.api_client)
|
||||
|
||||
pet_api.api_client.user_agent = 'api client 3'
|
||||
@@ -156,8 +174,8 @@ class PetApiTests(unittest.TestCase):
|
||||
self.assertNotEqual(pet_api.api_client.user_agent, pet_api2.api_client.user_agent)
|
||||
|
||||
def test_separate_default_config_instances(self):
|
||||
pet_api = petstore_api.PetApi()
|
||||
pet_api2 = petstore_api.PetApi()
|
||||
pet_api = PetApi()
|
||||
pet_api2 = PetApi()
|
||||
self.assertNotEqual(pet_api.api_client.configuration, pet_api2.api_client.configuration)
|
||||
|
||||
pet_api.api_client.configuration.host = 'somehost'
|
||||
@@ -171,7 +189,7 @@ class PetApiTests(unittest.TestCase):
|
||||
|
||||
thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True)
|
||||
result = thread.get()
|
||||
self.assertIsInstance(result, petstore_api.Pet)
|
||||
self.assertIsInstance(result, pet.Pet)
|
||||
|
||||
def test_async_with_result(self):
|
||||
self.pet_api.add_pet(self.pet, async_req=False)
|
||||
@@ -188,16 +206,17 @@ class PetApiTests(unittest.TestCase):
|
||||
def test_async_with_http_info(self):
|
||||
self.pet_api.add_pet(self.pet)
|
||||
|
||||
thread = self.pet_api.get_pet_by_id_with_http_info(self.pet.id, async_req=True)
|
||||
thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True,
|
||||
_return_http_data_only=False)
|
||||
data, status, headers = thread.get()
|
||||
|
||||
self.assertIsInstance(data, petstore_api.Pet)
|
||||
self.assertIsInstance(data, pet.Pet)
|
||||
self.assertEqual(status, 200)
|
||||
|
||||
def test_async_exception(self):
|
||||
self.pet_api.add_pet(self.pet)
|
||||
|
||||
thread = self.pet_api.get_pet_by_id("-9999999999999", async_req=True)
|
||||
thread = self.pet_api.get_pet_by_id(-9999999999999, async_req=True)
|
||||
|
||||
exception = None
|
||||
try:
|
||||
@@ -220,7 +239,10 @@ class PetApiTests(unittest.TestCase):
|
||||
def test_add_pet_and_get_pet_by_id_with_http_info(self):
|
||||
self.pet_api.add_pet(self.pet)
|
||||
|
||||
fetched = self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id)
|
||||
fetched = self.pet_api.get_pet_by_id(
|
||||
pet_id=self.pet.id,
|
||||
_return_http_data_only=False
|
||||
)
|
||||
self.assertIsNotNone(fetched)
|
||||
self.assertEqual(self.pet.id, fetched[0].id)
|
||||
self.assertIsNotNone(fetched[0].category)
|
||||
@@ -267,21 +289,108 @@ class PetApiTests(unittest.TestCase):
|
||||
|
||||
def test_upload_file(self):
|
||||
# upload file with form parameter
|
||||
file_path1 = os.path.join(self.test_file_dir, "1px_pic1.png")
|
||||
file_path2 = os.path.join(self.test_file_dir, "1px_pic2.png")
|
||||
try:
|
||||
file = open(file_path1, "rb")
|
||||
additional_metadata = "special"
|
||||
self.pet_api.upload_file(
|
||||
pet_id=self.pet.id,
|
||||
additional_metadata=additional_metadata,
|
||||
file=self.foo
|
||||
file=file
|
||||
)
|
||||
except ApiException as e:
|
||||
self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
# upload only file
|
||||
# upload only one file
|
||||
try:
|
||||
self.pet_api.upload_file(pet_id=self.pet.id, file=self.foo)
|
||||
file = open(file_path1, "rb")
|
||||
self.pet_api.upload_file(pet_id=self.pet.id, file=file)
|
||||
except ApiException as e:
|
||||
self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
# upload multiple files
|
||||
HTTPResponse = namedtuple(
|
||||
'urllib3_response_HTTPResponse',
|
||||
['status', 'reason', 'data', 'getheaders', 'getheader']
|
||||
)
|
||||
headers = {}
|
||||
def get_headers():
|
||||
return headers
|
||||
def get_header(name, default=None):
|
||||
return headers.get(name, default)
|
||||
api_respponse = {
|
||||
'code': 200,
|
||||
'type': 'blah',
|
||||
'message': 'file upload succeeded'
|
||||
}
|
||||
http_response = HTTPResponse(
|
||||
status=200,
|
||||
reason='OK',
|
||||
data=json.dumps(api_respponse).encode('utf-8'),
|
||||
getheaders=get_headers,
|
||||
getheader=get_header
|
||||
)
|
||||
mock_response = RESTResponse(http_response)
|
||||
try:
|
||||
file1 = open(file_path1, "rb")
|
||||
file2 = open(file_path2, "rb")
|
||||
with patch.object(RESTClientObject, 'request') as mock_method:
|
||||
mock_method.return_value = mock_response
|
||||
res = self.pet_api.upload_file(
|
||||
pet_id=684696917, files=[file1, file2])
|
||||
mock_method.assert_called_with(
|
||||
'POST',
|
||||
'http://localhost/v2/pet/684696917/uploadImage',
|
||||
_preload_content=True,
|
||||
_request_timeout=None,
|
||||
body=None,
|
||||
headers={
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'User-Agent': 'OpenAPI-Generator/1.0.0/python',
|
||||
'Authorization': 'Bearer ACCESS_TOKEN'
|
||||
},
|
||||
post_params=[
|
||||
('files', ('1px_pic1.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')),
|
||||
('files', ('1px_pic2.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png'))
|
||||
],
|
||||
query_params=[]
|
||||
)
|
||||
except ApiException as e:
|
||||
self.fail("upload_file() raised {0} unexpectedly".format(type(e)))
|
||||
finally:
|
||||
file1.close()
|
||||
file2.close()
|
||||
|
||||
# passing in an array of files to when file only allows one
|
||||
# raises an exceptions
|
||||
try:
|
||||
file = open(file_path1, "rb")
|
||||
with self.assertRaises(ApiTypeError) as exc:
|
||||
self.pet_api.upload_file(pet_id=self.pet.id, file=[file])
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
# passing in a single file when an array of file is required
|
||||
# raises an exception
|
||||
try:
|
||||
file = open(file_path1, "rb")
|
||||
with self.assertRaises(ApiTypeError) as exc:
|
||||
self.pet_api.upload_file(pet_id=self.pet.id, files=file)
|
||||
finally:
|
||||
file.close()
|
||||
|
||||
# passing in a closed file raises an exception
|
||||
with self.assertRaises(ApiValueError) as exc:
|
||||
file = open(file_path1, "rb")
|
||||
file.close()
|
||||
self.pet_api.upload_file(pet_id=self.pet.id, file=file)
|
||||
|
||||
|
||||
def test_delete_pet(self):
|
||||
self.pet_api.add_pet(self.pet)
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd petstore_api-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
|
||||
|
||||
class PetModelTests(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.pet = petstore_api.Pet(name="test name", photo_urls=["string"])
|
||||
self.pet.id = 1
|
||||
self.pet.status = "available"
|
||||
cate = petstore_api.Category()
|
||||
cate.id = 1
|
||||
cate.name = "dog"
|
||||
self.pet.category = cate
|
||||
tag = petstore_api.Tag()
|
||||
tag.id = 1
|
||||
self.pet.tags = [tag]
|
||||
|
||||
def test_to_str(self):
|
||||
data = ("{'category': {'id': 1, 'name': 'dog'},\n"
|
||||
" 'id': 1,\n"
|
||||
" 'name': 'test name',\n"
|
||||
" 'photo_urls': ['string'],\n"
|
||||
" 'status': 'available',\n"
|
||||
" 'tags': [{'id': 1, 'name': None}]}")
|
||||
self.assertEqual(data, self.pet.to_str())
|
||||
|
||||
def test_equal(self):
|
||||
self.pet1 = petstore_api.Pet(name="test name", photo_urls=["string"])
|
||||
self.pet1.id = 1
|
||||
self.pet1.status = "available"
|
||||
cate1 = petstore_api.Category()
|
||||
cate1.id = 1
|
||||
cate1.name = "dog"
|
||||
self.pet.category = cate1
|
||||
tag1 = petstore_api.Tag()
|
||||
tag1.id = 1
|
||||
self.pet1.tags = [tag1]
|
||||
|
||||
self.pet2 = petstore_api.Pet(name="test name", photo_urls=["string"])
|
||||
self.pet2.id = 1
|
||||
self.pet2.status = "available"
|
||||
cate2 = petstore_api.Category()
|
||||
cate2.id = 1
|
||||
cate2.name = "dog"
|
||||
self.pet.category = cate2
|
||||
tag2 = petstore_api.Tag()
|
||||
tag2.id = 1
|
||||
self.pet2.tags = [tag2]
|
||||
|
||||
self.assertTrue(self.pet1 == self.pet2)
|
||||
|
||||
# reset pet1 tags to empty array so that object comparison returns false
|
||||
self.pet1.tags = []
|
||||
self.assertFalse(self.pet1 == self.pet2)
|
||||
78
samples/client/petstore/python/tests/test_serialization.py
Normal file
78
samples/client/petstore/python/tests/test_serialization.py
Normal file
@@ -0,0 +1,78 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""
|
||||
Run the tests.
|
||||
$ pip install nose (optional)
|
||||
$ cd OpenAPIPetstore-python
|
||||
$ nosetests -v
|
||||
"""
|
||||
from collections import namedtuple
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
import datetime
|
||||
|
||||
import six
|
||||
|
||||
import petstore_api
|
||||
|
||||
from petstore_api.exceptions import (
|
||||
ApiTypeError,
|
||||
ApiKeyError,
|
||||
ApiValueError,
|
||||
)
|
||||
from petstore_api.model import (
|
||||
enum_test,
|
||||
pet,
|
||||
animal,
|
||||
dog,
|
||||
parent_pet,
|
||||
child_lizard,
|
||||
category,
|
||||
string_enum,
|
||||
string_boolean_map,
|
||||
)
|
||||
from petstore_api.model_utils import (
|
||||
file_type,
|
||||
model_to_dict,
|
||||
)
|
||||
|
||||
from petstore_api.rest import RESTResponse
|
||||
|
||||
MockResponse = namedtuple('MockResponse', 'data')
|
||||
|
||||
class SerializationTests(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.api_client = petstore_api.ApiClient()
|
||||
self.serialize = self.api_client.sanitize_for_serialization
|
||||
|
||||
def test_enum_test(self):
|
||||
""" serialize dict(str, Enum_Test) """
|
||||
value = (
|
||||
string_enum.StringEnum.allowed_values[('value',)]["PLACED"])
|
||||
string_enum_val = string_enum.StringEnum(value)
|
||||
|
||||
source = enum_test.EnumTest(
|
||||
enum_string="UPPER",
|
||||
enum_string_required="lower",
|
||||
enum_integer=1,
|
||||
enum_number=1.1,
|
||||
string_enum=string_enum_val
|
||||
)
|
||||
|
||||
result = {
|
||||
'enum_test': {
|
||||
"enum_string": "UPPER",
|
||||
"enum_string_required": "lower",
|
||||
"enum_integer": 1,
|
||||
"enum_number": 1.1,
|
||||
"stringEnum": "placed"
|
||||
}
|
||||
}
|
||||
serialized = self.serialize({"enum_test": source})
|
||||
|
||||
self.assertEqual(result, serialized)
|
||||
@@ -14,13 +14,13 @@ import time
|
||||
import unittest
|
||||
|
||||
import petstore_api
|
||||
from petstore_api.rest import ApiException
|
||||
from petstore_api.api.store_api import StoreApi
|
||||
|
||||
|
||||
class StoreApiTests(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.store_api = petstore_api.StoreApi()
|
||||
self.store_api = StoreApi()
|
||||
|
||||
def tearDown(self):
|
||||
# sleep 1 sec between two every 2 tests
|
||||
|
||||
Reference in New Issue
Block a user