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)
Exemplo n.º 2
0
    def test_valid_http_signature_ec_p521(self):
        privkey_path = self.ec_p521_key_path
        signing_cfg = signing.HttpSigningConfiguration(
            key_id="my-key-id",
            signing_scheme=signing.SCHEME_HS2019,
            private_key_path=privkey_path,
            private_key_passphrase=self.private_key_passphrase,
            hash_algorithm=signing.HASH_SHA512,
            signed_headers=[
                signing.HEADER_REQUEST_TARGET,
                signing.HEADER_CREATED,
            ]
        )
        config = Configuration(host=HOST, signing_info=signing_cfg)
        # Set the OAuth2 acces_token to None. Here we are interested in testing
        # the HTTP signature scheme.
        config.access_token = None

        api_client = petstore_api.ApiClient(config)
        pet_api = PetApi(api_client)

        mock_pool = MockPoolManager(self)
        api_client.rest_client.pool_manager = mock_pool

        mock_pool.set_signing_config(signing_cfg)
        mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet',
                                 body=json.dumps(api_client.sanitize_for_serialization(self.pet)),
                                 headers={'Content-Type': r'application/json',
                                          'Authorization': r'Signature keyId="my-key-id",algorithm="hs2019",created=[0-9]+,'
                                                r'headers="\(request-target\) \(created\)",'
                                                r'signature="[a-zA-Z0-9+/=]+"',
                                          'User-Agent': r'OpenAPI-Generator/1.0.0/python'},
                                 preload_content=True, timeout=None)

        pet_api.add_pet(self.pet)
Exemplo n.º 3
0
 def test_deserialize_cat_discard_unknown_properties(self):
     """
     Deserialize Cat with unknown properties.
     Request to discard unknown properties, but Cat is composed schema
     with one inner schema that has 'additionalProperties' set to true.
     """
     config = Configuration(discard_unknown_keys=True)
     api_client = petstore_api.ApiClient(config)
     data = {
         "class_name": "Cat",
         "color": "black",
         "declawed": True,
         # Below are additional (undeclared) properties.
         "my_additional_property": 123,
     }
     # The 'my_additional_property' is undeclared, but 'Cat' has a 'Address' type through
     # the allOf: [ $ref: '#/components/schemas/Address' ].
     response = MockResponse(data=json.dumps(data))
     deserialized = api_client.deserialize(response, ((petstore_api.Cat), ),
                                           True)
     self.assertTrue(isinstance(deserialized, petstore_api.Cat))
     # Check the 'unknown_property' and 'more-unknown' properties are not present in the
     # output.
     self.assertIn("declawed", deserialized.to_dict().keys())
     self.assertIn("my_additional_property", deserialized.to_dict().keys())
Exemplo n.º 4
0
 def setUp(self):
     config = Configuration()
     config.host = HOST
     self.api_client = petstore_api.ApiClient(config)
     self.pet_api = petstore_api.PetApi(self.api_client)
     self.setUpModels()
     self.setUpFiles()
