Exemplo n.º 1
0
    def serialize_obj(self, obj, class_name):
        '''
        Return a JSON representation of an Azure object.

        :param obj: Azure object
        :param class_name: Name of the object's class
        :return: serialized result
        '''
        serializer = Serializer()
        return serializer.body(obj, class_name)
    def test_list_not_wrapped_complex_types(self):
        """Test XML list and wrap, items is ref and there is no itemsName.
        """

        basic_xml = ET.fromstring("""<?xml version="1.0"?>
            <AppleBarrel>
                <Apple name="granny"/>
                <Apple name="fuji"/>
            </AppleBarrel>""")

        class AppleBarrel(Model):
            _attribute_map = {
                # Name is ignored if "wrapped" is False
                'good_apples': {
                    'key': 'GoodApples',
                    'type': '[Apple]',
                    'xml': {
                        'name': 'GoodApples'
                    }
                },
            }
            _xml_map = {'name': 'AppleBarrel'}

        class Apple(Model):
            _attribute_map = {
                'name': {
                    'key': 'name',
                    'type': 'str',
                    'xml': {
                        'name': 'name',
                        'attr': True
                    }
                },
            }
            _xml_map = {'name': 'Apple'}

        mymodel = AppleBarrel(
            good_apples=[Apple(
                name='granny'), Apple(name='fuji')])

        s = Serializer({"AppleBarrel": AppleBarrel, "Apple": Apple})
        rawxml = s.body(mymodel, 'AppleBarrel')

        assert_xml_equals(rawxml, basic_xml)
Exemplo n.º 3
0
    def serialize_obj(self, obj, class_name, enum_modules=[]):
        '''
        Return a JSON representation of an Azure object.

        :param obj: Azure object
        :param class_name: Name of the object's class
        :param enum_modules: List of module names to build enum dependencies from.
        :return: serialized result
        '''
        dependencies = dict()
        if enum_modules:
            for module_name in enum_modules:
                mod = importlib.import_module(module_name)
                for mod_class_name, mod_class_obj in inspect.getmembers(mod, predicate=inspect.isclass):
                    dependencies[mod_class_name] = mod_class_obj
            self.log("dependencies: ")
            self.log(str(dependencies))
        serializer = Serializer(classes=dependencies)
        return serializer.body(obj, class_name)
Exemplo n.º 4
0
    def serialize_obj(self, obj, class_name, enum_modules=[]):
        '''
        Return a JSON representation of an Azure object.

        :param obj: Azure object
        :param class_name: Name of the object's class
        :param enum_modules: List of module names to build enum dependencies from.
        :return: serialized result
        '''
        dependencies = dict()
        if enum_modules:
            for module_name in enum_modules:  
               mod = importlib.import_module(module_name)
               for mod_class_name, mod_class_obj in inspect.getmembers(mod, predicate=inspect.isclass):
                   dependencies[mod_class_name] = mod_class_obj 
            self.log("dependencies: ");
            self.log(str(dependencies))
        serializer = Serializer(classes=dependencies)
        return serializer.body(obj, class_name)
Exemplo n.º 5
0
def serializer_helper(object_to_serialize: Model) -> dict:
    if object_to_serialize is None:
        return None

    dependencies = [
        schema_cls for key, schema_cls in getmembers(schema)
        if isinstance(schema_cls, type) and issubclass(schema_cls, (Model,
                                                                    Enum))
    ]
    dependencies += [
        schema_cls for key, schema_cls in getmembers(teams_schema)
        if isinstance(schema_cls, type) and issubclass(schema_cls, (Model,
                                                                    Enum))
    ]
    dependencies_dict = {
        dependency.__name__: dependency
        for dependency in dependencies
    }
    serializer = Serializer(dependencies_dict)
    # pylint: disable=protected-access
    return serializer._serialize(object_to_serialize)
Exemplo n.º 6
0
    def test_list_wrapped_items_name_complex_types(self):
        """Test XML list and wrap, items is ref and there is itemsName.
        """

        basic_xml = ET.fromstring("""<?xml version="1.0"?>
            <AppleBarrel>
                <GoodApples>
                  <Apple name="granny"/>
                  <Apple name="fuji"/>
                </GoodApples>
            </AppleBarrel>""")

        class AppleBarrel(Model):
            _attribute_map = {
                # Pomme should be ignored, since it's invalid to define itemsName for a $ref type
                'good_apples': {'key': 'GoodApples', 'type': '[Apple]', 'xml': {'name': 'GoodApples', 'wrapped': True, 'itemsName': 'Pomme'}},
            }
            _xml_map = {
                'name': 'AppleBarrel'
            }

        class Apple(Model):
            _attribute_map = {
                'name': {'key': 'name', 'type': 'str', 'xml':{'name': 'name', 'attr': True}},
            }
            _xml_map = {
                'name': 'Apple'
            }

        mymodel = AppleBarrel(
            good_apples=[
                Apple(name='granny'),
                Apple(name='fuji')
            ]
        )

        s = Serializer({"AppleBarrel": AppleBarrel, "Apple": Apple})
        rawxml = s.body(mymodel, 'AppleBarrel')

        assert_xml_equals(rawxml, basic_xml)
