def test_multiple_of_deserialization(self):
        data = {
            'byte': '3',
            'date': '1970-01-01',
            'password': "******",
            'integer': 30,
            'number': 65.0,
            'float': 62.4,
        }
        response = MockResponse(data=json.dumps(data))
        deserialized = self.api_client.deserialize(response, (format_test.FormatTest,), True)
        self.assertTrue(isinstance(deserialized, format_test.FormatTest))

        with self.checkRaiseRegex(petstore_api.exceptions.ApiValueError, "Invalid value for `integer`, value must be a multiple of `2`"):
          data = {
              'byte': '3',
              'date': '1970-01-01',
              'password': "******",
              'integer': 31,  # Value is supposed to be multiple of '2'. An error must be raised
              'number': 65.0,
              'float': 62.4,
          }
          response = MockResponse(data=json.dumps(data))
          deserialized = self.api_client.deserialize(response, (format_test.FormatTest,), True)

        # Disable JSON schema validation. No error should be raised during deserialization.
        config = petstore_api.Configuration()
        config.disabled_client_side_validations = "multipleOf"
        api_client = petstore_api.ApiClient(configuration=config)

        data = {
            'byte': '3',
            'date': '1970-01-01',
            'password': "******",
            'integer': 31, # Value is supposed to be multiple of '2'
            'number': 65.0,
            'float': 62.4,
        }
        response = MockResponse(data=json.dumps(data))
        deserialized = api_client.deserialize(response, (format_test.FormatTest,), True)
        self.assertTrue(isinstance(deserialized, format_test.FormatTest))

        # Disable JSON schema validation but for a different keyword.
        # An error should be raised during deserialization.
        config = petstore_api.Configuration()
        config.disabled_client_side_validations = "maxItems"
        api_client = petstore_api.ApiClient(configuration=config)

        with self.checkRaiseRegex(petstore_api.exceptions.ApiValueError, "Invalid value for `integer`, value must be a multiple of `2`"):
            data = {
                'byte': '3',
                'date': '1970-01-01',
                'password': "******",
                'integer': 31, # Value is supposed to be multiple of '2'
                'number': 65.0,
                'float': 62.4,
            }
            response = MockResponse(data=json.dumps(data))
            deserialized = api_client.deserialize(response, (format_test.FormatTest,), True)
Пример #2
0
    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'
        config.username = '******'
        config.password = '******'

        header_params = {'test1': 'value1'}
        query_params = {'test2': 'value2'}
        auth_settings = ['api_key', 'unknown']

        client = petstore_api.ApiClient(config)

        # test prefix
        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)

        # test api key auth
        self.assertEqual(header_params['test1'], 'value1')
        self.assertEqual(header_params['api_key'], 'PREFIX 123456')
        self.assertEqual(query_params['test2'], 'value2')

        # test basic auth
        self.assertEqual('test_username', client.configuration.username)
        self.assertEqual('test_password', client.configuration.password)
    def test_configuration(self):
        config = petstore_api.Configuration()
        config.host = 'http://localhost/'

        config.disabled_client_side_validations = ("multipleOf,maximum,exclusiveMaximum,minimum,exclusiveMinimum,"
            "maxLength,minLength,pattern,maxItems,minItems")
        with self.checkRaiseRegex(ValueError, "Invalid keyword: 'foo'"):
            config.disabled_client_side_validations = 'foo'
        config.disabled_client_side_validations = ""
Пример #4
0
    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'
        config.username = '******'
        config.password = '******'

        header_params = {'test1': 'value1'}
        query_params = {'test2': 'value2'}
        auth_settings = ['api_key', 'unknown']

        client = petstore_api.ApiClient(config)

        # test prefix
        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)

        # test api key auth
        self.assertEqual(header_params['test1'], 'value1')
        self.assertEqual(header_params['api_key'], 'PREFIX 123456')
        self.assertEqual(query_params['test2'], 'value2')

        # test basic auth
        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)
        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)
        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)
        self.assertEqual(header_params['api_key'], 'PREFIX=123456')
    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))