Exemplo n.º 5
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_deserialize_banana_req_discard_unknown_properties(self):
     """
     Deserialize bananaReq with unknown properties.
     Discard unknown properties.
     """
     config = Configuration(discard_unknown_keys=True)
     api_client = petstore_api.ApiClient(config)
     data = {
         'lengthCm': 21.3,
         'sweet': False,
         # Below are additional (undeclared) properties not specified in the bananaReq schema.
         'unknown_property': 'a-value',
         'more-unknown': ['a']
     }
     # The 'unknown_property' is undeclared, which would normally raise an exception, but
     # when discard_unknown_keys is set to True, the unknown properties are discarded.
     response = MockResponse(data=json.dumps(data))
     deserialized = api_client.deserialize(response,
                                           ((banana_req.BananaReq), ), True)
     self.assertTrue(isinstance(deserialized, banana_req.BananaReq))
     # Check the 'unknown_property' and 'more-unknown' properties are not present in the
     # output.
     self.assertIn("length_cm", deserialized.to_dict().keys())
     self.assertNotIn("unknown_property", deserialized.to_dict().keys())
     self.assertNotIn("more-unknown", deserialized.to_dict().keys())
    def test_deserialize_banana_req_do_not_discard_unknown_properties(self):
        """
        deserialize bananaReq with unknown properties.
        Strict validation is enabled.
        Simple (non-composed) schema scenario.
        """
        config = Configuration(discard_unknown_keys=False)
        api_client = petstore_api.ApiClient(config)
        data = {
            'lengthCm': 21.3,
            'sweet': False,
            # Below is an unknown property not explicitly declared in the OpenAPI document.
            # It should not be in the payload because additional properties (undeclared) are
            # not allowed in the bananaReq schema (additionalProperties: false).
            'unknown_property': 'a-value'
        }
        response = MockResponse(data=json.dumps(data))

        # Deserializing with strict validation raises an exception because the 'unknown_property'
        # is undeclared.
        with self.assertRaises(
                petstore_api.exceptions.ApiAttributeError) as cm:
            deserialized = api_client.deserialize(response,
                                                  ((banana_req.BananaReq), ),
                                                  True)
        self.assertTrue(
            re.match("BananaReq has no attribute 'unknown_property' at.*",
                     str(cm.exception)),
            'Exception message: {0}'.format(str(cm.exception)))
    def test_deserialize_fruit_req_do_not_discard_unknown_properties(self):
        """
        deserialize FruitReq with unknown properties.
        Strict validation is enabled.
        Composed schema scenario.
        """
        config = Configuration(discard_unknown_keys=False)
        api_client = petstore_api.ApiClient(config)
        data = {
            'lengthCm': 21.3,
            'sweet': False,
            # Below is an unknown property not explicitly declared in the OpenAPI document.
            # It should not be in the payload because additional properties (undeclared) are
            # not allowed in the schema (additionalProperties: false).
            'unknown_property': 'a-value'
        }
        response = MockResponse(data=json.dumps(data))

        # Deserializing with strict validation raises an exception because the 'unknown_property'
        # is undeclared.
        with self.assertRaisesRegex(
                petstore_api.ApiValueError,
                "Invalid inputs given to generate an instance of FruitReq. None of the oneOf schemas matched the input data."
        ):
            deserialized = api_client.deserialize(response,
                                                  ((fruit_req.FruitReq), ),
                                                  True)
    def test_deserialize_isosceles_triangle_do_not_discard_unknown_properties(
            self):
        """
        deserialize IsoscelesTriangle with unknown properties.
        Strict validation is enabled.
        Composed schema scenario.
        """
        config = Configuration(discard_unknown_keys=False)
        api_client = petstore_api.ApiClient(config)
        data = {
            'shape_type': 'Triangle',
            'triangle_type': 'EquilateralTriangle',
            # Below is an unknown property not explicitly declared in the OpenAPI document.
            # It should not be in the payload because additional properties (undeclared) are
            # not allowed in the schema (additionalProperties: false).
            'unknown_property': 'a-value'
        }
        response = MockResponse(data=json.dumps(data))

        # Deserializing with strict validation raises an exception because the 'unknown_property'
        # is undeclared.
        with self.assertRaises(petstore_api.ApiValueError) as cm:
            deserialized = api_client.deserialize(
                response, ((isosceles_triangle.IsoscelesTriangle), ), True)
        self.assertTrue(
            re.match('.*Not all inputs were used.*unknown_property.*',
                     str(cm.exception)),
            'Exception message: {0}'.format(str(cm.exception)))
Exemplo n.º 10
0
 def setUp(self):
     config = Configuration()
     config.host = HOST
     config.access_token = 'ACCESS_TOKEN'
     self.api_client = petstore_api.ApiClient(config)
     self.pet_api = PetApi(self.api_client)
     self.setUpModels()
     self.setUpFiles()
Exemplo n.º 11
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')
Exemplo n.º 12
0
    def test_create_api_instance(self):
        pet_api = petstore_api.PetApi()
        pet_api2 = petstore_api.PetApi()
        api_client3 = petstore_api.ApiClient()
        api_client3.user_agent = 'api client 3'
        api_client4 = petstore_api.ApiClient()
        api_client4.user_agent = 'api client 4'
        pet_api3 = petstore_api.PetApi(api_client3)

        # same default api client
        self.assertEqual(pet_api.api_client, pet_api2.api_client)
        # confirm using the default api client in the config module
        self.assertEqual(pet_api.api_client, petstore_api.configuration.api_client)
        # 2 different api clients are not the same
        self.assertNotEqual(api_client3, api_client4)
        # customized pet api not using the default api client
        self.assertNotEqual(pet_api3.api_client, petstore_api.configuration.api_client)
        # customized pet api not using the old pet api's api client
        self.assertNotEqual(pet_api3.api_client, pet_api2.api_client)
