def setUp(self): self.api = FakeApi() # noqa: E501
class TestFakeApi(unittest.TestCase): """FakeApi unit test stubs""" def setUp(self): self.api = FakeApi() # noqa: E501 def tearDown(self): pass @staticmethod def mock_response(body_value): http_response = HTTPResponse( status=200, reason='OK', data=json.dumps(body_value).encode('utf-8'), getheaders=get_headers, getheader=get_header) return RESTResponse(http_response) @staticmethod def assert_request_called_with(mock_method, url, accept='application/json', http_method='POST', **kwargs): headers = { 'Accept': accept, 'User-Agent': 'OpenAPI-Generator/1.0.0/python', } if 'content_type' in kwargs: headers['Content-Type'] = kwargs['content_type'] used_kwargs = dict(_preload_content=True, _request_timeout=None, headers=headers, query_params=[]) if 'post_params' in kwargs: used_kwargs['post_params'] = kwargs['post_params'] if 'body' in kwargs: used_kwargs['body'] = kwargs['body'] else: mock_method.assert_called_with(http_method, url, **used_kwargs) def test_array_model(self): """Test case for array_model """ from petstore_api.model import animal_farm, animal endpoint = self.api.array_model assert endpoint.openapi_types['body'] == (animal_farm.AnimalFarm, ) assert endpoint.settings['response_type'] == (animal_farm.AnimalFarm, ) # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_method: cat = animal.Animal(class_name="Cat", color="black") body = animal_farm.AnimalFarm([cat]) json_data = [{"className": "Cat", "color": "black"}] mock_method.return_value = self.mock_response(json_data) response = endpoint(body=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', body=json_data) assert isinstance(response, animal_farm.AnimalFarm) assert response == body def test_boolean(self): """Test case for boolean """ endpoint = self.api.boolean assert endpoint.openapi_types['body'] == (bool, ) assert endpoint.settings['response_type'] == (bool, ) def test_recursionlimit(self): """Test case for recursionlimit """ assert sys.getrecursionlimit() == 1234 def test_fake_health_get(self): """Test case for fake_health_get Health check endpoint # noqa: E501 """ pass def test_additional_properties_with_array_of_enums(self): """Test case for additional_properties_with_array_of_enums Additional Properties with Array of Enums # noqa: E501 """ pass def test_enum_test(self): """Test case for enum_test Object contains enum properties and array properties containing enums """ 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 endpoint = self.api.enum_test assert endpoint.openapi_types['enum_test'] == (EnumTest, ) assert endpoint.settings['response_type'] == (EnumTest, ) # serialization + deserialization works w/ inline array with patch.object(RESTClientObject, 'request') as mock_method: body = EnumTest(enum_string_required='lower', inline_array_of_str_enum=[StringEnum('approved')]) json_value = { 'enum_string_required': 'lower', 'InlineArrayOfStrEnum': ['approved'] } mock_method.return_value = self.mock_response(json_value) response = endpoint(enum_test=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', body=json_value) assert isinstance(response, EnumTest) assert response == body # serialization + deserialization works w/ refed array with patch.object(RESTClientObject, 'request') as mock_method: body = EnumTest(enum_string_required='lower', array_of_str_enum=ArrayOfEnums( [StringEnum('approved')])) json_value = { 'enum_string_required': 'lower', 'ArrayOfStrEnum': ['approved'] } mock_method.return_value = self.mock_response(json_value) response = endpoint(enum_test=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', body=json_value) assert isinstance(response, EnumTest) assert response == body def test_array_of_enums(self): """Test case for array_of_enums Array of Enums # noqa: E501 """ from petstore_api.model import array_of_enums, string_enum endpoint = self.api.array_of_enums assert endpoint.openapi_types['array_of_enums'] == ( array_of_enums.ArrayOfEnums, ) assert endpoint.settings['response_type'] == ( array_of_enums.ArrayOfEnums, ) # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_method: value = [string_enum.StringEnum("placed")] body = array_of_enums.ArrayOfEnums(value) value_simple = ["placed"] mock_method.return_value = self.mock_response(value_simple) response = endpoint(array_of_enums=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', body=value_simple) assert isinstance(response, array_of_enums.ArrayOfEnums) assert response.value == value def test_number_with_validations(self): """Test case for number_with_validations """ from petstore_api.model import number_with_validations endpoint = self.api.number_with_validations assert endpoint.openapi_types['body'] == ( number_with_validations.NumberWithValidations, ) assert endpoint.settings['response_type'] == ( number_with_validations.NumberWithValidations, ) # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_method: value = 10.0 body = number_with_validations.NumberWithValidations(value) mock_method.return_value = self.mock_response(value) response = endpoint(body=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/number', body=value) assert isinstance(response, number_with_validations.NumberWithValidations) assert response.value == value def test_object_model_with_ref_props(self): """Test case for object_model_with_ref_props """ from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps from petstore_api.model.number_with_validations import NumberWithValidations endpoint = self.api.object_model_with_ref_props assert endpoint.openapi_types['body'] == (ObjectModelWithRefProps, ) assert endpoint.settings['response_type'] == ( ObjectModelWithRefProps, ) json_payloads = [ {}, # only required + no optional properties works { # optional properties works "my_number": 11.0, "my_string": 'a', "my_boolean": True, } ] # instantiation works expected_models = [ ObjectModelWithRefProps(), ObjectModelWithRefProps(my_number=NumberWithValidations(11.0), my_string='a', my_boolean=True) ] pairs = zip(json_payloads, expected_models) # serialization + deserialization works for (json_payload, expected_model) in pairs: with patch.object(RESTClientObject, 'request') as mock_method: mock_method.return_value = self.mock_response(json_payload) response = endpoint(body=expected_model) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/object_model_with_ref_props', body=json_payload) assert isinstance(response, expected_model.__class__) assert response == expected_model def test_composed_one_of_number_with_validations(self): """Test case for composed_one_of_number_with_validations """ from petstore_api.model import animal, composed_one_of_number_with_validations, number_with_validations endpoint = self.api.composed_one_of_number_with_validations assert endpoint.openapi_types[ 'composed_one_of_number_with_validations'] == ( composed_one_of_number_with_validations. ComposedOneOfNumberWithValidations, ) assert endpoint.settings['response_type'] == ( composed_one_of_number_with_validations. ComposedOneOfNumberWithValidations, ) # serialization + deserialization works num_with_validations = number_with_validations.NumberWithValidations( 10.0) cat_in_composed = composed_one_of_number_with_validations.ComposedOneOfNumberWithValidations( class_name="Cat", color="black") import datetime date = datetime.date(1970, 1, 1) body_value_simple = [ (num_with_validations, 10.0), (cat_in_composed, { "className": "Cat", "color": "black" }), (None, None), (date, '1970-01-01'), ] for (body, value_simple) in body_value_simple: with patch.object(RESTClientObject, 'request') as mock_method: mock_method.return_value = self.mock_response(value_simple) response = endpoint( composed_one_of_number_with_validations=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', body=value_simple) assert isinstance(response, body.__class__) assert response == body def test_string(self): """Test case for string """ endpoint = self.api.string assert endpoint.openapi_types['body'] == (str, ) assert endpoint.settings['response_type'] == (str, ) # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_method: body = "blah" value_simple = body mock_method.return_value = self.mock_response(value_simple) response = endpoint(body=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/string', body=value_simple) assert isinstance(response, str) assert response == value_simple def test_string_enum(self): """Test case for string_enum """ from petstore_api.model import string_enum endpoint = self.api.string_enum assert endpoint.openapi_types['body'] == (string_enum.StringEnum, ) assert endpoint.settings['response_type'] == (string_enum.StringEnum, ) # serialization + deserialization works from petstore_api.rest import RESTClientObject, RESTResponse with patch.object(RESTClientObject, 'request') as mock_method: value = "placed" body = string_enum.StringEnum(value) mock_method.return_value = self.mock_response(value) response = endpoint(body=body) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=value) assert isinstance(response, string_enum.StringEnum) assert response.value == value def test_upload_file(self): # uploads a file test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_path1 = os.path.join(test_file_dir, "1px_pic1.png") 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) file1 = open(file_path1, "rb") try: with patch.object(RESTClientObject, 'request') as mock_method: mock_method.return_value = mock_response res = self.api.upload_file(file=file1) body = None post_params = [ ('file', ('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')), ] self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/uploadFile', body=body, post_params=post_params, content_type='multipart/form-data') except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.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(petstore_api.ApiTypeError) as exc: self.api.upload_file(file=[file]) finally: file.close() # passing in a closed file raises an exception with self.assertRaises(petstore_api.ApiValueError) as exc: file = open(file_path1, "rb") file.close() self.api.upload_file(file=file) def test_upload_files(self): test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_path1 = os.path.join(test_file_dir, "1px_pic1.png") file_path2 = os.path.join(test_file_dir, "1px_pic2.png") 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) file1 = open(file_path1, "rb") file2 = open(file_path2, "rb") try: with patch.object(RESTClientObject, 'request') as mock_method: mock_method.return_value = mock_response res = self.api.upload_files(files=[file1, file2]) 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')) ] self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/uploadFiles', body=None, post_params=post_params, content_type='multipart/form-data') except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() file2.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(petstore_api.ApiTypeError) as exc: self.api.upload_files(files=file) finally: file.close() def test_download_attachment(self): """Ensures that file deserialization works""" # sample from http://www.jtricks.com/download-text file_name = 'content.txt' headers = { 'Content-Disposition': 'attachment; filename={}'.format(file_name), 'Content-Type': 'text/plain' } 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) # deserialize response to a file mock_response = RESTResponse(http_response) with patch.object(RESTClientObject, 'request') as mock_method: mock_method.return_value = mock_response try: file_object = self.api.download_attachment( file_name='download-text') self.assert_request_called_with( mock_method, 'http://www.jtricks.com/download-text', http_method='GET', accept='text/plain', ) self.assertTrue(isinstance(file_object, file_type)) self.assertFalse(file_object.closed) self.assertEqual(file_object.read(), file_data.encode('utf-8')) finally: file_object.close() os.unlink(file_object.name) def test_upload_download_file(self): test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_path1 = os.path.join(test_file_dir, "1px_pic1.png") with open(file_path1, "rb") as f: expected_file_data = f.read() headers = {'Content-Type': 'application/octet-stream'} def get_headers(): return headers def get_header(name, default=None): return headers.get(name, default) http_response = HTTPResponse(status=200, reason='OK', data=expected_file_data, getheaders=get_headers, getheader=get_header) mock_response = RESTResponse(http_response) file1 = open(file_path1, "rb") try: with patch.object(RESTClientObject, 'request') as mock_method: mock_method.return_value = mock_response downloaded_file = self.api.upload_download_file(body=file1) self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=expected_file_data, content_type='application/octet-stream') self.assertTrue(isinstance(downloaded_file, file_type)) self.assertFalse(downloaded_file.closed) self.assertEqual(downloaded_file.read(), expected_file_data) except petstore_api.ApiException as e: self.fail("upload_download_file() raised {0} unexpectedly".format( type(e))) finally: file1.close() downloaded_file.close() os.unlink(downloaded_file.name) def test_test_body_with_file_schema(self): """Test case for test_body_with_file_schema """ pass def test_test_body_with_query_params(self): """Test case for test_body_with_query_params """ pass def test_test_client_model(self): """Test case for test_client_model To test \"client\" model # noqa: E501 """ pass def test_test_endpoint_parameters(self): """Test case for test_endpoint_parameters Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 """ pass def test_test_enum_parameters(self): """Test case for test_enum_parameters To test enum parameters # noqa: E501 """ pass def test_test_group_parameters(self): """Test case for test_group_parameters Fake endpoint to test group parameters (optional) # noqa: E501 """ pass def test_test_inline_additional_properties(self): """Test case for test_inline_additional_properties test inline additionalProperties # noqa: E501 """ pass def test_test_json_form_data(self): """Test case for test_json_form_data test json serialization of form data # noqa: E501 """ pass def test_test_query_parameter_collection_format(self): """Test case for test_query_parameter_collection_format """ pass
class TestFakeApi(unittest.TestCase): """FakeApi unit test stubs""" json_content_type = 'application/json' configuration = petstore_api.Configuration() api = FakeApi(api_client=api_client.ApiClient(configuration=configuration)) @staticmethod def headers_for_content_type(content_type: str) -> 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[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') @staticmethod def __assert_request_called_with( mock_request, url: str, method: str = 'POST', body: typing.Optional[bytes] = None, content_type: typing.Optional[str] = 'application/json', fields: typing.Optional[tuple[api_client.RequestField, ...]] = None, accept_content_type: str = 'application/json', stream: bool = False, query_params: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None): headers = { 'Accept': accept_content_type, 'User-Agent': 'OpenAPI-Generator/1.0.0/python' } if content_type: headers['Content-Type'] = content_type kwargs = dict( headers=HTTPHeaderDict(headers), query_params=query_params, fields=fields, stream=stream, timeout=None, ) if method != 'GET': kwargs['body'] = body mock_request.assert_called_with(method, url, **kwargs) def test_array_model(self): from petstore_api.model import animal_farm, animal # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: json_data = [{"className": "Cat", "color": "black"}] mock_request.return_value = self.__response( self.__json_bytes(json_data)) cat = animal.Animal(className="Cat", color="black") body = animal_farm.AnimalFarm([cat]) api_response = self.api.array_model(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', body=self.__json_bytes(json_data)) assert isinstance(api_response.body, animal_farm.AnimalFarm) assert api_response.body == body def test_recursionlimit(self): """Test case for recursionlimit """ assert sys.getrecursionlimit() == 1234 def test_array_of_enums(self): from petstore_api.model import array_of_enums, string_enum # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: value = [string_enum.StringEnum("placed")] body = array_of_enums.ArrayOfEnums(value) value_simple = ["placed"] mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.array_of_enums(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', body=self.__json_bytes(value_simple)) assert isinstance(api_response.body, array_of_enums.ArrayOfEnums) assert api_response.body == body def test_number_with_validations(self): from petstore_api.model import number_with_validations # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: value = 10.0 body = number_with_validations.NumberWithValidations(value) mock_request.return_value = self.__response( self.__json_bytes(value)) api_response = self.api.number_with_validations(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/number', body=self.__json_bytes(value)) assert isinstance(api_response.body, number_with_validations.NumberWithValidations) assert api_response.body == value def test_composed_one_of_different_types(self): from petstore_api.model import composed_one_of_different_types # serialization + deserialization works number = composed_one_of_different_types.ComposedOneOfDifferentTypes( 10.0) cat = composed_one_of_different_types.ComposedOneOfDifferentTypes( className="Cat", color="black") none_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes( None) date_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes( '1970-01-01') cast_to_simple_value = [ (number, 10.0), (cat, { "className": "Cat", "color": "black" }), (none_instance, None), (date_instance, '1970-01-01'), ] for (body, value_simple) in cast_to_simple_value: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.composed_one_of_different_types( body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', body=self.__json_bytes(value_simple)) assert isinstance( api_response.body, composed_one_of_different_types. ComposedOneOfDifferentTypes) assert api_response.body == body # inputting the uncast values into the endpoint also works for (body, value_simple) in cast_to_simple_value: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.composed_one_of_different_types( body=value_simple) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', body=self.__json_bytes(value_simple)) assert isinstance( api_response.body, composed_one_of_different_types. ComposedOneOfDifferentTypes) assert api_response.body == body def test_string(self): # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: body = "blah" value_simple = body mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.string(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/string', body=self.__json_bytes(value_simple)) assert isinstance(api_response.body, str) assert api_response.body == value_simple def test_string_enum(self): from petstore_api.model import string_enum # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: value = "placed" body = string_enum.StringEnum(value) mock_request.return_value = self.__response( self.__json_bytes(value)) api_response = self.api.string_enum(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=self.__json_bytes(value)) assert isinstance(api_response.body, string_enum.StringEnum) assert api_response.body == value def test_mammal(self): # serialization + deserialization works from petstore_api.model.mammal import Mammal with patch.object(RESTClientObject, 'request') as mock_request: body = Mammal(className="BasquePig") value_simple = dict(className='BasquePig') mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.mammal(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/mammal', body=self.__json_bytes(value_simple)) assert isinstance(api_response.body, Mammal) assert api_response.body == value_simple def test_missing_or_unset_required_body(self): # missing required body with self.assertRaises(TypeError): self.api.mammal() # required body may not be unset with self.assertRaises(petstore_api.ApiValueError): self.api.mammal(body=schemas.unset) def test_missing_or_unset_required_query_parameter(self): from petstore_api.model.user import User user = User({}) # missing required query param with self.assertRaises(petstore_api.ApiTypeError): self.api.body_with_query_params(body=user) # required query param may not be unset with self.assertRaises(petstore_api.ApiValueError): self.api.body_with_query_params( body=schemas.unset, query_params=dict(query=schemas.unset)) def test_upload_download_file_tx_bytes_and_file(self): """Test case for upload_download_file uploads a file and downloads a file using application/octet-stream # noqa: E501 """ import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() file1 = open(file_path1, "rb") mock_response = self.__response( file_bytes, content_type='application/octet-stream') try: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file1) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream') self.assertTrue( isinstance(api_response.body, schemas.BinarySchema)) self.assertTrue( isinstance(api_response.body, schemas.BytesSchema)) self.assertTrue(isinstance(api_response.body, bytes)) self.assertEqual(api_response.body, file_bytes) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() # sending just bytes works also with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file_bytes) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream') self.assertEqual(api_response.body, file_bytes) def test_upload_download_file_rx_file(self): import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() # passing in file1 as the response body simulates a streamed response file1 = open(file_path1, "rb") class StreamableBody: """ This class simulates http.client.HTTPResponse for a streamable response """ def __init__(self, file: io.BufferedReader): self.fp = file def read(self, *args, **kwargs): return self.fp.read(*args, **kwargs) def close(self): self.fp.close() streamable_body = StreamableBody(file1) mock_response = self.__response( streamable_body, content_type='application/octet-stream', preload_content=False) with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file_bytes, stream=True) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream', stream=True) self.assertTrue(file1.closed) self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) self.assertTrue(isinstance(api_response.body, schemas.FileIO)) self.assertEqual(api_response.body.read(), file_bytes) api_response.body.close() os.unlink(api_response.body.name) file1 = open(file_path1, "rb") streamable_body = StreamableBody(file1) saved_file_name = "fileName.abc" """ when streaming is used and the response contains the content disposition header with a filename that filename is used when saving the file locally """ mock_response = self.__response( streamable_body, content_type='application/octet-stream', headers={ 'content-disposition': f'attachment; filename="{saved_file_name}"' }, preload_content=False) with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file_bytes, stream=True) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream', stream=True) self.assertTrue(file1.closed) self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) self.assertTrue(isinstance(api_response.body, schemas.FileIO)) self.assertTrue(api_response.body.name.endswith(saved_file_name)) self.assertEqual(api_response.body.read(), file_bytes) api_response.body.close() os.unlink(api_response.body.name) def test_upload_file(self): """Test case for upload_file uploads a file using multipart/form-data # noqa: E501 """ import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() file1 = open(file_path1, "rb") response_json = { 'code': 200, 'type': 'blah', 'message': 'file upload succeeded' } try: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_file(body={'file': file1}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFile', fields=(api_client.RequestField( name='file', data=file_bytes, filename=file_name, headers={'Content-Type': 'application/octet-stream'}), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() # sending just bytes works also with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_file(body={'file': file_bytes}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFile', fields=(api_client.RequestField( name='file', data=file_bytes, headers={'Content-Type': 'application/octet-stream'}), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json) # passing in an array of files to when file only allows one # raises an exceptions try: file = open(file_path1, "rb") with self.assertRaises(petstore_api.ApiTypeError): self.api.upload_file(body={'file': [file]}) finally: file.close() # passing in a closed file raises an exception with self.assertRaises(ValueError): file = open(file_path1, "rb") file.close() self.api.upload_file(body={'file': file}) def test_upload_files(self): """Test case for upload_files uploads files using multipart/form-data # noqa: E501 """ import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() file1 = open(file_path1, "rb") response_json = { 'code': 200, 'type': 'blah', 'message': 'file upload succeeded' } try: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_files( body={'files': [file1, file1]}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFiles', fields=( api_client.RequestField(name='files', data=file_bytes, filename=file_name, headers={ 'Content-Type': 'application/octet-stream' }), api_client.RequestField(name='files', data=file_bytes, filename=file_name, headers={ 'Content-Type': 'application/octet-stream' }), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() # sending just bytes works also with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_files( body={'files': [file_bytes, file_bytes]}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFiles', fields=( api_client.RequestField( name='files', data=file_bytes, headers={'Content-Type': 'application/octet-stream'}), api_client.RequestField( name='files', data=file_bytes, headers={'Content-Type': 'application/octet-stream'}), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json) @staticmethod def __encode_multipart_formdata( fields: typing.Dict[str, typing.Any]) -> multipart.MIMEMultipart: m = multipart.MIMEMultipart("form-data") for field, value in fields.items(): data = MIMEFormdata(field, "text", "plain") # data.set_payload(value, charset='us-ascii') data.set_payload(value) m.attach(data) return m # comment out below for the time being after adding better inline model support # ref: https://github.com/OpenAPITools/openapi-generator/pull/12104 # #@patch.object(RESTClientObject, 'request') #def test_inline_composition(self, mock_request): # """Test case for inline_composition # testing composed schemas at inline locations # noqa: E501 # """ # single_char_str = 'a' # json_bytes = self.__json_bytes(single_char_str) # # tx and rx json with composition at root level of schema for request + response body # content_type = 'application/json' # mock_request.return_value = self.__response( # json_bytes # ) # api_response = self.api.inline_composition( # body=single_char_str, # query_params={ # 'compositionAtRoot': single_char_str, # 'compositionInProperty': {'someProp': single_char_str} # }, # accept_content_types=(content_type,) # ) # self.__assert_request_called_with( # mock_request, # 'http://petstore.swagger.io:80/v2/fake/inlineComposition/', # accept_content_type=content_type, # content_type=content_type, # query_params=(('compositionAtRoot', 'a'), ('someProp', 'a')), # body=json_bytes # ) # self.assertEqual(api_response.body, single_char_str) # self.assertTrue(isinstance(api_response.body, schemas.StrSchema)) # # tx and rx json with composition at property level of schema for request + response body # content_type = 'multipart/form-data' # multipart_response = self.__encode_multipart_formdata(fields={'someProp': single_char_str}) # mock_request.return_value = self.__response( # bytes(multipart_response), # content_type=multipart_response.get_content_type() # ) # api_response = self.api.inline_composition( # body={'someProp': single_char_str}, # query_params={ # 'compositionAtRoot': single_char_str, # 'compositionInProperty': {'someProp': single_char_str} # }, # content_type=content_type, # accept_content_types=(content_type,) # ) # self.__assert_request_called_with( # mock_request, # 'http://petstore.swagger.io:80/v2/fake/inlineComposition/', # accept_content_type=content_type, # content_type=content_type, # query_params=(('compositionAtRoot', 'a'), ('someProp', 'a')), # fields=( # api_client.RequestField( # name='someProp', # data=single_char_str, # headers={'Content-Type': 'text/plain'} # ), # ), # ) # self.assertEqual(api_response.body, {'someProp': single_char_str}) # self.assertTrue(isinstance(api_response.body.someProp, schemas.StrSchema)) # # error thrown when a str is input which doesn't meet the composed schema length constraint # invalid_value = '' # variable_locations = 4 # for invalid_index in range(variable_locations): # values = [single_char_str]*variable_locations # values[invalid_index] = invalid_value # with self.assertRaises(exceptions.ApiValueError): # multipart_response = self.__encode_multipart_formdata(fields={'someProp': values[0]}) # mock_request.return_value = self.__response( # bytes(multipart_response), # content_type=multipart_response.get_content_type() # ) # self.api.inline_composition( # body={'someProp': values[1]}, # query_params={ # 'compositionAtRoot': values[2], # 'compositionInProperty': {'someProp': values[3]} # }, # content_type=content_type, # accept_content_types=(content_type,) # ) def test_json_with_charset(self): # serialization + deserialization of json with charset works with patch.object(RESTClientObject, 'request') as mock_request: body = None content_type_with_charset = 'application/json; charset=utf-8' mock_request.return_value = self.__response( self.__json_bytes(body), content_type=content_type_with_charset) api_response = self.api.json_with_charset(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/jsonWithCharset', body=self.__json_bytes(body), content_type=content_type_with_charset, accept_content_type=content_type_with_charset) assert isinstance(api_response.body, schemas.AnyTypeSchema) assert isinstance(api_response.body, schemas.NoneClass) assert api_response.body.is_none() def test_response_without_schema(self): # received response is not loaded into body because there is no deserialization schema defined with patch.object(RESTClientObject, 'request') as mock_request: body = None content_type = 'application/json' mock_request.return_value = self.__response( self.__json_bytes(body), ) api_response = self.api.response_without_schema() self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/responseWithoutSchema', method='GET', accept_content_type='application/json, application/xml', content_type=None) assert isinstance(api_response.body, schemas.Unset) with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( 'blah', content_type='text/plain') # when an incorrect content-type is sent back, and exception is raised with self.assertRaises(exceptions.ApiValueError): self.api.response_without_schema()
class TestFakeApi(unittest.TestCase): """FakeApi unit test stubs""" def setUp(self): self.api = FakeApi() # noqa: E501 def tearDown(self): pass def test_create_xml_item(self): """Test case for create_xml_item creates an XmlItem # noqa: E501 """ pass def test_boolean(self): """Test case for boolean """ endpoint = self.api.boolean_endpoint assert endpoint.openapi_types['body'] == (bool, ) assert endpoint.settings['response_type'] == (bool, ) def test_string(self): """Test case for string """ endpoint = self.api.string_endpoint assert endpoint.openapi_types['body'] == (str, ) assert endpoint.settings['response_type'] == (str, ) def test_object_model_with_ref_props(self): """Test case for object_model_with_ref_props """ from petstore_api.model import object_model_with_ref_props endpoint = self.api.object_model_with_ref_props_endpoint assert endpoint.openapi_types['body'] == ( object_model_with_ref_props.ObjectModelWithRefProps, ) assert endpoint.settings['response_type'] == ( object_model_with_ref_props.ObjectModelWithRefProps, ) def test_string_enum(self): """Test case for string_enum """ from petstore_api.model import string_enum endpoint = self.api.string_enum_endpoint assert endpoint.openapi_types['body'] == (string_enum.StringEnum, ) assert endpoint.settings['response_type'] == (string_enum.StringEnum, ) def test_array_model(self): """Test case for array_model """ from petstore_api.model import animal_farm endpoint = self.api.array_model_endpoint assert endpoint.openapi_types['body'] == (animal_farm.AnimalFarm, ) assert endpoint.settings['response_type'] == (animal_farm.AnimalFarm, ) def test_number_with_validations(self): """Test case for number_with_validations """ from petstore_api.model import number_with_validations endpoint = self.api.number_with_validations_endpoint assert endpoint.openapi_types['body'] == ( number_with_validations.NumberWithValidations, ) assert endpoint.settings['response_type'] == ( number_with_validations.NumberWithValidations, ) def test_test_body_with_file_schema(self): """Test case for test_body_with_file_schema """ pass def test_test_body_with_query_params(self): """Test case for test_body_with_query_params """ pass def test_test_client_model(self): """Test case for test_client_model To test \"client\" model # noqa: E501 """ pass def test_test_endpoint_enums_length_one(self): """Test case for test_endpoint_enums_length_one """ # when we omit the required enums of length one, they are still set endpoint = self.api.test_endpoint_enums_length_one_endpoint import six if six.PY3: from unittest.mock import patch else: from mock import patch with patch.object(endpoint, 'call_with_http_info') as call_with_http_info: self.api.test_endpoint_enums_length_one() call_with_http_info.assert_called_with(_check_input_type=True, _check_return_type=True, _host_index=None, _preload_content=True, _request_timeout=None, _return_http_data_only=True, async_req=False, header_number=1.234, path_integer=34, path_string='hello', query_integer=3, query_string='brillig') def test_test_endpoint_parameters(self): """Test case for test_endpoint_parameters Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 """ # check that we can access the endpoint's validations endpoint = self.api.test_endpoint_parameters_endpoint assert endpoint.validations[('number', )] == { 'inclusive_maximum': 543.2, 'inclusive_minimum': 32.1, } # make sure that an exception is thrown on an invalid value keyword_args = dict( number=544, # invalid double=100, pattern_without_delimiter="abc", byte='sample string') with self.assertRaises(petstore_api.ApiValueError): self.api.test_endpoint_parameters(**keyword_args) def test_test_enum_parameters(self): """Test case for test_enum_parameters To test enum parameters # noqa: E501 """ # check that we can access the endpoint's allowed_values endpoint = self.api.test_enum_parameters_endpoint assert endpoint.allowed_values[('enum_query_string', )] == { "_ABC": "_abc", "-EFG": "-efg", "(XYZ)": "(xyz)" } # make sure that an exception is thrown on an invalid value keyword_args = dict(enum_query_string="bad value") with self.assertRaises(petstore_api.ApiValueError): self.api.test_enum_parameters(**keyword_args) def test_test_group_parameters(self): """Test case for test_group_parameters Fake endpoint to test group parameters (optional) # noqa: E501 """ pass def test_test_inline_additional_properties(self): """Test case for test_inline_additional_properties test inline additionalProperties # noqa: E501 """ pass def test_test_json_form_data(self): """Test case for test_json_form_data test json serialization of form data # noqa: E501 """ pass
class TestFakeApi(unittest.TestCase): """FakeApi unit test stubs""" json_content_type = 'application/json' configuration = petstore_api.Configuration() api = FakeApi(api_client=api_client.ApiClient(configuration=configuration)) @staticmethod def headers_for_content_type(content_type: str) -> 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[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') @staticmethod def __assert_request_called_with( mock_request, url: str, body: typing.Optional[bytes] = None, content_type: str = 'application/json', fields: typing.Optional[tuple[api_client.RequestField, ...]] = None, accept_content_type: str = 'application/json', stream: bool = False, ): mock_request.assert_called_with( 'POST', url, headers=HTTPHeaderDict({ 'Accept': accept_content_type, 'Content-Type': content_type, 'User-Agent': 'OpenAPI-Generator/1.0.0/python' }), body=body, query_params=None, fields=fields, stream=stream, timeout=None, ) def test_array_model(self): from petstore_api.model import animal_farm, animal # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: json_data = [{"className": "Cat", "color": "black"}] mock_request.return_value = self.__response( self.__json_bytes(json_data)) cat = animal.Animal(className="Cat", color="black") body = animal_farm.AnimalFarm([cat]) api_response = self.api.array_model(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', body=self.__json_bytes(json_data)) assert isinstance(api_response.body, animal_farm.AnimalFarm) assert api_response.body == body def test_recursionlimit(self): """Test case for recursionlimit """ assert sys.getrecursionlimit() == 1234 def test_array_of_enums(self): from petstore_api.model import array_of_enums, string_enum # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: value = [string_enum.StringEnum("placed")] body = array_of_enums.ArrayOfEnums(value) value_simple = ["placed"] mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.array_of_enums(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', body=self.__json_bytes(value_simple)) assert isinstance(api_response.body, array_of_enums.ArrayOfEnums) assert api_response.body == body def test_number_with_validations(self): from petstore_api.model import number_with_validations # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: value = 10.0 body = number_with_validations.NumberWithValidations(value) mock_request.return_value = self.__response( self.__json_bytes(value)) api_response = self.api.number_with_validations(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/number', body=self.__json_bytes(value)) assert isinstance(api_response.body, number_with_validations.NumberWithValidations) assert api_response.body == value def test_composed_one_of_different_types(self): from petstore_api.model import composed_one_of_different_types # serialization + deserialization works number = composed_one_of_different_types.ComposedOneOfDifferentTypes( 10.0) cat = composed_one_of_different_types.ComposedOneOfDifferentTypes( className="Cat", color="black") none_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes( None) date_instance = composed_one_of_different_types.ComposedOneOfDifferentTypes( '1970-01-01') cast_to_simple_value = [ (number, 10.0), (cat, { "className": "Cat", "color": "black" }), (none_instance, None), (date_instance, '1970-01-01'), ] for (body, value_simple) in cast_to_simple_value: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.composed_one_of_different_types( body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', body=self.__json_bytes(value_simple)) assert isinstance( api_response.body, composed_one_of_different_types. ComposedOneOfDifferentTypes) assert api_response.body == body # inputting the uncast values into the endpoint also works for (body, value_simple) in cast_to_simple_value: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.composed_one_of_different_types( body=value_simple) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', body=self.__json_bytes(value_simple)) assert isinstance( api_response.body, composed_one_of_different_types. ComposedOneOfDifferentTypes) assert api_response.body == body def test_string(self): # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: body = "blah" value_simple = body mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.string(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/string', body=self.__json_bytes(value_simple)) assert isinstance(api_response.body, str) assert api_response.body == value_simple def test_string_enum(self): from petstore_api.model import string_enum # serialization + deserialization works with patch.object(RESTClientObject, 'request') as mock_request: value = "placed" body = string_enum.StringEnum(value) mock_request.return_value = self.__response( self.__json_bytes(value)) api_response = self.api.string_enum(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=self.__json_bytes(value)) assert isinstance(api_response.body, string_enum.StringEnum) assert api_response.body == value def test_mammal(self): # serialization + deserialization works from petstore_api.model.mammal import Mammal with patch.object(RESTClientObject, 'request') as mock_request: body = Mammal(className="BasquePig") value_simple = dict(className='BasquePig') mock_request.return_value = self.__response( self.__json_bytes(value_simple)) api_response = self.api.mammal(body=body) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/refs/mammal', body=self.__json_bytes(value_simple)) assert isinstance(api_response.body, Mammal) assert api_response.body == value_simple def test_missing_or_unset_required_body(self): # missing required body with self.assertRaises(TypeError): self.api.mammal() # required body may not be unset with self.assertRaises(petstore_api.ApiValueError): self.api.mammal(body=schemas.unset) def test_missing_or_unset_required_query_parameter(self): from petstore_api.model.user import User user = User({}) # missing required query param with self.assertRaises(petstore_api.ApiTypeError): self.api.body_with_query_params(body=user) # required query param may not be unset with self.assertRaises(petstore_api.ApiValueError): self.api.body_with_query_params( body=schemas.unset, query_params=dict(query=schemas.unset)) def test_upload_download_file_tx_bytes_and_file(self): """Test case for upload_download_file uploads a file and downloads a file using application/octet-stream # noqa: E501 """ import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() file1 = open(file_path1, "rb") mock_response = self.__response( file_bytes, content_type='application/octet-stream') try: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file1) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream') self.assertTrue( isinstance(api_response.body, schemas.BinarySchema)) self.assertTrue( isinstance(api_response.body, schemas.BytesSchema)) self.assertTrue(isinstance(api_response.body, bytes)) self.assertEqual(api_response.body, file_bytes) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() # sending just bytes works also with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file_bytes) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream') self.assertEqual(api_response.body, file_bytes) def test_upload_download_file_rx_file(self): import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() # passing in file1 as the response body simulates a streamed response file1 = open(file_path1, "rb") class StreamableBody: """ This class simulates http.client.HTTPResponse for a streamable response """ def __init__(self, file: io.BufferedReader): self.fp = file def read(self, *args, **kwargs): return self.fp.read(*args, **kwargs) def close(self): self.fp.close() streamable_body = StreamableBody(file1) mock_response = self.__response( streamable_body, content_type='application/octet-stream', preload_content=False) with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file_bytes, stream=True) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream', stream=True) self.assertTrue(file1.closed) self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) self.assertTrue(isinstance(api_response.body, schemas.FileIO)) self.assertEqual(api_response.body.read(), file_bytes) api_response.body.close() os.unlink(api_response.body.name) file1 = open(file_path1, "rb") streamable_body = StreamableBody(file1) saved_file_name = "fileName.abc" """ when streaming is used and the response contains the content disposition header with a filename that filename is used when saving the file locally """ mock_response = self.__response( streamable_body, content_type='application/octet-stream', headers={ 'content-disposition': f'attachment; filename="{saved_file_name}"' }, preload_content=False) with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = mock_response api_response = self.api.upload_download_file(body=file_bytes, stream=True) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', body=file_bytes, content_type='application/octet-stream', accept_content_type='application/octet-stream', stream=True) self.assertTrue(file1.closed) self.assertTrue(isinstance(api_response.body, schemas.BinarySchema)) self.assertTrue(isinstance(api_response.body, schemas.FileSchema)) self.assertTrue(isinstance(api_response.body, schemas.FileIO)) self.assertTrue(api_response.body.name.endswith(saved_file_name)) self.assertEqual(api_response.body.read(), file_bytes) api_response.body.close() os.unlink(api_response.body.name) def test_upload_file(self): """Test case for upload_file uploads a file using multipart/form-data # noqa: E501 """ import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() file1 = open(file_path1, "rb") response_json = { 'code': 200, 'type': 'blah', 'message': 'file upload succeeded' } try: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_file(body={'file': file1}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFile', fields=(api_client.RequestField( name='file', data=file_bytes, filename=file_name, headers={'Content-Type': 'application/octet-stream'}), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() # sending just bytes works also with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_file(body={'file': file_bytes}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFile', fields=(api_client.RequestField( name='file', data=file_bytes, headers={'Content-Type': 'application/octet-stream'}), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json) # passing in an array of files to when file only allows one # raises an exceptions try: file = open(file_path1, "rb") with self.assertRaises(petstore_api.ApiTypeError): self.api.upload_file(body={'file': [file]}) finally: file.close() # passing in a closed file raises an exception with self.assertRaises(ValueError): file = open(file_path1, "rb") file.close() self.api.upload_file(body={'file': file}) def test_upload_files(self): """Test case for upload_files uploads files using multipart/form-data # noqa: E501 """ import os test_file_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "testfiles")) file_name = '1px_pic1.png' file_path1 = os.path.join(test_file_dir, file_name) with open(file_path1, "rb") as some_file: file_bytes = some_file.read() file1 = open(file_path1, "rb") response_json = { 'code': 200, 'type': 'blah', 'message': 'file upload succeeded' } try: with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_files( body={'files': [file1, file1]}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFiles', fields=( api_client.RequestField(name='files', data=file_bytes, filename=file_name, headers={ 'Content-Type': 'application/octet-stream' }), api_client.RequestField(name='files', data=file_bytes, filename=file_name, headers={ 'Content-Type': 'application/octet-stream' }), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json) except petstore_api.ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) finally: file1.close() # sending just bytes works also with patch.object(RESTClientObject, 'request') as mock_request: mock_request.return_value = self.__response( self.__json_bytes(response_json)) api_response = self.api.upload_files( body={'files': [file_bytes, file_bytes]}) self.__assert_request_called_with( mock_request, 'http://petstore.swagger.io:80/v2/fake/uploadFiles', fields=( api_client.RequestField( name='files', data=file_bytes, headers={'Content-Type': 'application/octet-stream'}), api_client.RequestField( name='files', data=file_bytes, headers={'Content-Type': 'application/octet-stream'}), ), content_type='multipart/form-data') self.assertEqual(api_response.body, response_json)