Пример #6
0
    def test_socket_options_get_passed_to_pool_manager(self):

        socket_options = ["extra", "socket", "options"]

        config = petstore_api.Configuration(host="HOST")
        config.socket_options = socket_options

        with patch("petstore_api.rest.urllib3.PoolManager", StubPoolManager):
            api_client = petstore_api.ApiClient(config)

        # urllib3.PoolManager promises to pass socket_options in kwargs
        # to the underlying socket. So asserting that our manager
        # gets it is a good start
        assert api_client.rest_client.pool_manager.actual_kwargs[
            "socket_options"] == socket_options
    def test_servers(self):
        config = petstore_api.Configuration(server_index=1, server_variables={'version': 'v1'})
        api_client = petstore_api.ApiClient(config)
        api = pet_api.PetApi(api_client)

        def request(expected_url, method, url, **kwargs):
            assert expected_url == url
            raise RuntimeError('pass')

        api_client.request = functools.partial(request, 'http://path-server-test.petstore.local/v2/pet')
        try:
            api.add_pet({'name': 'pet', 'photo_urls': []})
        except RuntimeError as e:
            assert "pass" == str(e)

        api_client.request = functools.partial(request, 'https://localhost:8080/v1/pet/123456789')
        try:
            api.delete_pet(123456789)
        except RuntimeError as e:
            assert "pass" == str(e)
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()
Пример #9
0
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)
    def test_multiple_of_deserialization(self):
        data = {
            'byte': '3',
            'date': '1970-01-01',
            'password': "******",
            'integer': 30,
            'number': 65.0,
            'float': 62.4,
        }
        from petstore_api.model import format_test
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=format_test.FormatTest),
        }, )
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        self.assertTrue(isinstance(deserialized.body, format_test.FormatTest))

        with self.assertRaisesRegex(
                petstore_api.exceptions.ApiValueError,
                r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)"
        ):
            data = {
                'byte': '3',
                'date': '1970-01-01',
                'password': "******",
                'integer':
                31,  # Value is supposed to be multiple of '2'. An error must be raised
                'number': 65.0,
                'float': 62.4,
            }
            response = self.__response(data)
            _response_for_200.deserialize(response, self.configuration)

        # Disable JSON schema validation. No error should be raised during deserialization.
        configuration = petstore_api.Configuration()
        configuration.disabled_client_side_validations = "multipleOf"

        data = {
            'byte': '3',
            'date': '1970-01-01',
            'password': "******",
            'integer': 31,  # Value is supposed to be multiple of '2'
            'number': 65.0,
            'float': 62.4,
        }
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response, configuration)
        self.assertTrue(isinstance(deserialized.body, format_test.FormatTest))

        # Disable JSON schema validation but for a different keyword.
        # An error should be raised during deserialization.
        configuration = petstore_api.Configuration()
        configuration.disabled_client_side_validations = "maxItems"

        with self.assertRaisesRegex(
                petstore_api.exceptions.ApiValueError,
                r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)"
        ):
            data = {
                'byte': '3',
                'date': '1970-01-01',
                'password': "******",
                'integer': 31,  # Value is supposed to be multiple of '2'
                'number': 65.0,
                'float': 62.4,
            }
            response = self.__response(data)
            _response_for_200.deserialize(response, configuration)