Exemplo n.º 13
0
    async def test_proxy(self):
        config = Configuration()
        # set not-existent proxy and catch an error to verify that
        # the client library (aiohttp) tried to use it.
        config.proxy = 'http://localhost:8080/proxy'
        async with petstore_api.ApiClient(config) as client:
            pet_api = petstore_api.PetApi(client)

            with self.assertRaisesRegex(petstore_api.rest.aiohttp.client_exceptions.ClientProxyConnectionError,
                                        'Cannot connect to host localhost:8080'):
                await pet_api.get_pet_by_id(self.pet.id)
Exemplo n.º 14
0
    async def test_context_manager_closes_client(self):

        async with petstore_api.ApiClient() as client:
            # thread pool
            self.assertIsNotNone(client.pool)
            pool_ref = weakref.ref(client._pool)
            self.assertIsNotNone(pool_ref())
            # pool_manager
            self.assertFalse(client.rest_client.pool_manager.closed)
            rest_pool_ref = client.rest_client.pool_manager

        self.assertIsNone(pool_ref())
        self.assertTrue(rest_pool_ref.closed)
Exemplo n.º 15
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 testReadOnlyForComposedSchema(self):
     """Test ReadOnlyForComposedSchema"""
     MockResponse = namedtuple('MockResponse', 'data')
     client = petstore_api.ApiClient()
     """ deserialize dict(str, Enum_Test) """
     data = {
         "Dog": {
             "class_name": "Dog",
             "breed": "BullDog",
             "color": "Black",
             "tail": True
         }
     }
     response = MockResponse(data=json.dumps(data))
     deserialized = client.deserialize(response, ({str: (Dog, )}, ), True)
     assert isinstance(deserialized, dict)
     assert isinstance(deserialized['Dog'], Dog)
Exemplo n.º 17
0
    def test_deserialize_dog_do_not_discard_unknown_properties(self):
        """ deserialize str, Dog) with unknown properties, strict validation is enabled """
        config = Configuration(discard_unknown_keys=False)
        api_client = petstore_api.ApiClient(config)
        data = {
            "class_name": "Dog",
            "color": "black",
            "breed": "husky",
            "unknown_property": "a-value"
        }
        response = MockResponse(data=json.dumps(data))

        # Deserializing with strict validation raises an exception because the 'unknown_property'
        # is undeclared.
        with self.assertRaises(petstore_api.ApiValueError) as cm:
            deserialized = api_client.deserialize(response, ((petstore_api.Dog),), True)
        self.assertTrue(re.match('.*Not all inputs were used.*unknown_property.*', str(cm.exception)),
            'Exception message: {0}'.format(str(cm.exception)))