Exemplo n.º 7
0
 def __init__(self):
     self.config = KeyVaultSampleConfig()
     self.credentials = None
     self.keyvault_data_client = None
     self.keyvault_mgmt_client = None
     self.resource_mgmt_client = None
     self._setup_complete = False
     self.samples = {(name, m)
                     for name, m in inspect.getmembers(self)
                     if getattr(m, 'kv_sample', False)}
     models = {}
     models.update({
         k: v
         for k, v in azure.keyvault.models.__dict__.items()
         if isinstance(v, type)
     })
     models.update({
         k: v
         for k, v in azure.mgmt.keyvault.models.__dict__.items()
         if isinstance(v, type)
     })
     self._serializer = Serializer(models)
Exemplo n.º 8
0
    def test_basic_namespace(self):
        """Test an ultra basic XML."""
        basic_xml = ET.fromstring("""<?xml version="1.0"?>
            <Data xmlns:fictional="http://characters.example.com">
                <fictional:Age>37</fictional:Age>
            </Data>""")

        class XmlModel(Model):
            _attribute_map = {
                'age': {'key': 'age', 'type': 'int', 'xml':{'name': 'Age', 'prefix':'fictional','ns':'http://characters.example.com'}},
            }
            _xml_map = {
                'name': 'Data'
            }

        mymodel = XmlModel(
            age=37,
        )

        s = Serializer({"XmlModel": XmlModel})
        rawxml = s.body(mymodel, 'XmlModel')

        assert_xml_equals(rawxml, basic_xml)
Exemplo n.º 9
0
    def test_basic_unicode(self):
        """Test a XML with unicode."""
        basic_xml = ET.fromstring(u"""<?xml version="1.0" encoding="utf-8"?>
            <Data language="français"/>""".encode("utf-8"))

        class XmlModel(Model):
            _attribute_map = {
                'language': {
                    'key': 'language',
                    'type': 'str',
                    'xml': {
                        'name': 'language',
                        'attr': True
                    }
                },
            }
            _xml_map = {'name': 'Data'}

        mymodel = XmlModel(language=u"français")

        s = Serializer({"XmlModel": XmlModel})
        rawxml = s.body(mymodel, 'XmlModel')

        assert_xml_equals(rawxml, basic_xml)
    def test_two_complex_same_type(self):
        """Two different attribute are same type
        """

        basic_xml = ET.fromstring("""<?xml version="1.0"?>
            <AppleBarrel>
                <EuropeanApple name="granny"/>
                <USAApple name="fuji"/>
            </AppleBarrel>""")

        class AppleBarrel(Model):
            _attribute_map = {
                'eu_apple': {'key': 'EuropeanApple', 'type': 'Apple', 'xml': {'name': 'EuropeanApple'}},
                'us_apple': {'key': 'USAApple', 'type': 'Apple', 'xml': {'name': 'USAApple'}},
            }
            _xml_map = {
                'name': 'AppleBarrel'
            }

        class Apple(Model):
            _attribute_map = {
                'name': {'key': 'name', 'type': 'str', 'xml':{'name': 'name', 'attr': True}},
            }
            _xml_map = {
                'name': 'Apple'
            }

        mymodel = AppleBarrel(
            eu_apple=Apple(name='granny'),
            us_apple=Apple(name='fuji'),
        )

        s = Serializer({"AppleBarrel": AppleBarrel, "Apple": Apple})
        rawxml = s.body(mymodel, 'AppleBarrel')

        assert_xml_equals(rawxml, basic_xml)