class DeserializationTests(unittest.TestCase):
    json_content_type = 'application/json'
    json_content_type_headers = {'content-type': json_content_type}
    configuration = petstore_api.Configuration()

    @classmethod
    def __response(cls, data: typing.Any) -> urllib3.HTTPResponse:
        return urllib3.HTTPResponse(json.dumps(data).encode('utf-8'),
                                    headers=cls.json_content_type_headers)

    def test_deserialize_shape(self):
        """

        deserialize Shape to an instance of:
        - EquilateralTriangle
        - IsoscelesTriangle
        - IsoscelesTriangle
        - ScaleneTriangle
        - ComplexQuadrilateral
        - SimpleQuadrilateral
        by traveling through 2 discriminators
        """
        from petstore_api.model import shape, equilateral_triangle
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=shape.Shape),
        }, )
        data = {
            'shapeType': 'Triangle',
            'triangleType': 'EquilateralTriangle',
        }
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(
            isinstance(body, equilateral_triangle.EquilateralTriangle))
        self.assertEqual(body.shapeType, 'Triangle')
        self.assertEqual(body.triangleType, 'EquilateralTriangle')

        # invalid quadrilateralType, second discriminator value
        data = {
            'shapeType': 'Quadrilateral',
            'quadrilateralType': 'Triangle',
        }
        response = self.__response(data)

        err_msg = (
            r"Invalid discriminator value was passed in to Quadrilateral.quadrilateralType Only the values "
            r"\['ComplexQuadrilateral', 'SimpleQuadrilateral'\] are allowed at \('args\[0\]', 'quadrilateralType'\)"
        )
        with self.assertRaisesRegex(petstore_api.ApiValueError, err_msg):
            _response_for_200.deserialize(response, self.configuration)

    def test_deserialize_animal(self):
        """
        deserialize Animal to a Dog instance
        Animal uses a discriminator which has a map built of child classes
        that inherrit from Animal
        This is the swagger (v2) way of doing something like oneOf composition
        """
        from petstore_api.model import animal, dog
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=animal.Animal),
        }, )
        data = {
            'className': 'Dog',
            'color': 'white',
            'breed': 'Jack Russel Terrier'
        }
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(isinstance(body, dog.Dog))
        self.assertEqual(body.className, 'Dog')
        self.assertEqual(body.color, 'white')
        self.assertEqual(body.breed, 'Jack Russel Terrier')

    def test_regex_constraint(self):
        """
        Test regex pattern validation.
        """
        from petstore_api.model import apple

        # Test with valid regex pattern.
        inst = apple.Apple(cultivar="Akane")
        assert isinstance(inst, apple.Apple)

        inst = apple.Apple(cultivar="Golden Delicious", origin="cHiLe")
        assert isinstance(inst, apple.Apple)

        # Test with invalid regex pattern.
        err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'cultivar'\)"
        with self.assertRaisesRegex(petstore_api.ApiValueError, err_regex):
            inst = apple.Apple(cultivar="!@#%@$#Akane")

        err_regex = r"Invalid value `.+?`, must match regular expression `.+?` at \('args\[0\]', 'origin'\)"
        with self.assertRaisesRegex(petstore_api.ApiValueError, err_regex):
            inst = apple.Apple(cultivar="Golden Delicious",
                               origin="!@#%@$#Chile")

    def test_deserialize_mammal(self):
        """
        deserialize mammal
        mammal is a oneOf composed schema model with discriminator
        """

        # whale test
        from petstore_api.model import mammal, zebra, whale
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=mammal.Mammal),
        }, )
        has_baleen = True
        has_teeth = False
        class_name = 'whale'
        data = {
            'hasBaleen': has_baleen,
            'hasTeeth': has_teeth,
            'className': class_name
        }
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(isinstance(body, whale.Whale))
        self.assertEqual(bool(body.hasBaleen), has_baleen)
        self.assertEqual(bool(body.hasTeeth), has_teeth)
        self.assertEqual(body.className, class_name)

        # zebra test
        zebra_type = 'plains'
        class_name = 'zebra'
        data = {'type': zebra_type, 'className': class_name}
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(isinstance(body, zebra.Zebra))
        self.assertEqual(body.type, zebra_type)
        self.assertEqual(body.className, class_name)

    def test_deserialize_float_value(self):
        """
        Deserialize floating point values.
        """
        from petstore_api.model import banana
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=banana.Banana),
        }, )
        data = {'lengthCm': 3.1415}
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(isinstance(body, banana.Banana))
        self.assertTrue(isinstance(body.lengthCm, Decimal))
        self.assertEqual(body.lengthCm, 3.1415)
        """
        Float value is serialized without decimal point
        The client receive it as an integer, which work because Banana.lengthCm is type number without format
        Which accepts int AND float
        """
        data = {'lengthCm': 3}
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(isinstance(body, banana.Banana))
        self.assertTrue(isinstance(body.lengthCm, Decimal))
        self.assertEqual(body.lengthCm, 3)

    def test_deserialize_fruit_null_value(self):
        """
        deserialize fruit with null value.
        fruitReq is a oneOf composed schema model with discriminator, including 'null' type.
        """
        from petstore_api.model import fruit_req
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=fruit_req.FruitReq),
        }, )
        data = None
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        self.assertTrue(isinstance(deserialized.body, fruit_req.FruitReq))
        self.assertTrue(isinstance(deserialized.body, NoneClass))

    def test_deserialize_with_additional_properties(self):
        """
        Deserialize data with schemas that have the additionalProperties keyword.
        Test conditions when additional properties are allowed, not allowed, have
        specific types...
        """

        # Dog is allOf with two child schemas.
        # The OAS document for Dog does not specify the 'additionalProperties' keyword,
        # which means that by default, the Dog schema must allow undeclared properties.
        # The additionalProperties keyword is used to control the handling of extra stuff,
        # that is, properties whose names are not listed in the properties keyword.
        # By default any additional properties are allowed.
        from petstore_api.model import dog, mammal, zebra, banana_req
        data = {
            'className': 'Dog',
            'color': 'brown',
            'breed': 'golden retriever',
            # Below are additional, undeclared properties.
            'group': 'Terrier Group',
            'size': 'medium',
        }
        response = self.__response(data)
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=dog.Dog),
        }, )
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(isinstance(body, dog.Dog))
        self.assertEqual(body.className, 'Dog')
        self.assertEqual(body.color, 'brown')
        self.assertEqual(body.breed, 'golden retriever')
        self.assertEqual(body.group, 'Terrier Group')
        self.assertEqual(body.size, 'medium')

        # The 'zebra' schema allows additional properties by explicitly setting
        # additionalProperties: true.
        # This is equivalent to 'additionalProperties' not being present.
        data = {
            'className': 'zebra',
            'type': 'plains',
            # Below are additional, undeclared properties
            'group': 'abc',
            'size': 3,
            'p1': True,
            'p2': ['a', 'b', 123],
        }
        response = self.__response(data)
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=mammal.Mammal),
        }, )
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        body = deserialized.body
        self.assertTrue(isinstance(body, zebra.Zebra))
        self.assertEqual(body.className, 'zebra')
        self.assertEqual(body.type, 'plains')
        self.assertEqual(bool(body.p1), True)

        # The 'bananaReq' schema disallows additional properties by explicitly setting
        # additionalProperties: false
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=banana_req.BananaReq),
        }, )
        with self.assertRaisesRegex(
                petstore_api.exceptions.ApiTypeError,
                r"BananaReq was passed 1 invalid argument: \['unknown-group'\]"
        ):
            data = {
                'lengthCm': 21.2,
                'sweet': False,
                # Below are additional, undeclared properties. They are not allowed,
                # an exception must be raised.
                'unknown-group': 'abc',
            }
            response = self.__response(data)
            _response_for_200.deserialize(response, self.configuration)

    def test_deserialize_with_additional_properties_and_reference(self):
        """
        Deserialize data with schemas that has the additionalProperties keyword
        and the schema is specified as a reference ($ref).
        """
        from petstore_api.model import drawing
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=drawing.Drawing),
        }, )
        data = {
            'mainShape': {
                'shapeType': 'Triangle',
                'triangleType': 'EquilateralTriangle',
            },
            'shapes': [
                {
                    'shapeType': 'Triangle',
                    'triangleType': 'IsoscelesTriangle',
                },
                {
                    'shapeType': 'Quadrilateral',
                    'quadrilateralType': 'ComplexQuadrilateral',
                },
            ],
            'an_additional_prop': {
                'lengthCm': 4,
                'color': 'yellow'
            }
        }
        response = self.__response(data)
        _response_for_200.deserialize(response, self.configuration)

    def test_deserialize_NumberWithValidations(self):
        from petstore_api.model.number_with_validations import NumberWithValidations
        from petstore_api.api.fake_api_endpoints.number_with_validations import _response_for_200

        # make sure that an exception is thrown on an invalid type value
        with self.assertRaises(petstore_api.ApiTypeError):
            response = self.__response('test str')
            _response_for_200.deserialize(response, self.configuration)

        # make sure that an exception is thrown on an invalid value
        with self.assertRaises(petstore_api.ApiValueError):
            response = self.__response(21.0)
            _response_for_200.deserialize(response, self.configuration)

        # valid value works
        number_val = 11.0
        response = self.__response(number_val)
        response = _response_for_200.deserialize(response, self.configuration)
        self.assertTrue(isinstance(response.body, NumberWithValidations))
        self.assertEqual(response.body, number_val)

    def test_array_of_enums(self):
        from petstore_api.model.array_of_enums import ArrayOfEnums
        from petstore_api.api.fake_api_endpoints.array_of_enums import _response_for_200
        from petstore_api.model import string_enum
        data = ["placed", None]
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        assert isinstance(deserialized.body, ArrayOfEnums)
        expected_results = ArrayOfEnums(
            [string_enum.StringEnum(v) for v in data])
        assert expected_results == deserialized.body

    def test_multiple_of_deserialization(self):
        data = {
            'byte': '3',
            'date': '1970-01-01',
            'password': "******",
            'integer': 30,
            'number': 65.0,
            'float': 62.4,
        }
        from petstore_api.model import format_test
        _response_for_200 = api_client.OpenApiResponse(content={
            self.json_content_type:
            api_client.MediaType(schema=format_test.FormatTest),
        }, )
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response,
                                                     self.configuration)
        self.assertTrue(isinstance(deserialized.body, format_test.FormatTest))

        with self.assertRaisesRegex(
                petstore_api.exceptions.ApiValueError,
                r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)"
        ):
            data = {
                'byte': '3',
                'date': '1970-01-01',
                'password': "******",
                'integer':
                31,  # Value is supposed to be multiple of '2'. An error must be raised
                'number': 65.0,
                'float': 62.4,
            }
            response = self.__response(data)
            _response_for_200.deserialize(response, self.configuration)

        # Disable JSON schema validation. No error should be raised during deserialization.
        configuration = petstore_api.Configuration()
        configuration.disabled_client_side_validations = "multipleOf"

        data = {
            'byte': '3',
            'date': '1970-01-01',
            'password': "******",
            'integer': 31,  # Value is supposed to be multiple of '2'
            'number': 65.0,
            'float': 62.4,
        }
        response = self.__response(data)
        deserialized = _response_for_200.deserialize(response, configuration)
        self.assertTrue(isinstance(deserialized.body, format_test.FormatTest))

        # Disable JSON schema validation but for a different keyword.
        # An error should be raised during deserialization.
        configuration = petstore_api.Configuration()
        configuration.disabled_client_side_validations = "maxItems"

        with self.assertRaisesRegex(
                petstore_api.exceptions.ApiValueError,
                r"Invalid value `31`, value must be a multiple of `2` at \('args\[0\]', 'integer'\)"
        ):
            data = {
                'byte': '3',
                'date': '1970-01-01',
                'password': "******",
                'integer': 31,  # Value is supposed to be multiple of '2'
                'number': 65.0,
                'float': 62.4,
            }
            response = self.__response(data)
            _response_for_200.deserialize(response, configuration)
 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))
Пример #13
0
 def testConfiguration(self):
     # check that different instances use different dictionaries
     c1 = petstore_api.Configuration()
     c2 = petstore_api.Configuration()
     assert id(c1.api_key) != id(c2.api_key)
     assert id(c1.api_key_prefix) != id(c2.api_key_prefix)