Exemplo n.º 1
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.º 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 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.º 4
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()
    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)
    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.º 7
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())
 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)
Exemplo n.º 11
0
    def test_default_config(self):
        default = Configuration()
        default.host = 'default_host'
        default.api_key['api_key'] = 'default_key'
        default.api_key_prefix['prefix'] = 'default_prefix'
        Configuration.set_default(default)

        configuration = Configuration()
        self.assertIsNot(configuration, default)
        self.assertEqual(configuration.host, default.host)
        self.assertEqual(configuration.api_key['api_key'], default.api_key['api_key'])
        self.assertEqual(configuration.api_key_prefix['prefix'], default.api_key_prefix['prefix'])

        configuration.host = 'some_host'
        configuration.api_key['api_key'] = 'some_key'
        configuration.api_key_prefix['prefix'] = 'some_prefix'
        self.assertEqual(default.host, 'default_host')
        self.assertEqual(default.api_key['api_key'], 'default_key')
        self.assertEqual(default.api_key_prefix['prefix'], 'default_prefix')
Exemplo n.º 12
0
class TestConfiguration(unittest.TestCase):
    """Configuration unit test stubs"""
    def setUp(self):
        self.config = Configuration()

    def tearDown(self):
        pass

    def test_configuration(self):
        """Test configuration

        Test host settings # noqa: E501
        """
        host_settings = self.config.get_host_settings()

        self.assertEqual('http://{server}.swagger.io:{port}/v2',
                         host_settings[0]['url'])
        self.assertEqual(
            'petstore',
            host_settings[0]['variables']['server']['default_value'])

        self.assertEqual('https://localhost:8080/{version}',
                         host_settings[1]['url'])
        self.assertEqual(
            'v2', host_settings[1]['variables']['version']['default_value'])

    def test_get_host_from_settings(self):
        """ Test get_host_from_settings

        Test get URL from host settings
        """
        self.assertEqual("http://petstore.swagger.io:80/v2",
                         self.config.get_host_from_settings(0))
        self.assertEqual(
            "http://petstore.swagger.io:8080/v2",
            self.config.get_host_from_settings(0, {'port': '8080'}))
        self.assertEqual(
            "http://dev-petstore.swagger.io:8080/v2",
            self.config.get_host_from_settings(0, {
                'server': 'dev-petstore',
                'port': '8080'
            }))
Exemplo n.º 13
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.º 14
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_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.º 17
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.º 18
0
 def tearDown(self):
     Configuration.set_default(None)
    def test_default_config(self):
        default = Configuration()
        default.host = 'default_host'
        default.api_key['api_key'] = 'default_key'
        default.api_key_prefix['prefix'] = 'default_prefix'
        Configuration.set_default(default)

        configuration = Configuration()
        self.assertIsNot(configuration, default)
        self.assertEqual(configuration.host, default.host)
        self.assertEqual(configuration.api_key['api_key'],
                         default.api_key['api_key'])
        self.assertEqual(configuration.api_key_prefix['prefix'],
                         default.api_key_prefix['prefix'])

        configuration.host = 'some_host'
        configuration.api_key['api_key'] = 'some_key'
        configuration.api_key_prefix['prefix'] = 'some_prefix'
        self.assertEqual(default.host, 'default_host')
        self.assertEqual(default.api_key['api_key'], 'default_key')
        self.assertEqual(default.api_key_prefix['prefix'], 'default_prefix')
 def tearDown(self):
     Configuration.set_default(None)
Exemplo n.º 21
0
 def setUp(self):
     self.config = Configuration()
Exemplo n.º 22
0
 def test_config(self):
     config = Configuration(host=HOST)
     self.assertIsNotNone(config.get_host_settings())
     self.assertEquals(
         config.get_basic_auth_token(),
         urllib3.util.make_headers(basic_auth=":").get('authorization'))
     self.assertEquals(len(config.auth_settings()), 1)
     self.assertIn("petstore_auth", config.auth_settings().keys())
     config.username = "******"
     config.password = "******"
     self.assertEquals(
         config.get_basic_auth_token(),
         urllib3.util.make_headers(
             basic_auth="user:password").get('authorization'))
     self.assertEquals(len(config.auth_settings()), 2)
     self.assertIn("petstore_auth", config.auth_settings().keys())
     self.assertIn("http_basic_test", config.auth_settings().keys())
     config.username = None
     config.password = None
     self.assertEquals(len(config.auth_settings()), 1)
     self.assertIn("petstore_auth", config.auth_settings().keys())
Exemplo n.º 23
0
 def test_config(self):
     config = Configuration(host=HOST)
     self.assertIsNotNone(config.get_host_settings())
     self.assertEqual(
         config.get_basic_auth_token(),
         urllib3.util.make_headers(basic_auth=":").get('authorization'))
     # No authentication scheme has been configured at this point, so auth_settings()
     # should return an empty list.
     self.assertEqual(len(config.auth_settings()), 0)
     # Configure OAuth2 access token and verify the auth_settings have OAuth2 parameters.
     config.access_token = 'MY-ACCESS_TOKEN'
     self.assertEqual(len(config.auth_settings()), 1)
     self.assertIn("petstore_auth", config.auth_settings().keys())
     config.username = "******"
     config.password = "******"
     self.assertEqual(
         config.get_basic_auth_token(),
         urllib3.util.make_headers(
             basic_auth="user:password").get('authorization'))
     self.assertEqual(len(config.auth_settings()), 2)
     self.assertIn("petstore_auth", config.auth_settings().keys())
     self.assertIn("http_basic_test", config.auth_settings().keys())
     config.username = None
     config.password = None
     self.assertEqual(len(config.auth_settings()), 1)
     self.assertIn("petstore_auth", config.auth_settings().keys())