Exemplo n.º 18
0
    def test_deserialize_cat_do_not_discard_unknown_properties(self):
        """ deserialize str, Cat) with unknown properties, strict validation is enabled """
        config = Configuration(discard_unknown_keys=False)
        api_client = petstore_api.ApiClient(config)
        data = {
            "class_name": "Cat",
            "color": "black",
            "declawed": True,
            "dynamic-property": 12345,
        }
        response = MockResponse(data=json.dumps(data))

        # Deserializing with strict validation does not raise an exception because the even though
        # the 'dynamic-property' is undeclared, the 'Cat' schema defines the additionalProperties
        # attribute.
        deserialized = api_client.deserialize(response, ((petstore_api.Cat),), True)
        self.assertTrue(isinstance(deserialized, petstore_api.Cat))
        self.assertIn('color', deserialized.to_dict())
        self.assertEqual(deserialized['color'], 'black')
 def test_deserialize_fruit_req_discard_unknown_properties(self):
     """
     deserialize FruitReq with unknown properties.
     Strict validation is enabled.
     Composed schema scenario.
     """
     config = Configuration(discard_unknown_keys=True)
     api_client = petstore_api.ApiClient(config)
     data = {
         'lengthCm': 21.3,
         'sweet': False,
         # Below is an unknown property not explicitly declared in the OpenAPI document.
         # It should not be in the payload because additional properties (undeclared) are
         # not allowed in BananaReq
         'unknown_property': 'a-value'
     }
     response = MockResponse(data=json.dumps(data))
     deserialized = api_client.deserialize(response,
                                           ((fruit_req.FruitReq), ), True)
     self.assertNotIn("unknown_property", deserialized.to_dict().keys())
    def test_servers(self):
        config = petstore_api.Configuration(server_index=1, server_variables={'version': 'v1'})
        api_client = petstore_api.ApiClient(config)
        api = pet_api.PetApi(api_client)

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

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

        api_client.request = functools.partial(request, 'https://localhost:8080/v1/pet/123456789')
        try:
            api.delete_pet(123456789)
        except RuntimeError as e:
            assert "pass" == str(e)
 def test_deserialize_cat_discard_unknown_properties(self):
     """
     Deserialize Cat with unknown properties.
     Request to discard unknown properties, but Cat is composed schema
     with one inner schema that has 'additionalProperties' set to true.
     """
     config = Configuration(discard_unknown_keys=True)
     api_client = petstore_api.ApiClient(config)
     data = {
         "class_name": "Cat",
         "color": "black",
         "declawed": True,
         # Below are additional (undeclared) properties.
         "my_additional_property": 123,
     }
     # The 'my_additional_property' is undeclared
     response = MockResponse(data=json.dumps(data))
     deserialized = api_client.deserialize(response, ((cat.Cat), ), True)
     self.assertTrue(isinstance(deserialized, cat.Cat))
     # Check the 'my_additional_property' is present
     self.assertIn("my_additional_property", deserialized.to_dict().keys())
Exemplo n.º 22
0
 def test_deserialize_dog_discard_unknown_properties(self):
     """ deserialize str, Dog) with unknown properties, discard unknown properties """
     config = Configuration(discard_unknown_keys=True)
     api_client = petstore_api.ApiClient(config)
     data = {
         "class_name": "Dog",
         "color": "black",
         "breed": "husky",
         "unknown_property": "a-value",
         "more-unknown": [
             "a"
         ]
     }
     # The 'unknown_property' is undeclared, which would normally raise an exception, but
     # when discard_unknown_keys is set to True, the unknown properties are discarded.
     response = MockResponse(data=json.dumps(data))
     deserialized = api_client.deserialize(response, ((petstore_api.Dog),), True)
     self.assertTrue(isinstance(deserialized, petstore_api.Dog))
     # Check the 'unknown_property' and 'more-unknown' properties are not present in the
     # output.
     self.assertIn("breed", deserialized.to_dict().keys())
     self.assertNotIn("unknown_property", deserialized.to_dict().keys())
     self.assertNotIn("more-unknown", deserialized.to_dict().keys())
Exemplo n.º 23
0
 def test_atexit_closes_threadpool(self):
     client = petstore_api.ApiClient()
     self.assertIsNotNone(client.pool)
     self.assertIsNotNone(client._pool)
     atexit._run_exitfuncs()
     self.assertIsNone(client._pool)
Exemplo n.º 24
0
 def test_context_manager_closes_threadpool(self):
     with petstore_api.ApiClient() as client:
         self.assertIsNotNone(client.pool)
         pool_ref = weakref.ref(client._pool)
         self.assertIsNotNone(pool_ref())
     self.assertIsNone(pool_ref())
Exemplo n.º 25
0
 def setUp(self):
     self.api_client = petstore_api.ApiClient()
Exemplo n.º 26
0
 def setUp(self):
     self.api_client = petstore_api.ApiClient()
     self.deserialize = self.api_client.deserialize
 def setUp(self):
     self.api_client = petstore_api.ApiClient()
     self.pet_api = petstore_api.PetApi(self.api_client)
     self.setUpModels()
 def setUp(self):
     self.api_client = petstore_api.ApiClient()
     self.serialize = self.api_client.sanitize_for_serialization
Exemplo n.º 29
0
 def setUp(self):
     self.api_client = petstore_api.ApiClient()
     from petstore_api.api.pet_api import PetApi
     self.pet_api = PetApi(self.api_client)
     self.setUpModels()