Exemplo n.º 11
0
class KeyVaultSampleBase(object):
    """Base class for Key Vault samples, provides common functionality needed across Key Vault sample code

    :ivar config: Azure subscription id for the user intending to run the sample
    :vartype config: :class: `KeyVaultSampleConfig`q
    
    :ivar credentials: Azure Active Directory credentials used to authenticate with Azure services
    :vartype credentials: :class: `ServicePrincipalCredentials 
     <msrestazure.azure_active_directory.ServicePrincipalCredentials>`
    
    :ivar keyvault_data_client: Key Vault data client used for interacting with key vaults 
    :vartype keyvault_data_client: :class: `KeyVaultClient <azure.keyvault.KeyVaultClient>`
    
    :ivar keyvault_mgmt_client: Key Vault management client used for creating and managing key vaults 
    :vartype keyvault_mgmt_client:  :class: `KeyVaultManagementClient <azure.mgmt.keyvault.KeyVaultManagementClient>`
    
    :ivar resource_mgmt_client: Azure resource management client used for managing azure resources, access, and groups 
    :vartype resource_mgmt_client:  :class: `ResourceManagementClient <azure.mgmt.resource.ResourceManagementClient>`
    """
    def __init__(self):
        self.config = KeyVaultSampleConfig()
        self.credentials = None
        self.keyvault_data_client = None
        self.keyvault_mgmt_client = None
        self.resource_mgmt_client = None
        self._setup_complete = False
        self.samples = {(name, m)
                        for name, m in inspect.getmembers(self)
                        if getattr(m, 'kv_sample', False)}
        models = {}
        models.update({
            k: v
            for k, v in azure.keyvault.models.__dict__.items()
            if isinstance(v, type)
        })
        models.update({
            k: v
            for k, v in azure.mgmt.keyvault.models.__dict__.items()
            if isinstance(v, type)
        })
        self._serializer = Serializer(models)

    def setup_sample(self):
        """
        Provides common setup for Key Vault samples, such as creating rest clients, creating a sample resource group
        if needed, and ensuring proper access for the service principal.
         
        :return: None 
        """
        if not self._setup_complete:
            self.mgmt_creds = ServicePrincipalCredentials(
                client_id=self.config.client_id,
                secret=self.config.client_secret,
                tenant=self.config.tenant_id)
            self.data_creds = ServicePrincipalCredentials(
                client_id=self.config.client_id,
                secret=self.config.client_secret,
                tenant=self.config.tenant_id)
            self.resource_mgmt_client = ResourceManagementClient(
                self.mgmt_creds, self.config.subscription_id)

            # ensure the service principle has key vault as a valid provider
            self.resource_mgmt_client.providers.register('Microsoft.KeyVault')

            # ensure the intended resource group exists
            self.resource_mgmt_client.resource_groups.create_or_update(
                self.config.group_name, {'location': self.config.location})

            self.keyvault_mgmt_client = KeyVaultManagementClient(
                self.mgmt_creds, self.config.subscription_id)

            self.keyvault_data_client = KeyVaultClient(self.data_creds)

            self._setup_complete = True

    def create_vault(self):
        """
        Creates a new key vault with a unique name, granting full permissions to the current credentials
        :return: a newly created key vault
        :rtype: :class:`Vault <azure.keyvault.generated.models.Vault>`
        """
        vault_name = get_name('vault')

        # setup vault permissions for the access policy for the sample service principle
        permissions = Permissions()
        permissions.keys = KEY_PERMISSIONS_ALL
        permissions.secrets = SECRET_PERMISSIONS_ALL
        permissions.certificates = CERTIFICATE_PERMISSIONS_ALL

        policy = AccessPolicyEntry(self.config.tenant_id,
                                   self.config.client_oid, permissions)

        properties = VaultProperties(self.config.tenant_id,
                                     Sku(name='standard'),
                                     access_policies=[policy])

        parameters = VaultCreateOrUpdateParameters(self.config.location,
                                                   properties)
        parameters.properties.enabled_for_deployment = True
        parameters.properties.enabled_for_disk_encryption = True
        parameters.properties.enabled_for_template_deployment = True

        print('creating vault {}'.format(vault_name))

        vault = self.keyvault_mgmt_client.vaults.create_or_update(
            self.config.group_name, vault_name, parameters)

        # wait for vault DNS entry to be created
        # see issue: https://github.com/Azure/azure-sdk-for-python/issues/1172
        self._poll_for_vault_connection(vault.properties.vault_uri)

        print('created vault {} {}'.format(vault_name,
                                           vault.properties.vault_uri))

        return vault

    def _poll_for_vault_connection(self,
                                   vault_uri,
                                   retry_wait=10,
                                   max_retries=4):
        """
        polls the data client 'get_secrets' method until a 200 response is received indicating the the vault
        is available for data plane requests
        """
        last_error = None
        for x in range(max_retries - 1):
            try:
                # sleep first to avoid improper DNS caching
                time.sleep(retry_wait)
                self.keyvault_data_client.get_secrets(vault_uri)
                return
            except ClientRequestError as e:
                print('vault connection not available')
                last_error = e
        raise last_error

    def _serialize(self, obj):
        if isinstance(obj, Paged):
            serialized = [self._serialize(i) for i in list(obj)]
        else:
            serialized = self._serializer.body(obj, type(obj).__name__)
        return json.dumps(serialized, indent=4, separators=(',', ': '))