diff --git a/README.md b/README.md index b1bdf402..fd2874c0 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ Service Name | Imported Class Name --- | --- [Case Management](https://cloud.ibm.com/apidocs/case-management) | CaseManagementV1 [Catalog Management](https://cloud.ibm.com/apidocs/resource-catalog/private-catalog) | CatalogManagementV1 +[Configuration Governance](https://cloud.ibm.com/apidocs/security-compliance/config) | ConfigurationGovernanceV1 [Enterprise Management](https://cloud.ibm.com/apidocs/enterprise-apis/enterprise) | EnterpriseManagementV1 [Global Catalog](https://cloud.ibm.com/apidocs/resource-catalog/global-catalog) | GlobalCatalogV1 [Global Search](https://cloud.ibm.com/apidocs/search) | GlobalSearchV2 @@ -74,13 +75,13 @@ Service Name | Imported Class Name To install, use `pip` or `easy_install`: ```bash -pip install --upgrade "ibm_platform_services>=0.11.0" +pip install --upgrade "ibm-platform-services>=0.11.0" ``` or ```bash -easy_install --upgrade "ibm_platform_services>=0.11.0" +easy_install --upgrade "ibm-platform-services>=0.11.0" ``` ## Using the SDK diff --git a/examples/test_configuration_governance_v1_examples.py b/examples/test_configuration_governance_v1_examples.py new file mode 100644 index 00000000..68432e0f --- /dev/null +++ b/examples/test_configuration_governance_v1_examples.py @@ -0,0 +1,396 @@ +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Examples for ConfigurationGovernanceV1 +""" + +import os +import pytest +from ibm_cloud_sdk_core import ApiException, read_external_sources +from ibm_platform_services.configuration_governance_v1 import * + +# Config file name +config_file = 'configuration_governance.env' + +configuration_governance_service = None + +config = None + +# Variables to hold link values +attachment_etag_link = None +attachment_id_link = None +rule_etag_link = None +rule_id_link = None + +# Additional configuration settings +test_label = 'PythonSDKExamples' +account_id = None +service_name = None +enterprise_scope_id = None +subacct_scope_id = None + +############################################################################## +# Start of Examples for Service: ConfigurationGovernanceV1 +############################################################################## +# region +class TestConfigurationGovernanceV1Examples(): + """ + Example Test Class for ConfigurationGovernanceV1 + """ + + @classmethod + def setup_class(cls): + global configuration_governance_service + if os.path.exists(config_file): + os.environ['IBM_CREDENTIALS_FILE'] = config_file + + # begin-common + + configuration_governance_service = ConfigurationGovernanceV1.new_instance( + ) + + # end-common + assert configuration_governance_service is not None + + # Load the configuration + global config, account_id, service_name, enterprise_scope_id, subacct_scope_id + config = read_external_sources(ConfigurationGovernanceV1.DEFAULT_SERVICE_NAME) + + account_id = config['ACCOUNT_ID'] + service_name = config['EXAMPLE_SERVICE_NAME'] + enterprise_scope_id = config['ENTERPRISE_SCOPE_ID'] + subacct_scope_id = config['SUBACCT_SCOPE_ID'] + + cls.clean_rules() + + print('Setup complete.') + + needscredentials = pytest.mark.skipif( + not os.path.exists(config_file), reason="External configuration not available, skipping..." + ) + + @needscredentials + def test_create_rules_example(self): + """ + create_rules request example + """ + try: + # begin-create_rules + + target_resource_model = { + 'service_name': service_name, + 'resource_kind': 'service' + } + + rule_required_config_model = { + 'description': 'Public access check', + 'property': 'public_access_enabled', + 'operator': 'is_true' + } + + enforcement_action_model = { + 'action': 'disallow' + } + + rule_request_model = { + 'account_id': account_id, + 'name': 'Disable public access', + 'description': 'Ensure that public access to account resources is disabled.', + 'target': {'service_name':service_name,'resource_kind':'service'}, + 'required_config': {'description':'Public access check','and':[{'property':'public_access_enabled','operator':'is_false'}]}, + 'enforcement_actions': [enforcement_action_model], + 'labels': [test_label] + } + + create_rule_request_model = { + 'request_id': '3cebc877-58e7-44a5-a292-32114fa73558', + 'rule': {'account_id':account_id,'name':'Disable public access','description':'Ensure that public access to account resources is disabled.','labels':[test_label],'target':{'service_name':service_name,'resource_kind':'service'},'required_config':{'description':'Public access check','and':[{'property':'public_access_enabled','operator':'is_false'}]},'enforcement_actions':[{'action':'disallow'},{'action':'audit_log'}]} + } + + detailed_response = configuration_governance_service.create_rules( + rules=[create_rule_request_model] + ) + create_rules_response = detailed_response.get_result() + if detailed_response.status_code == 207: + for responseEntry in create_rules_response['rules']: + if responseEntry['status_code'] > 299: + raise ApiException(code=responseEntry['errors'][0]['code'], message=responseEntry['errors'][0]['message']) + + print(json.dumps(create_rules_response, indent=2)) + + # end-create_rules + + global rule_id_link + rule_id_link = create_rules_response['rules'][0]['rule']['rule_id']; + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_create_attachments_example(self): + """ + create_attachments request example + """ + try: + # begin-create_attachments + + excluded_scope_model = { + 'note': 'Development account', + 'scope_id': subacct_scope_id, + 'scope_type': 'enterprise.account' + } + + attachment_request_model = { + 'account_id': account_id, + 'included_scope': {'note':'My enterprise','scope_id':enterprise_scope_id,'scope_type':'enterprise'}, + 'excluded_scopes': [excluded_scope_model] + } + + create_attachments_response = configuration_governance_service.create_attachments( + rule_id=rule_id_link, + attachments=[attachment_request_model] + ).get_result() + + print(json.dumps(create_attachments_response, indent=2)) + + # end-create_attachments + + global attachment_id_link + attachment_id_link = create_attachments_response['attachments'][0]['attachment_id']; + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_get_attachment_example(self): + """ + get_attachment request example + """ + try: + # begin-get_attachment + + attachment = configuration_governance_service.get_attachment( + rule_id=rule_id_link, + attachment_id=attachment_id_link + ).get_result() + + print(json.dumps(attachment, indent=2)) + + # end-get_attachment + + global attachment_etag_link + attachment_etag_link = configuration_governance_service.get_attachment( + rule_id=rule_id_link, attachment_id=attachment_id_link).get_headers().get('Etag') + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_get_rule_example(self): + """ + get_rule request example + """ + try: + # begin-get_rule + + rule = configuration_governance_service.get_rule( + rule_id=rule_id_link + ).get_result() + + print(json.dumps(rule, indent=2)) + + # end-get_rule + + global rule_etag_link + rule_etag_link = configuration_governance_service.get_rule(rule_id=rule_id_link).get_headers().get('etag') + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_list_rules_example(self): + """ + list_rules request example + """ + try: + # begin-list_rules + + rule_list = configuration_governance_service.list_rules( + account_id=account_id + ).get_result() + + print(json.dumps(rule_list, indent=2)) + + # end-list_rules + + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_update_rule_example(self): + """ + update_rule request example + """ + try: + # begin-update_rule + + rule_target_attribute_model = { + 'name': 'testString', + 'operator': 'string_equals' + } + + target_resource_model = { + 'service_name': service_name, + 'resource_kind': 'service', + 'additional_target_attributes': [rule_target_attribute_model] + } + + rule_required_config_model = { + 'property': 'public_access_enabled', + 'operator': 'is_false' + } + + enforcement_action_model = { + 'action': 'audit_log' + } + + rule = configuration_governance_service.update_rule( + rule_id=rule_id_link, + if_match=rule_etag_link, + name='Disable public access', + description='Ensure that public access to account resources is disabled.', + target={'service_name':service_name,'resource_kind':'service','additional_target_attributes':[]}, + required_config={'property':'public_access_enabled','operator':'is_false'}, + enforcement_actions=[enforcement_action_model], + account_id=account_id, + rule_type='user_defined', + labels=['testString'] + ).get_result() + + print(json.dumps(rule, indent=2)) + + # end-update_rule + + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_list_attachments_example(self): + """ + list_attachments request example + """ + try: + # begin-list_attachments + + attachment_list = configuration_governance_service.list_attachments( + rule_id=rule_id_link + ).get_result() + + print(json.dumps(attachment_list, indent=2)) + + # end-list_attachments + + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_update_attachment_example(self): + """ + update_attachment request example + """ + try: + # begin-update_attachment + + excluded_scope_model = { + 'note': 'Development account', + 'scope_id': subacct_scope_id, + 'scope_type': 'enterprise.account' + } + + attachment = configuration_governance_service.update_attachment( + rule_id=rule_id_link, + attachment_id=attachment_id_link, + if_match=attachment_etag_link, + account_id=account_id, + included_scope={'note':'My enterprise','scope_id':enterprise_scope_id,'scope_type':'enterprise'}, + excluded_scopes=[excluded_scope_model] + ).get_result() + + print(json.dumps(attachment, indent=2)) + + # end-update_attachment + + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_delete_attachment_example(self): + """ + delete_attachment request example + """ + try: + # begin-delete_attachment + + response = configuration_governance_service.delete_attachment( + rule_id=rule_id_link, + attachment_id=attachment_id_link + ).get_result() + + print(json.dumps(response, indent=2)) + + # end-delete_attachment + + except ApiException as e: + pytest.fail(str(e)) + + @needscredentials + def test_delete_rule_example(self): + """ + delete_rule request example + """ + try: + # begin-delete_rule + + response = configuration_governance_service.delete_rule( + rule_id=rule_id_link + ).get_result() + + print(json.dumps(response, indent=2)) + + # end-delete_rule + + except ApiException as e: + pytest.fail(str(e)) + + @classmethod + def clean_rules(cls): + """ + Clean up rules from prior test runs + """ + try: + rule_list = configuration_governance_service.list_rules( + account_id=account_id, + labels=test_label + ).get_result() + + for rule in rule_list['rules']: + rule_id = rule['rule_id'] + print(f'deleting rule {rule_id}') + configuration_governance_service.delete_rule(rule_id) + + except ApiException as e: + print(str(e)) + +# endregion +############################################################################## +# End of Examples for Service: ConfigurationGovernanceV1 +############################################################################## diff --git a/ibm_platform_services/__init__.py b/ibm_platform_services/__init__.py index a2c86902..c41d8eff 100644 --- a/ibm_platform_services/__init__.py +++ b/ibm_platform_services/__init__.py @@ -24,6 +24,7 @@ from .case_management_v1 import CaseManagementV1 from .catalog_management_v1 import CatalogManagementV1 +from .configuration_governance_v1 import ConfigurationGovernanceV1 from .enterprise_management_v1 import EnterpriseManagementV1 from .global_catalog_v1 import GlobalCatalogV1 from .global_search_v2 import GlobalSearchV2 diff --git a/ibm_platform_services/configuration_governance_v1.py b/ibm_platform_services/configuration_governance_v1.py new file mode 100644 index 00000000..64f86f83 --- /dev/null +++ b/ibm_platform_services/configuration_governance_v1.py @@ -0,0 +1,2925 @@ +# coding: utf-8 + +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-68ee7c8f-20200829-062726 + +""" +API specification for the Configuration Governance service. +""" + +from enum import Enum +from typing import Dict, List +import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from ibm_cloud_sdk_core.utils import convert_model + +from .common import get_sdk_headers + +############################################################################## +# Service +############################################################################## + +class ConfigurationGovernanceV1(BaseService): + """The Configuration Governance V1 service.""" + + DEFAULT_SERVICE_URL = 'https://compliance.cloud.ibm.com' + DEFAULT_SERVICE_NAME = 'configuration_governance' + + @classmethod + def new_instance(cls, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> 'ConfigurationGovernanceV1': + """ + Return a new client for the Configuration Governance service using the + specified parameters and external configuration. + """ + authenticator = get_authenticator_from_environment(service_name) + service = cls( + authenticator + ) + service.configure_service(service_name) + return service + + def __init__(self, + authenticator: Authenticator = None, + ) -> None: + """ + Construct a new client for the Configuration Governance service. + + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + """ + BaseService.__init__(self, + service_url=self.DEFAULT_SERVICE_URL, + authenticator=authenticator) + + + ######################### + # Rules + ######################### + + + def create_rules(self, + rules: List['CreateRuleRequest'], + *, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Create rules. + + Creates one or more rules that you can use to govern the way that IBM Cloud + resources can be provisioned and configured. + A successful `POST /config/rules` request defines a rule based on the target, + conditions, and enforcement actions that you specify. The response returns the ID + value for your rule, along with other metadata. + + :param List[CreateRuleRequest] rules: A list of rules to be created. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CreateRulesResponse` object + """ + + if rules is None: + raise ValueError('rules must be provided') + rules = [convert_model(x) for x in rules] + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_rules') + headers.update(sdk_headers) + + data = { + 'rules': rules + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data) + + response = self.send(request) + return response + + + def list_rules(self, + account_id: str, + *, + transaction_id: str = None, + attached: bool = None, + labels: str = None, + scopes: str = None, + limit: int = None, + offset: int = None, + **kwargs + ) -> DetailedResponse: + """ + List rules. + + Retrieves a list of the rules that are available in your account. + + :param str account_id: Your IBM Cloud account ID. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param bool attached: (optional) Retrieves a list of rules that have scope + attachments. + :param str labels: (optional) Retrieves a list of rules that match the + labels that you specify. + :param str scopes: (optional) Retrieves a list of rules that match the + scope ID that you specify. + :param int limit: (optional) The number of resources to retrieve. By + default, list operations return the first 100 items. To retrieve a + different set of items, use `limit` with `offset` to page through your + available resources. + **Usage:** If you have 20 rules, and you want to retrieve only the first 5 + rules, use `../rules?account_id={account_id}&limit=5`. + :param int offset: (optional) The number of resources to skip. By + specifying `offset`, you retrieve a subset of resources that starts with + the `offset` value. Use `offset` with `limit` to page through your + available resources. + **Usage:** If you have 100 rules, and you want to retrieve rules 26 through + 50, use `../rules?account_id={account_id}&offset=25&limit=5`. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `RuleList` object + """ + + if account_id is None: + raise ValueError('account_id must be provided') + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_rules') + headers.update(sdk_headers) + + params = { + 'account_id': account_id, + 'attached': attached, + 'labels': labels, + 'scopes': scopes, + 'limit': limit, + 'offset': offset + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + + def get_rule(self, + rule_id: str, + *, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Get a rule. + + Retrieves an existing rule and its details. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Rule` object + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_rule') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules/{0}'.format( + *self.encode_path_vars(rule_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers) + + response = self.send(request) + return response + + + def update_rule(self, + rule_id: str, + if_match: str, + name: str, + description: str, + target: 'TargetResource', + required_config: 'RuleRequiredConfig', + enforcement_actions: List['EnforcementAction'], + *, + account_id: str = None, + rule_type: str = None, + labels: List[str] = None, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Update a rule. + + Updates an existing rule based on the properties that you specify. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param str if_match: Compares a supplied `Etag` value with the version that + is stored for the requested resource. If the values match, the server + allows the request method to continue. + To find the `Etag` value, run a GET request on the resource that you want + to modify, and check the response headers. + :param str name: A human-readable alias to assign to your rule. + :param str description: An extended description of your rule. + :param TargetResource target: The properties that describe the resource + that you want to target + with the rule. + :param RuleRequiredConfig required_config: + :param List[EnforcementAction] enforcement_actions: The actions that the + service must run on your behalf when a request to create or modify the + target resource does not comply with your conditions. + :param str account_id: (optional) Your IBM Cloud account ID. + :param str rule_type: (optional) The type of rule. Rules that you create + are `user_defined`. + :param List[str] labels: (optional) Labels that you can use to group and + search for similar rules, such as those that help you to meet a specific + organization guideline. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Rule` object + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + if if_match is None: + raise ValueError('if_match must be provided') + if name is None: + raise ValueError('name must be provided') + if description is None: + raise ValueError('description must be provided') + if target is None: + raise ValueError('target must be provided') + if required_config is None: + raise ValueError('required_config must be provided') + if enforcement_actions is None: + raise ValueError('enforcement_actions must be provided') + target = convert_model(target) + required_config = convert_model(required_config) + enforcement_actions = [convert_model(x) for x in enforcement_actions] + headers = { + 'If-Match': if_match, + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_rule') + headers.update(sdk_headers) + + data = { + 'name': name, + 'description': description, + 'target': target, + 'required_config': required_config, + 'enforcement_actions': enforcement_actions, + 'account_id': account_id, + 'rule_type': rule_type, + 'labels': labels + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules/{0}'.format( + *self.encode_path_vars(rule_id)) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + data=data) + + response = self.send(request) + return response + + + def delete_rule(self, + rule_id: str, + *, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Delete a rule. + + Deletes an existing rule. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_rule') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + url = '/config/v1/rules/{0}'.format( + *self.encode_path_vars(rule_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers) + + response = self.send(request) + return response + + + def create_attachments(self, + rule_id: str, + attachments: List['AttachmentRequest'], + *, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Create attachments. + + Creates one or more scope attachments for an existing rule. + You can attach an existing rule to a scope, such as a specific IBM Cloud account, + to start evaluating the rule for compliance. A successful + `POST /config/v1/rules/{rule_id}/attachments` returns the ID value for the + attachment, along with other metadata. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param List[AttachmentRequest] attachments: + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CreateAttachmentsResponse` object + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + if attachments is None: + raise ValueError('attachments must be provided') + attachments = [convert_model(x) for x in attachments] + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_attachments') + headers.update(sdk_headers) + + data = { + 'attachments': attachments + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules/{0}/attachments'.format( + *self.encode_path_vars(rule_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data) + + response = self.send(request) + return response + + + def list_attachments(self, + rule_id: str, + *, + transaction_id: str = None, + limit: int = None, + offset: int = None, + **kwargs + ) -> DetailedResponse: + """ + List attachments. + + Retrieves a list of scope attachments that are associated with the specified rule. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param int limit: (optional) The number of resources to retrieve. By + default, list operations return the first 100 items. To retrieve a + different set of items, use `limit` with `offset` to page through your + available resources. + **Usage:** If you have 20 rules, and you want to retrieve only the first 5 + rules, use `../rules?account_id={account_id}&limit=5`. + :param int offset: (optional) The number of resources to skip. By + specifying `offset`, you retrieve a subset of resources that starts with + the `offset` value. Use `offset` with `limit` to page through your + available resources. + **Usage:** If you have 100 rules, and you want to retrieve rules 26 through + 50, use `../rules?account_id={account_id}&offset=25&limit=5`. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AttachmentList` object + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_attachments') + headers.update(sdk_headers) + + params = { + 'limit': limit, + 'offset': offset + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules/{0}/attachments'.format( + *self.encode_path_vars(rule_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + + def get_attachment(self, + rule_id: str, + attachment_id: str, + *, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Get an attachment. + + Retrieves an existing scope attachment for a rule. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param str attachment_id: The UUID that uniquely identifies the attachment. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Attachment` object + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + if attachment_id is None: + raise ValueError('attachment_id must be provided') + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_attachment') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules/{0}/attachments/{1}'.format( + *self.encode_path_vars(rule_id, attachment_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers) + + response = self.send(request) + return response + + + def update_attachment(self, + rule_id: str, + attachment_id: str, + if_match: str, + account_id: str, + included_scope: 'RuleScope', + *, + excluded_scopes: List['RuleScope'] = None, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Update an attachment. + + Updates an existing scope attachment based on the properties that you specify. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param str attachment_id: The UUID that uniquely identifies the attachment. + :param str if_match: Compares a supplied `Etag` value with the version that + is stored for the requested resource. If the values match, the server + allows the request method to continue. + To find the `Etag` value, run a GET request on the resource that you want + to modify, and check the response headers. + :param str account_id: Your IBM Cloud account ID. + :param RuleScope included_scope: The extent at which the rule can be + attached across your accounts. + :param List[RuleScope] excluded_scopes: (optional) The extent at which the + rule can be excluded from the included scope. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Attachment` object + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + if attachment_id is None: + raise ValueError('attachment_id must be provided') + if if_match is None: + raise ValueError('if_match must be provided') + if account_id is None: + raise ValueError('account_id must be provided') + if included_scope is None: + raise ValueError('included_scope must be provided') + included_scope = convert_model(included_scope) + if excluded_scopes is not None: + excluded_scopes = [convert_model(x) for x in excluded_scopes] + headers = { + 'If-Match': if_match, + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_attachment') + headers.update(sdk_headers) + + data = { + 'account_id': account_id, + 'included_scope': included_scope, + 'excluded_scopes': excluded_scopes + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/config/v1/rules/{0}/attachments/{1}'.format( + *self.encode_path_vars(rule_id, attachment_id)) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + data=data) + + response = self.send(request) + return response + + + def delete_attachment(self, + rule_id: str, + attachment_id: str, + *, + transaction_id: str = None, + **kwargs + ) -> DetailedResponse: + """ + Delete an attachment. + + Deletes an existing scope attachment. + + :param str rule_id: The UUID that uniquely identifies the rule. + :param str attachment_id: The UUID that uniquely identifies the attachment. + :param str transaction_id: (optional) The unique identifier that is used to + trace an entire request. If you omit this field, the service generates and + sends a transaction ID in the + `trace` field of the response body. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `Transaction-Id` with each request. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if rule_id is None: + raise ValueError('rule_id must be provided') + if attachment_id is None: + raise ValueError('attachment_id must be provided') + headers = { + 'Transaction-Id': transaction_id + } + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_attachment') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + url = '/config/v1/rules/{0}/attachments/{1}'.format( + *self.encode_path_vars(rule_id, attachment_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers) + + response = self.send(request) + return response + + +############################################################################## +# Models +############################################################################## + + +class Attachment(): + """ + The scopes to attach to the rule. + + :attr str attachment_id: The UUID that uniquely identifies the attachment. + :attr str rule_id: The UUID that uniquely identifies the rule. + :attr str account_id: Your IBM Cloud account ID. + :attr RuleScope included_scope: The extent at which the rule can be attached + across your accounts. + :attr List[RuleScope] excluded_scopes: (optional) The extent at which the rule + can be excluded from the included scope. + """ + + def __init__(self, + attachment_id: str, + rule_id: str, + account_id: str, + included_scope: 'RuleScope', + *, + excluded_scopes: List['RuleScope'] = None) -> None: + """ + Initialize a Attachment object. + + :param str attachment_id: The UUID that uniquely identifies the attachment. + :param str rule_id: The UUID that uniquely identifies the rule. + :param str account_id: Your IBM Cloud account ID. + :param RuleScope included_scope: The extent at which the rule can be + attached across your accounts. + :param List[RuleScope] excluded_scopes: (optional) The extent at which the + rule can be excluded from the included scope. + """ + self.attachment_id = attachment_id + self.rule_id = rule_id + self.account_id = account_id + self.included_scope = included_scope + self.excluded_scopes = excluded_scopes + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Attachment': + """Initialize a Attachment object from a json dictionary.""" + args = {} + if 'attachment_id' in _dict: + args['attachment_id'] = _dict.get('attachment_id') + else: + raise ValueError('Required property \'attachment_id\' not present in Attachment JSON') + if 'rule_id' in _dict: + args['rule_id'] = _dict.get('rule_id') + else: + raise ValueError('Required property \'rule_id\' not present in Attachment JSON') + if 'account_id' in _dict: + args['account_id'] = _dict.get('account_id') + else: + raise ValueError('Required property \'account_id\' not present in Attachment JSON') + if 'included_scope' in _dict: + args['included_scope'] = RuleScope.from_dict(_dict.get('included_scope')) + else: + raise ValueError('Required property \'included_scope\' not present in Attachment JSON') + if 'excluded_scopes' in _dict: + args['excluded_scopes'] = [RuleScope.from_dict(x) for x in _dict.get('excluded_scopes')] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Attachment object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'attachment_id') and self.attachment_id is not None: + _dict['attachment_id'] = self.attachment_id + if hasattr(self, 'rule_id') and self.rule_id is not None: + _dict['rule_id'] = self.rule_id + if hasattr(self, 'account_id') and self.account_id is not None: + _dict['account_id'] = self.account_id + if hasattr(self, 'included_scope') and self.included_scope is not None: + _dict['included_scope'] = self.included_scope.to_dict() + if hasattr(self, 'excluded_scopes') and self.excluded_scopes is not None: + _dict['excluded_scopes'] = [x.to_dict() for x in self.excluded_scopes] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Attachment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Attachment') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Attachment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class AttachmentList(): + """ + A list of attachments. + + :attr int offset: The requested offset for the returned items. + :attr int limit: The requested limit for the returned items. + :attr int total_count: The total number of available items. + :attr Link first: The first page of available items. + :attr Link last: The last page of available items. + :attr List[Attachment] attachments: + """ + + def __init__(self, + offset: int, + limit: int, + total_count: int, + first: 'Link', + last: 'Link', + attachments: List['Attachment']) -> None: + """ + Initialize a AttachmentList object. + + :param int offset: The requested offset for the returned items. + :param int limit: The requested limit for the returned items. + :param int total_count: The total number of available items. + :param Link first: The first page of available items. + :param Link last: The last page of available items. + :param List[Attachment] attachments: + """ + self.offset = offset + self.limit = limit + self.total_count = total_count + self.first = first + self.last = last + self.attachments = attachments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AttachmentList': + """Initialize a AttachmentList object from a json dictionary.""" + args = {} + if 'offset' in _dict: + args['offset'] = _dict.get('offset') + else: + raise ValueError('Required property \'offset\' not present in AttachmentList JSON') + if 'limit' in _dict: + args['limit'] = _dict.get('limit') + else: + raise ValueError('Required property \'limit\' not present in AttachmentList JSON') + if 'total_count' in _dict: + args['total_count'] = _dict.get('total_count') + else: + raise ValueError('Required property \'total_count\' not present in AttachmentList JSON') + if 'first' in _dict: + args['first'] = Link.from_dict(_dict.get('first')) + else: + raise ValueError('Required property \'first\' not present in AttachmentList JSON') + if 'last' in _dict: + args['last'] = Link.from_dict(_dict.get('last')) + else: + raise ValueError('Required property \'last\' not present in AttachmentList JSON') + if 'attachments' in _dict: + args['attachments'] = [Attachment.from_dict(x) for x in _dict.get('attachments')] + else: + raise ValueError('Required property \'attachments\' not present in AttachmentList JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AttachmentList object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'offset') and self.offset is not None: + _dict['offset'] = self.offset + if hasattr(self, 'limit') and self.limit is not None: + _dict['limit'] = self.limit + if hasattr(self, 'total_count') and self.total_count is not None: + _dict['total_count'] = self.total_count + if hasattr(self, 'first') and self.first is not None: + _dict['first'] = self.first.to_dict() + if hasattr(self, 'last') and self.last is not None: + _dict['last'] = self.last.to_dict() + if hasattr(self, 'attachments') and self.attachments is not None: + _dict['attachments'] = [x.to_dict() for x in self.attachments] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AttachmentList object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AttachmentList') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AttachmentList') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class AttachmentRequest(): + """ + The scopes to attach to the rule. + + :attr str account_id: Your IBM Cloud account ID. + :attr RuleScope included_scope: The extent at which the rule can be attached + across your accounts. + :attr List[RuleScope] excluded_scopes: (optional) The extent at which the rule + can be excluded from the included scope. + """ + + def __init__(self, + account_id: str, + included_scope: 'RuleScope', + *, + excluded_scopes: List['RuleScope'] = None) -> None: + """ + Initialize a AttachmentRequest object. + + :param str account_id: Your IBM Cloud account ID. + :param RuleScope included_scope: The extent at which the rule can be + attached across your accounts. + :param List[RuleScope] excluded_scopes: (optional) The extent at which the + rule can be excluded from the included scope. + """ + self.account_id = account_id + self.included_scope = included_scope + self.excluded_scopes = excluded_scopes + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AttachmentRequest': + """Initialize a AttachmentRequest object from a json dictionary.""" + args = {} + if 'account_id' in _dict: + args['account_id'] = _dict.get('account_id') + else: + raise ValueError('Required property \'account_id\' not present in AttachmentRequest JSON') + if 'included_scope' in _dict: + args['included_scope'] = RuleScope.from_dict(_dict.get('included_scope')) + else: + raise ValueError('Required property \'included_scope\' not present in AttachmentRequest JSON') + if 'excluded_scopes' in _dict: + args['excluded_scopes'] = [RuleScope.from_dict(x) for x in _dict.get('excluded_scopes')] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AttachmentRequest object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'account_id') and self.account_id is not None: + _dict['account_id'] = self.account_id + if hasattr(self, 'included_scope') and self.included_scope is not None: + _dict['included_scope'] = self.included_scope.to_dict() + if hasattr(self, 'excluded_scopes') and self.excluded_scopes is not None: + _dict['excluded_scopes'] = [x.to_dict() for x in self.excluded_scopes] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AttachmentRequest object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AttachmentRequest') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AttachmentRequest') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class CreateAttachmentsResponse(): + """ + CreateAttachmentsResponse. + + :attr List[Attachment] attachments: + """ + + def __init__(self, + attachments: List['Attachment']) -> None: + """ + Initialize a CreateAttachmentsResponse object. + + :param List[Attachment] attachments: + """ + self.attachments = attachments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateAttachmentsResponse': + """Initialize a CreateAttachmentsResponse object from a json dictionary.""" + args = {} + if 'attachments' in _dict: + args['attachments'] = [Attachment.from_dict(x) for x in _dict.get('attachments')] + else: + raise ValueError('Required property \'attachments\' not present in CreateAttachmentsResponse JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateAttachmentsResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'attachments') and self.attachments is not None: + _dict['attachments'] = [x.to_dict() for x in self.attachments] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CreateAttachmentsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateAttachmentsResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateAttachmentsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class CreateRuleRequest(): + """ + A rule to be created. + + :attr str request_id: (optional) A field that you can use in bulk operations to + store a custom identifier for an individual request. If you omit this field, the + service generates and sends a `request_id` string for each new rule. The + generated string corresponds with the numerical order of the rules request + array. For example, `"request_id": "1"`, `"request_id": "2"`. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `request_id` with each request. + :attr RuleRequest rule: User-settable properties associated with a rule to be + created or updated. + """ + + def __init__(self, + rule: 'RuleRequest', + *, + request_id: str = None) -> None: + """ + Initialize a CreateRuleRequest object. + + :param RuleRequest rule: User-settable properties associated with a rule to + be created or updated. + :param str request_id: (optional) A field that you can use in bulk + operations to store a custom identifier for an individual request. If you + omit this field, the service generates and sends a `request_id` string for + each new rule. The generated string corresponds with the numerical order of + the rules request array. For example, `"request_id": "1"`, `"request_id": + "2"`. + **Note:** To help with debugging logs, it is strongly recommended that you + generate and supply a `request_id` with each request. + """ + self.request_id = request_id + self.rule = rule + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateRuleRequest': + """Initialize a CreateRuleRequest object from a json dictionary.""" + args = {} + if 'request_id' in _dict: + args['request_id'] = _dict.get('request_id') + if 'rule' in _dict: + args['rule'] = RuleRequest.from_dict(_dict.get('rule')) + else: + raise ValueError('Required property \'rule\' not present in CreateRuleRequest JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateRuleRequest object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'request_id') and self.request_id is not None: + _dict['request_id'] = self.request_id + if hasattr(self, 'rule') and self.rule is not None: + _dict['rule'] = self.rule.to_dict() + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CreateRuleRequest object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateRuleRequest') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateRuleRequest') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class CreateRuleResponse(): + """ + Response information for a rule request. + If the 'status_code' property indicates success, the 'request_id' and 'rule' + properties will be present. If the 'status_code' property indicates an error, the + 'request_id', 'errors', and 'trace' fields will be present. + + :attr str request_id: (optional) The identifier that is used to correlate an + individual request. + To assist with debugging, you can use this ID to identify and inspect only one + request that was made as part of a bulk operation. + :attr int status_code: (optional) The HTTP response status code. + :attr Rule rule: (optional) Information about a newly-created rule. + This field will be present for a successful request. + :attr List[RuleResponseError] errors: (optional) The error contents of the + multi-status response. + This field will be present for a failed rule request. + :attr str trace: (optional) The UUID that uniquely identifies the request. + This field will be present for a failed rule request. + """ + + def __init__(self, + *, + request_id: str = None, + status_code: int = None, + rule: 'Rule' = None, + errors: List['RuleResponseError'] = None, + trace: str = None) -> None: + """ + Initialize a CreateRuleResponse object. + + :param str request_id: (optional) The identifier that is used to correlate + an individual request. + To assist with debugging, you can use this ID to identify and inspect only + one request that was made as part of a bulk operation. + :param int status_code: (optional) The HTTP response status code. + :param Rule rule: (optional) Information about a newly-created rule. + This field will be present for a successful request. + :param List[RuleResponseError] errors: (optional) The error contents of the + multi-status response. + This field will be present for a failed rule request. + :param str trace: (optional) The UUID that uniquely identifies the request. + This field will be present for a failed rule request. + """ + self.request_id = request_id + self.status_code = status_code + self.rule = rule + self.errors = errors + self.trace = trace + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateRuleResponse': + """Initialize a CreateRuleResponse object from a json dictionary.""" + args = {} + if 'request_id' in _dict: + args['request_id'] = _dict.get('request_id') + if 'status_code' in _dict: + args['status_code'] = _dict.get('status_code') + if 'rule' in _dict: + args['rule'] = Rule.from_dict(_dict.get('rule')) + if 'errors' in _dict: + args['errors'] = [RuleResponseError.from_dict(x) for x in _dict.get('errors')] + if 'trace' in _dict: + args['trace'] = _dict.get('trace') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateRuleResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'request_id') and self.request_id is not None: + _dict['request_id'] = self.request_id + if hasattr(self, 'status_code') and self.status_code is not None: + _dict['status_code'] = self.status_code + if hasattr(self, 'rule') and self.rule is not None: + _dict['rule'] = self.rule.to_dict() + if hasattr(self, 'errors') and self.errors is not None: + _dict['errors'] = [x.to_dict() for x in self.errors] + if hasattr(self, 'trace') and self.trace is not None: + _dict['trace'] = self.trace + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CreateRuleResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateRuleResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateRuleResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class CreateRulesResponse(): + """ + The response associated with a request to create one or more rules. + + :attr List[CreateRuleResponse] rules: An array of rule responses. + """ + + def __init__(self, + rules: List['CreateRuleResponse']) -> None: + """ + Initialize a CreateRulesResponse object. + + :param List[CreateRuleResponse] rules: An array of rule responses. + """ + self.rules = rules + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateRulesResponse': + """Initialize a CreateRulesResponse object from a json dictionary.""" + args = {} + if 'rules' in _dict: + args['rules'] = [CreateRuleResponse.from_dict(x) for x in _dict.get('rules')] + else: + raise ValueError('Required property \'rules\' not present in CreateRulesResponse JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateRulesResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'rules') and self.rules is not None: + _dict['rules'] = [x.to_dict() for x in self.rules] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this CreateRulesResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateRulesResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateRulesResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class EnforcementAction(): + """ + EnforcementAction. + + :attr str action: To block a request from completing, use `disallow`. To log the + request to Activity Tracker with LogDNA, use `audit_log`. + """ + + def __init__(self, + action: str) -> None: + """ + Initialize a EnforcementAction object. + + :param str action: To block a request from completing, use `disallow`. To + log the request to Activity Tracker with LogDNA, use `audit_log`. + """ + self.action = action + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnforcementAction': + """Initialize a EnforcementAction object from a json dictionary.""" + args = {} + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError('Required property \'action\' not present in EnforcementAction JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnforcementAction object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this EnforcementAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnforcementAction') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'EnforcementAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ActionEnum(str, Enum): + """ + To block a request from completing, use `disallow`. To log the request to + Activity Tracker with LogDNA, use `audit_log`. + """ + AUDIT_LOG = 'audit_log' + DISALLOW = 'disallow' + + +class Link(): + """ + A link that is used to paginate through available resources. + + :attr str href: The URL for the first, previous, next, or last page of + resources. + """ + + def __init__(self, + href: str) -> None: + """ + Initialize a Link object. + + :param str href: The URL for the first, previous, next, or last page of + resources. + """ + self.href = href + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Link': + """Initialize a Link object from a json dictionary.""" + args = {} + if 'href' in _dict: + args['href'] = _dict.get('href') + else: + raise ValueError('Required property \'href\' not present in Link JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Link object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'href') and self.href is not None: + _dict['href'] = self.href + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Link object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Link') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Link') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class Rule(): + """ + Properties associated with a rule, including both user-settable and server-populated + properties. + + :attr str account_id: (optional) Your IBM Cloud account ID. + :attr str name: A human-readable alias to assign to your rule. + :attr str description: An extended description of your rule. + :attr str rule_type: (optional) The type of rule. Rules that you create are + `user_defined`. + :attr TargetResource target: The properties that describe the resource that you + want to target + with the rule. + :attr RuleRequiredConfig required_config: + :attr List[EnforcementAction] enforcement_actions: The actions that the service + must run on your behalf when a request to create or modify the target resource + does not comply with your conditions. + :attr List[str] labels: (optional) Labels that you can use to group and search + for similar rules, such as those that help you to meet a specific organization + guideline. + :attr str rule_id: (optional) The UUID that uniquely identifies the rule. + :attr str creation_date: (optional) The date the resource was created. + :attr str created_by: (optional) The unique identifier for the user or + application that created the resource. + :attr str modification_date: (optional) The date the resource was last modified. + :attr str modified_by: (optional) The unique identifier for the user or + application that last modified the resource. + :attr int number_of_attachments: (optional) The number of scope attachments that + are associated with the rule. + """ + + def __init__(self, + name: str, + description: str, + target: 'TargetResource', + required_config: 'RuleRequiredConfig', + enforcement_actions: List['EnforcementAction'], + *, + account_id: str = None, + rule_type: str = None, + labels: List[str] = None, + rule_id: str = None, + creation_date: str = None, + created_by: str = None, + modification_date: str = None, + modified_by: str = None, + number_of_attachments: int = None) -> None: + """ + Initialize a Rule object. + + :param str name: A human-readable alias to assign to your rule. + :param str description: An extended description of your rule. + :param TargetResource target: The properties that describe the resource + that you want to target + with the rule. + :param RuleRequiredConfig required_config: + :param List[EnforcementAction] enforcement_actions: The actions that the + service must run on your behalf when a request to create or modify the + target resource does not comply with your conditions. + :param str account_id: (optional) Your IBM Cloud account ID. + :param str rule_type: (optional) The type of rule. Rules that you create + are `user_defined`. + :param List[str] labels: (optional) Labels that you can use to group and + search for similar rules, such as those that help you to meet a specific + organization guideline. + """ + self.account_id = account_id + self.name = name + self.description = description + self.rule_type = rule_type + self.target = target + self.required_config = required_config + self.enforcement_actions = enforcement_actions + self.labels = labels + self.rule_id = rule_id + self.creation_date = creation_date + self.created_by = created_by + self.modification_date = modification_date + self.modified_by = modified_by + self.number_of_attachments = number_of_attachments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Rule': + """Initialize a Rule object from a json dictionary.""" + args = {} + if 'account_id' in _dict: + args['account_id'] = _dict.get('account_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError('Required property \'name\' not present in Rule JSON') + if 'description' in _dict: + args['description'] = _dict.get('description') + else: + raise ValueError('Required property \'description\' not present in Rule JSON') + if 'rule_type' in _dict: + args['rule_type'] = _dict.get('rule_type') + if 'target' in _dict: + args['target'] = TargetResource.from_dict(_dict.get('target')) + else: + raise ValueError('Required property \'target\' not present in Rule JSON') + if 'required_config' in _dict: + args['required_config'] = _dict.get('required_config') + else: + raise ValueError('Required property \'required_config\' not present in Rule JSON') + if 'enforcement_actions' in _dict: + args['enforcement_actions'] = [EnforcementAction.from_dict(x) for x in _dict.get('enforcement_actions')] + else: + raise ValueError('Required property \'enforcement_actions\' not present in Rule JSON') + if 'labels' in _dict: + args['labels'] = _dict.get('labels') + if 'rule_id' in _dict: + args['rule_id'] = _dict.get('rule_id') + if 'creation_date' in _dict: + args['creation_date'] = _dict.get('creation_date') + if 'created_by' in _dict: + args['created_by'] = _dict.get('created_by') + if 'modification_date' in _dict: + args['modification_date'] = _dict.get('modification_date') + if 'modified_by' in _dict: + args['modified_by'] = _dict.get('modified_by') + if 'number_of_attachments' in _dict: + args['number_of_attachments'] = _dict.get('number_of_attachments') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Rule object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'account_id') and self.account_id is not None: + _dict['account_id'] = self.account_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'rule_type') and self.rule_type is not None: + _dict['rule_type'] = self.rule_type + if hasattr(self, 'target') and self.target is not None: + _dict['target'] = self.target.to_dict() + if hasattr(self, 'required_config') and self.required_config is not None: + if isinstance(self.required_config, dict): + _dict['required_config'] = self.required_config + else: + _dict['required_config'] = self.required_config.to_dict() + if hasattr(self, 'enforcement_actions') and self.enforcement_actions is not None: + _dict['enforcement_actions'] = [x.to_dict() for x in self.enforcement_actions] + if hasattr(self, 'labels') and self.labels is not None: + _dict['labels'] = self.labels + if hasattr(self, 'rule_id') and getattr(self, 'rule_id') is not None: + _dict['rule_id'] = getattr(self, 'rule_id') + if hasattr(self, 'creation_date') and getattr(self, 'creation_date') is not None: + _dict['creation_date'] = getattr(self, 'creation_date') + if hasattr(self, 'created_by') and getattr(self, 'created_by') is not None: + _dict['created_by'] = getattr(self, 'created_by') + if hasattr(self, 'modification_date') and getattr(self, 'modification_date') is not None: + _dict['modification_date'] = getattr(self, 'modification_date') + if hasattr(self, 'modified_by') and getattr(self, 'modified_by') is not None: + _dict['modified_by'] = getattr(self, 'modified_by') + if hasattr(self, 'number_of_attachments') and getattr(self, 'number_of_attachments') is not None: + _dict['number_of_attachments'] = getattr(self, 'number_of_attachments') + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this Rule object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Rule') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Rule') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuleTypeEnum(str, Enum): + """ + The type of rule. Rules that you create are `user_defined`. + """ + USER_DEFINED = 'user_defined' + + +class RuleCondition(): + """ + RuleCondition. + + """ + + def __init__(self) -> None: + """ + Initialize a RuleCondition object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join(['RuleConditionSingleProperty', 'RuleConditionOrLvl2', 'RuleConditionAndLvl2'])) + raise Exception(msg) + +class RuleList(): + """ + A list of rules. + + :attr int offset: The requested offset for the returned items. + :attr int limit: The requested limit for the returned items. + :attr int total_count: The total number of available items. + :attr Link first: The first page of available items. + :attr Link last: The last page of available items. + :attr List[Rule] rules: An array of rules. + """ + + def __init__(self, + offset: int, + limit: int, + total_count: int, + first: 'Link', + last: 'Link', + rules: List['Rule']) -> None: + """ + Initialize a RuleList object. + + :param int offset: The requested offset for the returned items. + :param int limit: The requested limit for the returned items. + :param int total_count: The total number of available items. + :param Link first: The first page of available items. + :param Link last: The last page of available items. + :param List[Rule] rules: An array of rules. + """ + self.offset = offset + self.limit = limit + self.total_count = total_count + self.first = first + self.last = last + self.rules = rules + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleList': + """Initialize a RuleList object from a json dictionary.""" + args = {} + if 'offset' in _dict: + args['offset'] = _dict.get('offset') + else: + raise ValueError('Required property \'offset\' not present in RuleList JSON') + if 'limit' in _dict: + args['limit'] = _dict.get('limit') + else: + raise ValueError('Required property \'limit\' not present in RuleList JSON') + if 'total_count' in _dict: + args['total_count'] = _dict.get('total_count') + else: + raise ValueError('Required property \'total_count\' not present in RuleList JSON') + if 'first' in _dict: + args['first'] = Link.from_dict(_dict.get('first')) + else: + raise ValueError('Required property \'first\' not present in RuleList JSON') + if 'last' in _dict: + args['last'] = Link.from_dict(_dict.get('last')) + else: + raise ValueError('Required property \'last\' not present in RuleList JSON') + if 'rules' in _dict: + args['rules'] = [Rule.from_dict(x) for x in _dict.get('rules')] + else: + raise ValueError('Required property \'rules\' not present in RuleList JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleList object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'offset') and self.offset is not None: + _dict['offset'] = self.offset + if hasattr(self, 'limit') and self.limit is not None: + _dict['limit'] = self.limit + if hasattr(self, 'total_count') and self.total_count is not None: + _dict['total_count'] = self.total_count + if hasattr(self, 'first') and self.first is not None: + _dict['first'] = self.first.to_dict() + if hasattr(self, 'last') and self.last is not None: + _dict['last'] = self.last.to_dict() + if hasattr(self, 'rules') and self.rules is not None: + _dict['rules'] = [x.to_dict() for x in self.rules] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleList object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleList') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleList') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class RuleRequest(): + """ + User-settable properties associated with a rule to be created or updated. + + :attr str account_id: (optional) Your IBM Cloud account ID. + :attr str name: A human-readable alias to assign to your rule. + :attr str description: An extended description of your rule. + :attr str rule_type: (optional) The type of rule. Rules that you create are + `user_defined`. + :attr TargetResource target: The properties that describe the resource that you + want to target + with the rule. + :attr RuleRequiredConfig required_config: + :attr List[EnforcementAction] enforcement_actions: The actions that the service + must run on your behalf when a request to create or modify the target resource + does not comply with your conditions. + :attr List[str] labels: (optional) Labels that you can use to group and search + for similar rules, such as those that help you to meet a specific organization + guideline. + """ + + def __init__(self, + name: str, + description: str, + target: 'TargetResource', + required_config: 'RuleRequiredConfig', + enforcement_actions: List['EnforcementAction'], + *, + account_id: str = None, + rule_type: str = None, + labels: List[str] = None) -> None: + """ + Initialize a RuleRequest object. + + :param str name: A human-readable alias to assign to your rule. + :param str description: An extended description of your rule. + :param TargetResource target: The properties that describe the resource + that you want to target + with the rule. + :param RuleRequiredConfig required_config: + :param List[EnforcementAction] enforcement_actions: The actions that the + service must run on your behalf when a request to create or modify the + target resource does not comply with your conditions. + :param str account_id: (optional) Your IBM Cloud account ID. + :param str rule_type: (optional) The type of rule. Rules that you create + are `user_defined`. + :param List[str] labels: (optional) Labels that you can use to group and + search for similar rules, such as those that help you to meet a specific + organization guideline. + """ + self.account_id = account_id + self.name = name + self.description = description + self.rule_type = rule_type + self.target = target + self.required_config = required_config + self.enforcement_actions = enforcement_actions + self.labels = labels + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleRequest': + """Initialize a RuleRequest object from a json dictionary.""" + args = {} + if 'account_id' in _dict: + args['account_id'] = _dict.get('account_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError('Required property \'name\' not present in RuleRequest JSON') + if 'description' in _dict: + args['description'] = _dict.get('description') + else: + raise ValueError('Required property \'description\' not present in RuleRequest JSON') + if 'rule_type' in _dict: + args['rule_type'] = _dict.get('rule_type') + if 'target' in _dict: + args['target'] = TargetResource.from_dict(_dict.get('target')) + else: + raise ValueError('Required property \'target\' not present in RuleRequest JSON') + if 'required_config' in _dict: + args['required_config'] = _dict.get('required_config') + else: + raise ValueError('Required property \'required_config\' not present in RuleRequest JSON') + if 'enforcement_actions' in _dict: + args['enforcement_actions'] = [EnforcementAction.from_dict(x) for x in _dict.get('enforcement_actions')] + else: + raise ValueError('Required property \'enforcement_actions\' not present in RuleRequest JSON') + if 'labels' in _dict: + args['labels'] = _dict.get('labels') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleRequest object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'account_id') and self.account_id is not None: + _dict['account_id'] = self.account_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'rule_type') and self.rule_type is not None: + _dict['rule_type'] = self.rule_type + if hasattr(self, 'target') and self.target is not None: + _dict['target'] = self.target.to_dict() + if hasattr(self, 'required_config') and self.required_config is not None: + if isinstance(self.required_config, dict): + _dict['required_config'] = self.required_config + else: + _dict['required_config'] = self.required_config.to_dict() + if hasattr(self, 'enforcement_actions') and self.enforcement_actions is not None: + _dict['enforcement_actions'] = [x.to_dict() for x in self.enforcement_actions] + if hasattr(self, 'labels') and self.labels is not None: + _dict['labels'] = self.labels + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleRequest object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleRequest') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleRequest') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuleTypeEnum(str, Enum): + """ + The type of rule. Rules that you create are `user_defined`. + """ + USER_DEFINED = 'user_defined' + + +class RuleRequiredConfig(): + """ + RuleRequiredConfig. + + """ + + def __init__(self) -> None: + """ + Initialize a RuleRequiredConfig object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join(['RuleRequiredConfigSingleProperty', 'RuleRequiredConfigMultipleProperties'])) + raise Exception(msg) + +class RuleResponseError(): + """ + RuleResponseError. + + :attr str code: Specifies the problem that caused the error. + :attr str message: Describes the problem. + """ + + def __init__(self, + code: str, + message: str) -> None: + """ + Initialize a RuleResponseError object. + + :param str code: Specifies the problem that caused the error. + :param str message: Describes the problem. + """ + self.code = code + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleResponseError': + """Initialize a RuleResponseError object from a json dictionary.""" + args = {} + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError('Required property \'code\' not present in RuleResponseError JSON') + if 'message' in _dict: + args['message'] = _dict.get('message') + else: + raise ValueError('Required property \'message\' not present in RuleResponseError JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleResponseError object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleResponseError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleResponseError') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleResponseError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class RuleScope(): + """ + The extent at which the rule can be attached across your accounts. + + :attr str note: (optional) A short description or alias to assign to the scope. + :attr str scope_id: The ID of the scope, such as an enterprise, account, or + account group, that you want to evaluate. + :attr str scope_type: The type of scope that you want to evaluate. + """ + + def __init__(self, + scope_id: str, + scope_type: str, + *, + note: str = None) -> None: + """ + Initialize a RuleScope object. + + :param str scope_id: The ID of the scope, such as an enterprise, account, + or account group, that you want to evaluate. + :param str scope_type: The type of scope that you want to evaluate. + :param str note: (optional) A short description or alias to assign to the + scope. + """ + self.note = note + self.scope_id = scope_id + self.scope_type = scope_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleScope': + """Initialize a RuleScope object from a json dictionary.""" + args = {} + if 'note' in _dict: + args['note'] = _dict.get('note') + if 'scope_id' in _dict: + args['scope_id'] = _dict.get('scope_id') + else: + raise ValueError('Required property \'scope_id\' not present in RuleScope JSON') + if 'scope_type' in _dict: + args['scope_type'] = _dict.get('scope_type') + else: + raise ValueError('Required property \'scope_type\' not present in RuleScope JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleScope object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'note') and self.note is not None: + _dict['note'] = self.note + if hasattr(self, 'scope_id') and self.scope_id is not None: + _dict['scope_id'] = self.scope_id + if hasattr(self, 'scope_type') and self.scope_type is not None: + _dict['scope_type'] = self.scope_type + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleScope object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleScope') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleScope') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ScopeTypeEnum(str, Enum): + """ + The type of scope that you want to evaluate. + """ + ENTERPRISE = 'enterprise' + ENTERPRISE_ACCOUNT_GROUP = 'enterprise.account_group' + ENTERPRISE_ACCOUNT = 'enterprise.account' + ACCOUNT = 'account' + ACCOUNT_RESOURCE_GROUP = 'account.resource_group' + + +class RuleSingleProperty(): + """ + The requirement that must be met to determine the resource's level of compliance in + accordance with the rule. + To apply a single property check, define a configuration property and the desired + value that you want to check against. + + :attr str description: (optional) + :attr str property: A resource configuration variable that describes the + property that you want to apply to the target resource. + Available options depend on the target service and resource. Currently, + `public_access_enabled` is supported. + :attr str operator: The way in which the `property` field is compared to its + value. + There are three types of operators: string, numeric, and boolean. + :attr str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + + def __init__(self, + property: str, + operator: str, + *, + description: str = None, + value: str = None) -> None: + """ + Initialize a RuleSingleProperty object. + + :param str property: A resource configuration variable that describes the + property that you want to apply to the target resource. + Available options depend on the target service and resource. Currently, + `public_access_enabled` is supported. + :param str operator: The way in which the `property` field is compared to + its value. + There are three types of operators: string, numeric, and boolean. + :param str description: (optional) + :param str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + self.description = description + self.property = property + self.operator = operator + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleSingleProperty': + """Initialize a RuleSingleProperty object from a json dictionary.""" + args = {} + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'property' in _dict: + args['property'] = _dict.get('property') + else: + raise ValueError('Required property \'property\' not present in RuleSingleProperty JSON') + if 'operator' in _dict: + args['operator'] = _dict.get('operator') + else: + raise ValueError('Required property \'operator\' not present in RuleSingleProperty JSON') + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleSingleProperty object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'property') and self.property is not None: + _dict['property'] = self.property + if hasattr(self, 'operator') and self.operator is not None: + _dict['operator'] = self.operator + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleSingleProperty object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleSingleProperty') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleSingleProperty') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OperatorEnum(str, Enum): + """ + The way in which the `property` field is compared to its value. + There are three types of operators: string, numeric, and boolean. + """ + IS_TRUE = 'is_true' + IS_FALSE = 'is_false' + IS_EMPTY = 'is_empty' + IS_NOT_EMPTY = 'is_not_empty' + STRING_EQUALS = 'string_equals' + STRING_NOT_EQUALS = 'string_not_equals' + STRING_MATCH = 'string_match' + STRING_NOT_MATCH = 'string_not_match' + NUM_EQUALS = 'num_equals' + NUM_NOT_EQUALS = 'num_not_equals' + NUM_LESS_THAN = 'num_less_than' + NUM_LESS_THAN_EQUALS = 'num_less_than_equals' + NUM_GREATER_THAN = 'num_greater_than' + NUM_GREATER_THAN_EQUALS = 'num_greater_than_equals' + + +class RuleTargetAttribute(): + """ + The attributes that are associated with a rule target. + + :attr str name: + :attr str operator: The way in which the `name` field is compared to its value. + There are three types of operators: string, numeric, and boolean. + :attr str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + + def __init__(self, + name: str, + operator: str, + *, + value: str = None) -> None: + """ + Initialize a RuleTargetAttribute object. + + :param str name: + :param str operator: The way in which the `name` field is compared to its + value. + There are three types of operators: string, numeric, and boolean. + :param str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + self.name = name + self.operator = operator + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleTargetAttribute': + """Initialize a RuleTargetAttribute object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError('Required property \'name\' not present in RuleTargetAttribute JSON') + if 'operator' in _dict: + args['operator'] = _dict.get('operator') + else: + raise ValueError('Required property \'operator\' not present in RuleTargetAttribute JSON') + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleTargetAttribute object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'operator') and self.operator is not None: + _dict['operator'] = self.operator + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleTargetAttribute object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleTargetAttribute') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleTargetAttribute') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OperatorEnum(str, Enum): + """ + The way in which the `name` field is compared to its value. + There are three types of operators: string, numeric, and boolean. + """ + STRING_EQUALS = 'string_equals' + STRING_NOT_EQUALS = 'string_not_equals' + STRING_MATCH = 'string_match' + STRING_NOT_MATCH = 'string_not_match' + NUM_EQUALS = 'num_equals' + NUM_NOT_EQUALS = 'num_not_equals' + NUM_LESS_THAN = 'num_less_than' + NUM_LESS_THAN_EQUALS = 'num_less_than_equals' + NUM_GREATER_THAN = 'num_greater_than' + NUM_GREATER_THAN_EQUALS = 'num_greater_than_equals' + IS_EMPTY = 'is_empty' + IS_NOT_EMPTY = 'is_not_empty' + IS_TRUE = 'is_true' + IS_FALSE = 'is_false' + + +class TargetResource(): + """ + The properties that describe the resource that you want to target with the rule. + + :attr str service_name: The programmatic name of the IBM Cloud service that you + want to target with the rule. Currently, `iam-groups` is supported. + :attr str resource_kind: The type of resource that you want to target. + :attr List[RuleTargetAttribute] additional_target_attributes: (optional) An + extra qualifier for the resource kind. When you include additional attributes, + only the resources that match the definition are included in the + rule. + """ + + def __init__(self, + service_name: str, + resource_kind: str, + *, + additional_target_attributes: List['RuleTargetAttribute'] = None) -> None: + """ + Initialize a TargetResource object. + + :param str service_name: The programmatic name of the IBM Cloud service + that you want to target with the rule. Currently, `iam-groups` is + supported. + :param str resource_kind: The type of resource that you want to target. + :param List[RuleTargetAttribute] additional_target_attributes: (optional) + An extra qualifier for the resource kind. When you include additional + attributes, only the resources that match the definition are + included in the rule. + """ + self.service_name = service_name + self.resource_kind = resource_kind + self.additional_target_attributes = additional_target_attributes + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TargetResource': + """Initialize a TargetResource object from a json dictionary.""" + args = {} + if 'service_name' in _dict: + args['service_name'] = _dict.get('service_name') + else: + raise ValueError('Required property \'service_name\' not present in TargetResource JSON') + if 'resource_kind' in _dict: + args['resource_kind'] = _dict.get('resource_kind') + else: + raise ValueError('Required property \'resource_kind\' not present in TargetResource JSON') + if 'additional_target_attributes' in _dict: + args['additional_target_attributes'] = [RuleTargetAttribute.from_dict(x) for x in _dict.get('additional_target_attributes')] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TargetResource object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'service_name') and self.service_name is not None: + _dict['service_name'] = self.service_name + if hasattr(self, 'resource_kind') and self.resource_kind is not None: + _dict['resource_kind'] = self.resource_kind + if hasattr(self, 'additional_target_attributes') and self.additional_target_attributes is not None: + _dict['additional_target_attributes'] = [x.to_dict() for x in self.additional_target_attributes] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this TargetResource object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TargetResource') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'TargetResource') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class RuleConditionAndLvl2(RuleCondition): + """ + A condition with the `and` logical operator. + + :attr str description: (optional) + :attr List[RuleSingleProperty] and_: + """ + + def __init__(self, + and_: List['RuleSingleProperty'], + *, + description: str = None) -> None: + """ + Initialize a RuleConditionAndLvl2 object. + + :param List[RuleSingleProperty] and_: + :param str description: (optional) + """ + # pylint: disable=super-init-not-called + self.description = description + self.and_ = and_ + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleConditionAndLvl2': + """Initialize a RuleConditionAndLvl2 object from a json dictionary.""" + args = {} + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'and' in _dict: + args['and_'] = [RuleSingleProperty.from_dict(x) for x in _dict.get('and')] + else: + raise ValueError('Required property \'and\' not present in RuleConditionAndLvl2 JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleConditionAndLvl2 object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'and_') and self.and_ is not None: + _dict['and'] = [x.to_dict() for x in self.and_] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleConditionAndLvl2 object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleConditionAndLvl2') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleConditionAndLvl2') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class RuleConditionOrLvl2(RuleCondition): + """ + A condition with the `or` logical operator. + + :attr str description: (optional) + :attr List[RuleSingleProperty] or_: + """ + + def __init__(self, + or_: List['RuleSingleProperty'], + *, + description: str = None) -> None: + """ + Initialize a RuleConditionOrLvl2 object. + + :param List[RuleSingleProperty] or_: + :param str description: (optional) + """ + # pylint: disable=super-init-not-called + self.description = description + self.or_ = or_ + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleConditionOrLvl2': + """Initialize a RuleConditionOrLvl2 object from a json dictionary.""" + args = {} + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'or' in _dict: + args['or_'] = [RuleSingleProperty.from_dict(x) for x in _dict.get('or')] + else: + raise ValueError('Required property \'or\' not present in RuleConditionOrLvl2 JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleConditionOrLvl2 object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'or_') and self.or_ is not None: + _dict['or'] = [x.to_dict() for x in self.or_] + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleConditionOrLvl2 object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleConditionOrLvl2') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleConditionOrLvl2') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class RuleConditionSingleProperty(RuleCondition): + """ + The requirement that must be met to determine the resource's level of compliance in + accordance with the rule. + To apply a single property check, define a configuration property and the desired + value that you want to check against. + + :attr str description: (optional) + :attr str property: A resource configuration variable that describes the + property that you want to apply to the target resource. + Available options depend on the target service and resource. Currently, + `public_access_enabled` is supported. + :attr str operator: The way in which the `property` field is compared to its + value. + There are three types of operators: string, numeric, and boolean. + :attr str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + + def __init__(self, + property: str, + operator: str, + *, + description: str = None, + value: str = None) -> None: + """ + Initialize a RuleConditionSingleProperty object. + + :param str property: A resource configuration variable that describes the + property that you want to apply to the target resource. + Available options depend on the target service and resource. Currently, + `public_access_enabled` is supported. + :param str operator: The way in which the `property` field is compared to + its value. + There are three types of operators: string, numeric, and boolean. + :param str description: (optional) + :param str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + # pylint: disable=super-init-not-called + self.description = description + self.property = property + self.operator = operator + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleConditionSingleProperty': + """Initialize a RuleConditionSingleProperty object from a json dictionary.""" + args = {} + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'property' in _dict: + args['property'] = _dict.get('property') + else: + raise ValueError('Required property \'property\' not present in RuleConditionSingleProperty JSON') + if 'operator' in _dict: + args['operator'] = _dict.get('operator') + else: + raise ValueError('Required property \'operator\' not present in RuleConditionSingleProperty JSON') + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleConditionSingleProperty object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'property') and self.property is not None: + _dict['property'] = self.property + if hasattr(self, 'operator') and self.operator is not None: + _dict['operator'] = self.operator + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleConditionSingleProperty object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleConditionSingleProperty') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleConditionSingleProperty') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OperatorEnum(str, Enum): + """ + The way in which the `property` field is compared to its value. + There are three types of operators: string, numeric, and boolean. + """ + IS_TRUE = 'is_true' + IS_FALSE = 'is_false' + IS_EMPTY = 'is_empty' + IS_NOT_EMPTY = 'is_not_empty' + STRING_EQUALS = 'string_equals' + STRING_NOT_EQUALS = 'string_not_equals' + STRING_MATCH = 'string_match' + STRING_NOT_MATCH = 'string_not_match' + NUM_EQUALS = 'num_equals' + NUM_NOT_EQUALS = 'num_not_equals' + NUM_LESS_THAN = 'num_less_than' + NUM_LESS_THAN_EQUALS = 'num_less_than_equals' + NUM_GREATER_THAN = 'num_greater_than' + NUM_GREATER_THAN_EQUALS = 'num_greater_than_equals' + + +class RuleRequiredConfigMultipleProperties(RuleRequiredConfig): + """ + The requirements that must be met to determine the resource's level of compliance in + accordance with the rule. + Use logical operators (`and`/`or`) to define multiple property checks and conditions. + To define requirements for a rule, list one or more property check objects in the + `and` array. To add conditions to a property check, use `or`. + + """ + + def __init__(self) -> None: + """ + Initialize a RuleRequiredConfigMultipleProperties object. + + """ + # pylint: disable=super-init-not-called + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join(['RuleRequiredConfigMultiplePropertiesConditionOr', 'RuleRequiredConfigMultiplePropertiesConditionAnd'])) + raise Exception(msg) + +class RuleRequiredConfigSingleProperty(RuleRequiredConfig): + """ + The requirement that must be met to determine the resource's level of compliance in + accordance with the rule. + To apply a single property check, define a configuration property and the desired + value that you want to check against. + + :attr str description: (optional) + :attr str property: A resource configuration variable that describes the + property that you want to apply to the target resource. + Available options depend on the target service and resource. Currently, + `public_access_enabled` is supported. + :attr str operator: The way in which the `property` field is compared to its + value. + There are three types of operators: string, numeric, and boolean. + :attr str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + + def __init__(self, + property: str, + operator: str, + *, + description: str = None, + value: str = None) -> None: + """ + Initialize a RuleRequiredConfigSingleProperty object. + + :param str property: A resource configuration variable that describes the + property that you want to apply to the target resource. + Available options depend on the target service and resource. Currently, + `public_access_enabled` is supported. + :param str operator: The way in which the `property` field is compared to + its value. + There are three types of operators: string, numeric, and boolean. + :param str description: (optional) + :param str value: (optional) The way in which you want your property to be + applied. + Value options differ depending on the rule that you configure. If you use a + boolean operator, you do not need to input a value. + """ + # pylint: disable=super-init-not-called + self.description = description + self.property = property + self.operator = operator + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleRequiredConfigSingleProperty': + """Initialize a RuleRequiredConfigSingleProperty object from a json dictionary.""" + args = {} + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'property' in _dict: + args['property'] = _dict.get('property') + else: + raise ValueError('Required property \'property\' not present in RuleRequiredConfigSingleProperty JSON') + if 'operator' in _dict: + args['operator'] = _dict.get('operator') + else: + raise ValueError('Required property \'operator\' not present in RuleRequiredConfigSingleProperty JSON') + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleRequiredConfigSingleProperty object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'property') and self.property is not None: + _dict['property'] = self.property + if hasattr(self, 'operator') and self.operator is not None: + _dict['operator'] = self.operator + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleRequiredConfigSingleProperty object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleRequiredConfigSingleProperty') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleRequiredConfigSingleProperty') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OperatorEnum(str, Enum): + """ + The way in which the `property` field is compared to its value. + There are three types of operators: string, numeric, and boolean. + """ + IS_TRUE = 'is_true' + IS_FALSE = 'is_false' + IS_EMPTY = 'is_empty' + IS_NOT_EMPTY = 'is_not_empty' + STRING_EQUALS = 'string_equals' + STRING_NOT_EQUALS = 'string_not_equals' + STRING_MATCH = 'string_match' + STRING_NOT_MATCH = 'string_not_match' + NUM_EQUALS = 'num_equals' + NUM_NOT_EQUALS = 'num_not_equals' + NUM_LESS_THAN = 'num_less_than' + NUM_LESS_THAN_EQUALS = 'num_less_than_equals' + NUM_GREATER_THAN = 'num_greater_than' + NUM_GREATER_THAN_EQUALS = 'num_greater_than_equals' + + +class RuleRequiredConfigMultiplePropertiesConditionAnd(RuleRequiredConfigMultipleProperties): + """ + A condition with the `and` logical operator. + + :attr str description: (optional) + :attr List[RuleCondition] and_: + """ + + def __init__(self, + and_: List['RuleCondition'], + *, + description: str = None) -> None: + """ + Initialize a RuleRequiredConfigMultiplePropertiesConditionAnd object. + + :param List[RuleCondition] and_: + :param str description: (optional) + """ + # pylint: disable=super-init-not-called + self.description = description + self.and_ = and_ + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleRequiredConfigMultiplePropertiesConditionAnd': + """Initialize a RuleRequiredConfigMultiplePropertiesConditionAnd object from a json dictionary.""" + args = {} + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'and' in _dict: + args['and_'] = _dict.get('and') + else: + raise ValueError('Required property \'and\' not present in RuleRequiredConfigMultiplePropertiesConditionAnd JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleRequiredConfigMultiplePropertiesConditionAnd object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'and_') and self.and_ is not None: + and_list = [] + for x in self.and_: + if isinstance(x, dict): + and_list.append(x) + else: + and_list.append(x.to_dict()) + _dict['and'] = and_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleRequiredConfigMultiplePropertiesConditionAnd object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleRequiredConfigMultiplePropertiesConditionAnd') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleRequiredConfigMultiplePropertiesConditionAnd') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + +class RuleRequiredConfigMultiplePropertiesConditionOr(RuleRequiredConfigMultipleProperties): + """ + A condition with the `or` logical operator. + + :attr str description: (optional) + :attr List[RuleCondition] or_: + """ + + def __init__(self, + or_: List['RuleCondition'], + *, + description: str = None) -> None: + """ + Initialize a RuleRequiredConfigMultiplePropertiesConditionOr object. + + :param List[RuleCondition] or_: + :param str description: (optional) + """ + # pylint: disable=super-init-not-called + self.description = description + self.or_ = or_ + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuleRequiredConfigMultiplePropertiesConditionOr': + """Initialize a RuleRequiredConfigMultiplePropertiesConditionOr object from a json dictionary.""" + args = {} + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'or' in _dict: + args['or_'] = _dict.get('or') + else: + raise ValueError('Required property \'or\' not present in RuleRequiredConfigMultiplePropertiesConditionOr JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuleRequiredConfigMultiplePropertiesConditionOr object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'or_') and self.or_ is not None: + or_list = [] + for x in self.or_: + if isinstance(x, dict): + or_list.append(x) + else: + or_list.append(x.to_dict()) + _dict['or'] = or_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuleRequiredConfigMultiplePropertiesConditionOr object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuleRequiredConfigMultiplePropertiesConditionOr') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuleRequiredConfigMultiplePropertiesConditionOr') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/test/integration/test_configuration_governance_v1.py b/test/integration/test_configuration_governance_v1.py new file mode 100644 index 00000000..c5d862d5 --- /dev/null +++ b/test/integration/test_configuration_governance_v1.py @@ -0,0 +1,740 @@ +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Integration Tests for ConfigurationGovernanceV1 +""" + +import os +import pytest +import uuid +from ibm_cloud_sdk_core import * +from ibm_platform_services.configuration_governance_v1 import * + +# Config file name +config_file = 'configuration_governance.env' +TEST_LABEL = 'PythonSDKIntegrationTest' +TRANSACTION_ID = str(uuid.uuid4()) + + +class TestConfigurationGovernanceV1(): + """ + Integration Test Class for ConfigurationGovernanceV1 + """ + + def init_sample_data(self): + + # Construct a dict representation of a RuleTargetAttribute model + rule_target_attribute_model = { + 'name': 'resource_id', + 'operator': RuleTargetAttribute.OperatorEnum.IS_NOT_EMPTY + } + + # Construct a dict representation of a TargetResource model + target_resource_model = { + 'service_name': self.TEST_SERVICE_NAME, + 'resource_kind': 'bucket', + 'additional_target_attributes': [rule_target_attribute_model] + } + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + allowed_gb_condition = { + 'property': 'allowed_gb', + 'operator': RuleConditionSingleProperty.OperatorEnum.NUM_LESS_THAN_EQUALS, + 'value': '20' + } + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + location_condition = { + 'property': 'location', + 'operator': RuleConditionSingleProperty.OperatorEnum.STRING_EQUALS, + 'value': 'us-east' + } + + # Construct a dict representation of a RuleRequiredConfigMultiplePropertiesConditionAnd model + rule_required_config_model_1 = RuleRequiredConfigMultiplePropertiesConditionAnd( + description = "allowed_gb<=20 && location=='us-east'", + and_ = [allowed_gb_condition, location_condition] + ).to_dict() + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + rule_required_config_model_2 = { + 'description': "allowed_gb<=30", + 'property': 'allowed_gb', + 'operator': RuleRequiredConfigSingleProperty.OperatorEnum.NUM_LESS_THAN_EQUALS, + 'value': '30' + } + + # Construct a dict representation of a EnforcementAction model + enforcement_action_model = { + 'action': EnforcementAction.ActionEnum.DISALLOW + } + + # Construct a dict representation of a RuleRequest model + self.sample_rule_1 = { + 'account_id': self.ACCOUNT_ID, + 'name': 'Java Test Rule #1', + 'description': 'This is the description for Java Test Rule #1.', + 'rule_type': Rule.RuleTypeEnum.USER_DEFINED, + 'target': target_resource_model, + 'required_config': rule_required_config_model_1, + 'enforcement_actions': [enforcement_action_model], + 'labels': [TEST_LABEL] + } + + # Construct a dict representation of a RuleRequest model + self.sample_rule_2 = { + 'account_id': self.ACCOUNT_ID, + 'name': 'Java Test Rule #2', + 'description': 'This is the description for Java Test Rule #2.', + 'rule_type': Rule.RuleTypeEnum.USER_DEFINED, + 'target': target_resource_model, + 'required_config': rule_required_config_model_2, + 'enforcement_actions': [enforcement_action_model], + 'labels': [TEST_LABEL] + } + + # Construct a dict representation of a RuleRequest model + self.bad_sample_rule = { + 'account_id': self.ACCOUNT_ID, + 'name': 'Java Test Rule #2', + 'description': 'This is the description for Java Test Rule #2.', + 'rule_type': 'service_defined', + 'target': target_resource_model, + 'required_config': rule_required_config_model_2, + 'enforcement_actions': [enforcement_action_model], + 'labels': [TEST_LABEL] + } + + # Sample rule scopes + self.enterprise_scope = { + 'note': 'enterprise', + 'scope_id': self.ENTERPRISE_SCOPE_ID, + 'scope_type': 'enterprise' + } + + self.account_scope = { + 'note': 'leaf account', + 'scope_id': self.SUBACCT_SCOPE_ID, + 'scope_type': 'enterprise.account' + } + + self.bad_scope = { + 'note': 'leaf account', + 'scope_id': self.SUBACCT_SCOPE_ID, + 'scope_type': 'enterprise.BOGUS' + } + + # Helper function to clean rules + def clean_rules(self, label): + print("Cleaning rules..."); + + list_rules_response = self.service.list_rules( + account_id=self.ACCOUNT_ID, + labels=label, + limit=1000, + offset=0 + ) + + assert list_rules_response.get_status_code() == 200 + rule_list = list_rules_response.get_result() + assert rule_list is not None + + print("Found %d rule(s) to be cleaned" % rule_list['total_count']) + + # Now walk through the returned rules and delete each one. + if rule_list['total_count'] > 0: + for rule in rule_list['rules']: + print("Deleting rule: name='%s' id='%s'" % (rule['name'], rule['rule_id'])) + delete_rule_response = self.service.delete_rule( + rule_id=rule['rule_id'] + ) + assert delete_rule_response.get_status_code() == 204 + print("Finished cleaning rules...") + + @classmethod + def setup_class(cls): + if os.path.exists(config_file): + os.environ['IBM_CREDENTIALS_FILE'] = config_file + + # Construct the service client. + cls.service = ConfigurationGovernanceV1.new_instance() + assert cls.service is not None + assert cls.service.service_url is not None + + # Construct a separate service client for some negative tests. + # This service has an apikey that lacks the necessary access to create or list rules, etc. + cls.service_no_access = ConfigurationGovernanceV1.new_instance("NO_ACCESS"); + assert cls.service_no_access is not None + assert cls.service_no_access.service_url is not None + + # Load up our test-specific config properties. + cls.config = read_external_sources(ConfigurationGovernanceV1.DEFAULT_SERVICE_NAME); + assert cls.config is not None + assert cls.config["URL"] == cls.service.service_url + + # Retrieve and verify some additional test-related config properties. + cls.ACCOUNT_ID = cls.config.get("ACCOUNT_ID"); + cls.TEST_SERVICE_NAME = cls.config.get("TEST_SERVICE_NAME"); + cls.ENTERPRISE_SCOPE_ID = cls.config.get("ENTERPRISE_SCOPE_ID"); + cls.SUBACCT_SCOPE_ID = cls.config.get("SUBACCT_SCOPE_ID"); + assert cls.ACCOUNT_ID is not None + assert cls.TEST_SERVICE_NAME is not None + assert cls.ENTERPRISE_SCOPE_ID is not None + assert cls.SUBACCT_SCOPE_ID is not None + + print("Service URL: " + cls.service.service_url) + print("Transaction ID: " + TRANSACTION_ID) + + # Clean any existing test rules before we start the actual tests. + cls.clean_rules(cls, TEST_LABEL) + + # Create some sample model instances that we'll use when invoking the operations. + cls.init_sample_data(cls) + + print('Setup complete.') + + @classmethod + def teardown_class(cls): + print("Starting clean up..."); + cls.clean_rules(cls, TEST_LABEL); + print("Clean up complete."); + + needscredentials = pytest.mark.skipif( + not os.path.exists(config_file), reason="External configuration not available, skipping..." + ) + + def get_rule(self, rule_id): + get_rule_response = self.service.get_rule( + rule_id=rule_id, + transaction_id=TRANSACTION_ID + ) + assert get_rule_response.get_status_code() == 200 + return get_rule_response.get_result() + + def get_attachment(self, rule_id, attachment_id): + get_attachment_response = self.service.get_attachment( + rule_id=rule_id, + attachment_id=attachment_id + ) + assert get_rule_response.get_status_code() == 200 + return get_rule_response.get_result() + + @needscredentials + def test_create_rule_1(self): + + # Construct a dict representation of a CreateRuleRequest model + create_rule_request_model = { + 'request_id': 'request-0', + 'rule': self.sample_rule_1 + } + + create_rules_response = self.service.create_rules( + rules=[create_rule_request_model], + transaction_id=TRANSACTION_ID + ) + + assert create_rules_response.get_status_code() == 201 + create_rules_response = create_rules_response.get_result() + assert create_rules_response is not None + + global RULE_ID_1 + RULE_ID_1 = create_rules_response['rules'][0]['rule']['rule_id'] + assert RULE_ID_1 is not None + + @needscredentials + def test_create_rule_2(self): + + # Construct a dict representation of a CreateRuleRequest model + create_rule_request_model = { + 'request_id': 'request-0', + 'rule': self.sample_rule_2 + } + + create_rules_response = self.service.create_rules( + rules=[create_rule_request_model], + transaction_id=TRANSACTION_ID + ) + + assert create_rules_response.get_status_code() == 201 + create_rules_response = create_rules_response.get_result() + assert create_rules_response is not None + + global RULE_ID_2 + RULE_ID_2 = create_rules_response['rules'][0]['rule']['rule_id'] + assert RULE_ID_2 is not None + + @needscredentials + def test_create_rule_invalid_rule(self): + + # Construct a dict representation of a CreateRuleRequest model + create_rule_request_model = { + 'request_id': 'request-1', + 'rule': self.bad_sample_rule + } + + create_rules_response = self.service.create_rules( + rules=[create_rule_request_model], + transaction_id=TRANSACTION_ID + ) + + assert create_rules_response.get_status_code() == 207 + create_rules_response = create_rules_response.get_result() + assert create_rules_response is not None + + rule_response = create_rules_response['rules'][0] + assert rule_response['request_id'] == 'request-1' + assert rule_response['status_code'] == 400 + assert rule_response['trace'] == TRANSACTION_ID + assert len(rule_response['errors']) > 0 + assert rule_response['errors'][0]['code'] == 'rule_error' + + @needscredentials + def test_create_rule_no_access(self): + + try: + # Construct a dict representation of a CreateRuleRequest model + create_rule_request_model = { + 'request_id': 'request-1', + 'rule': self.sample_rule_1 + } + + create_rules_response = self.service_no_access.create_rules( + rules=[create_rule_request_model], + transaction_id=TRANSACTION_ID + ) + pytest.fail(msg='Using a no-access apikey should not have succeeded!') + except ApiException as e: + assert e.code == 403 + assert e.message == 'The token is not authorized to perform the operation' + + @needscredentials + def test_list_rules(self): + + list_rules_response = self.service.list_rules( + account_id=self.ACCOUNT_ID, + transaction_id=TRANSACTION_ID, + labels=TEST_LABEL, + limit=1000, + offset=0 + ) + + assert list_rules_response.get_status_code() == 200 + rule_list = list_rules_response.get_result() + assert rule_list is not None + + assert rule_list['total_count'] == 2 + assert rule_list['offset'] == 0 + assert rule_list['limit'] == 1000 + assert rule_list['first'] is not None + assert rule_list['last'] is not None + + @needscredentials + def test_list_rules_no_access(self): + try: + list_rules_response = self.service_no_access.list_rules( + account_id=self.ACCOUNT_ID, + transaction_id=TRANSACTION_ID, + labels=TEST_LABEL, + limit=1000, + offset=0 + ) + pytest.fail(msg='Using a no-access apikey should not have succeeded!') + except ApiException as e: + assert e.code == 403 + assert e.message == 'The token is not authorized to perform the operation' + + @needscredentials + def test_get_rule(self): + + get_rule_response = self.service.get_rule( + rule_id=RULE_ID_1, + transaction_id=TRANSACTION_ID + ) + + assert get_rule_response.get_status_code() == 200 + global RULE_1 + RULE_1 = get_rule_response.get_result() + assert RULE_1 is not None + + # Grab the Etag value from the response for use in the update operation. + assert get_rule_response.get_headers()['Etag'] is not None + global RULE_ETAG_1 + RULE_ETAG_1 = get_rule_response.get_headers()['Etag'] + + @needscredentials + def test_get_rule_invalid_rule_id(self): + try: + get_rule_response = self.service.get_rule( + rule_id="BOGUS_ID", + transaction_id=TRANSACTION_ID + ) + pytest.fail(msg="Invalid get should not have succeeded!") + except ApiException as e: + assert e.code == 404 + assert e.message == "The requested resource was not found" + + @needscredentials + def test_update_rule(self): + + assert RULE_1 is not None + assert RULE_ID_1 is not None + assert RULE_ETAG_1 is not None + + # Starting with "rule1" (result of a get), modify the description, then call the update operation. + update_rule_response = self.service.update_rule( + rule_id=RULE_ID_1, + if_match=RULE_ETAG_1, + name=RULE_1['name'], + description="Updated: " + RULE_1['description'], + target=RULE_1['target'], + required_config=RULE_1['required_config'], + enforcement_actions=RULE_1['enforcement_actions'], + account_id=RULE_1['account_id'], + rule_type=RULE_1['rule_type'], + labels=RULE_1['labels'], + transaction_id=TRANSACTION_ID + ) + + assert update_rule_response.get_status_code() == 200 + rule = update_rule_response.get_result() + assert rule is not None + assert rule['description'].startswith("Updated: ") + + @needscredentials + def test_update_rule_invalid_etag(self): + + try: + assert RULE_1 is not None + assert RULE_ID_1 is not None + assert RULE_ETAG_1 is not None + + # Starting with "rule1" (result of a get), modify the description, then call the update operation. + update_rule_response = self.service.update_rule( + rule_id=RULE_ID_1, + if_match=RULE_ETAG_1 + "just-foolin'", + name=RULE_1['name'], + description="Updated: " + RULE_1['description'], + target=RULE_1['target'], + required_config=RULE_1['required_config'], + enforcement_actions=RULE_1['enforcement_actions'], + account_id=RULE_1['account_id'], + rule_type=RULE_1['rule_type'], + labels=RULE_1['labels'], + transaction_id=TRANSACTION_ID + ) + pytest.fail(msg='Using an invalid etag should not have succeeded!') + except ApiException as e: + assert e.code == 400 + assert e.message == 'The provided If-Match value is malformed' + + @needscredentials + def test_delete_rule(self): + + assert RULE_ID_2 is not None + + delete_rule_response = self.service.delete_rule( + rule_id=RULE_ID_2, + transaction_id=TRANSACTION_ID + ) + + assert delete_rule_response.get_status_code() == 204 + + # Now check to make sure listRules() returns only 1 rule. + list_rules_response = self.service.list_rules( + account_id=self.ACCOUNT_ID, + transaction_id=TRANSACTION_ID, + labels=TEST_LABEL, + limit=1000, + offset=0 + ) + + assert list_rules_response.get_status_code() == 200 + rule_list = list_rules_response.get_result() + assert rule_list is not None + + assert rule_list['total_count'] == 1 + + try: + rule = self.get_rule(RULE_ID_2) + pytest.fail(msg="Getting a non-existant rule should not have succeeded!") + except ApiException as e: + assert e.code == 404 + assert e.message == "The requested resource was not found" + + + @needscredentials + def test_delete_rule_invalid_rule_id(self): + try: + delete_rule_response = self.service.delete_rule( + rule_id="BOGUS_RULE_ID", + transaction_id=TRANSACTION_ID + ) + pytest.fail(msg="Invalid delete should not have succeeded!") + except ApiException as e: + assert e.code == 404 + assert e.message == "The requested resource was not found" + + @needscredentials + def test_create_attachment_1(self): + + assert RULE_ID_1 is not None + + # Construct a dict representation of a AttachmentRequest model + attachment_request_model = { + 'account_id': self.ACCOUNT_ID, + 'included_scope': self.enterprise_scope, + 'excluded_scopes': [self.account_scope] + } + + create_attachments_response = self.service.create_attachments( + rule_id=RULE_ID_1, + attachments=[attachment_request_model], + transaction_id=TRANSACTION_ID + ) + + assert create_attachments_response.get_status_code() == 201 + create_attachments_response = create_attachments_response.get_result() + assert create_attachments_response is not None + + assert len(create_attachments_response['attachments']) == 1 + assert create_attachments_response['attachments'][0] is not None + global ATTACHMENT_ID_1 + ATTACHMENT_ID_1 = create_attachments_response['attachments'][0]['attachment_id'] + assert ATTACHMENT_ID_1 is not None + + rule = self.get_rule(RULE_ID_1) + assert rule is not None + assert rule['number_of_attachments'] == 1 + + @needscredentials + def test_create_attachment_2(self): + + assert RULE_ID_1 is not None + + # Construct a dict representation of a AttachmentRequest model + attachment_request_model = { + 'account_id': self.ACCOUNT_ID, + 'included_scope': self.account_scope + } + + create_attachments_response = self.service.create_attachments( + rule_id=RULE_ID_1, + attachments=[attachment_request_model], + transaction_id=TRANSACTION_ID + ) + + assert create_attachments_response.get_status_code() == 201 + create_attachments_response = create_attachments_response.get_result() + assert create_attachments_response is not None + + assert len(create_attachments_response['attachments']) == 1 + assert create_attachments_response['attachments'][0] is not None + global ATTACHMENT_ID_2 + ATTACHMENT_ID_2 = create_attachments_response['attachments'][0]['attachment_id'] + assert ATTACHMENT_ID_2 is not None + + rule = self.get_rule(RULE_ID_1) + assert rule is not None + assert rule['number_of_attachments'] == 2 + + + @needscredentials + def test_create_attachment_invalid_scope_type(self): + try: + assert RULE_ID_1 is not None + + # Construct a dict representation of a AttachmentRequest model + attachment_request_model = { + 'account_id': self.ACCOUNT_ID, + 'included_scope': self.enterprise_scope, + 'excluded_scopes': [self.bad_scope] + } + + create_attachments_response = self.service.create_attachments( + rule_id=RULE_ID_1, + attachments=[attachment_request_model], + transaction_id=TRANSACTION_ID + ) + pytest.fail(msg="Invalid attachment should not have succeeded!") + except ApiException as e: + assert e.code == 400 + assert e.message == "attachment[0]: The excluded scope at index 0 is not a descendant of the included scope." + + @needscredentials + def test_get_attachment(self): + + assert RULE_ID_1 is not None + assert ATTACHMENT_ID_1 is not None + + get_attachment_response = self.service.get_attachment( + rule_id=RULE_ID_1, + attachment_id=ATTACHMENT_ID_1 + ) + + assert get_attachment_response.get_status_code() == 200 + global ATTACHMENT_1 + ATTACHMENT_1 = get_attachment_response.get_result() + assert ATTACHMENT_1 is not None + + assert ATTACHMENT_1['account_id'] == self.ACCOUNT_ID + assert ATTACHMENT_1['rule_id'] == RULE_ID_1 + assert ATTACHMENT_1['attachment_id'] == ATTACHMENT_ID_1 + assert ATTACHMENT_1['included_scope']['note'] == 'enterprise' + assert len(ATTACHMENT_1['excluded_scopes']) == 1 + + # Grab the Etag value from the response for use in the update operation. + assert get_attachment_response.get_headers()['Etag'] is not None + global ATTACHMENT_ETAG_1 + ATTACHMENT_ETAG_1 = get_attachment_response.get_headers()['Etag'] + assert ATTACHMENT_ETAG_1 is not None + + @needscredentials + def test_get_attachment_invalid_attachment_id(self): + try: + assert RULE_ID_1 is not None + assert ATTACHMENT_ID_1 is not None + + get_attachment_response = self.service.get_attachment( + rule_id=RULE_ID_1, + attachment_id="BOGUS_ID" + ) + pytest.fail(msg="Invalid attachment id should not have succeeded!") + except ApiException as e: + assert e.code == 404 + assert e.message == "The requested resource was not found" + + @needscredentials + def test_list_attachments(self): + + list_attachments_response = self.service.list_attachments( + rule_id=RULE_ID_1, + transaction_id=TRANSACTION_ID, + limit=1000, + offset=0 + ) + + assert list_attachments_response.get_status_code() == 200 + attachment_list = list_attachments_response.get_result() + assert attachment_list is not None + + assert attachment_list['offset'] == 0 + assert attachment_list['limit'] == 1000 + assert attachment_list['total_count'] == 2 + assert attachment_list['first'] is not None + assert attachment_list['last'] is not None + for att in attachment_list['attachments']: + if att['attachment_id'] == ATTACHMENT_ID_1: + assert att['included_scope']['note'] == 'enterprise' + assert len(att['excluded_scopes']) == 1 + elif att['attachment_id'] == ATTACHMENT_ID_2: + assert att['included_scope']['note'] == 'leaf account' + assert len(att['excluded_scopes']) == 0 + else: + pytest.fail(msg="Unrecognized attachmentId: " + att['attachment_id']) + + @needscredentials + def test_update_attachment(self): + + assert RULE_ID_1 is not None + assert ATTACHMENT_1 is not None + assert ATTACHMENT_ETAG_1 is not None + + # Construct a dict representation of a RuleScope model + rule_scope_model = { + 'note': "Updated: " + ATTACHMENT_1['included_scope']['note'], + 'scope_id': ATTACHMENT_1['included_scope']['scope_id'], + 'scope_type': ATTACHMENT_1['included_scope']['scope_type'] + } + + update_attachment_response = self.service.update_attachment( + rule_id=ATTACHMENT_1['rule_id'], + attachment_id=ATTACHMENT_1['attachment_id'], + if_match=ATTACHMENT_ETAG_1, + account_id=ATTACHMENT_1['account_id'], + included_scope=rule_scope_model, + excluded_scopes=ATTACHMENT_1['excluded_scopes'], + transaction_id=TRANSACTION_ID + ) + + assert update_attachment_response.get_status_code() == 200 + attachment = update_attachment_response.get_result() + assert attachment is not None + + assert attachment['included_scope'] is not None + assert attachment['included_scope']['note'].startswith('Updated:') + + @needscredentials + def test_update_attachment_invalid_etag(self): + try: + assert RULE_ID_1 is not None + assert ATTACHMENT_1 is not None + assert ATTACHMENT_ETAG_1 is not None + + # Construct a dict representation of a RuleScope model + rule_scope_model = { + 'note': "Updated: " + ATTACHMENT_1['included_scope']['note'], + 'scope_id': ATTACHMENT_1['included_scope']['scope_id'], + 'scope_type': ATTACHMENT_1['included_scope']['scope_type'] + } + + update_attachment_response = self.service.update_attachment( + rule_id=ATTACHMENT_1['rule_id'], + attachment_id=ATTACHMENT_1['attachment_id'], + if_match="BOGUS_ETAG", + account_id=ATTACHMENT_1['account_id'], + included_scope=rule_scope_model, + excluded_scopes=ATTACHMENT_1['excluded_scopes'], + transaction_id=TRANSACTION_ID + ) + pytest.fail(msg="Invalid update should not have succeeded!") + except ApiException as e: + assert e.code == 400 + assert e.message == "The provided If-Match value is malformed" + + @needscredentials + def test_delete_attachment(self): + + assert RULE_ID_1 is not None + assert ATTACHMENT_ID_2 is not None + + delete_attachment_response = self.service.delete_attachment( + rule_id=RULE_ID_1, + attachment_id=ATTACHMENT_ID_2, + transaction_id=TRANSACTION_ID + ) + + assert delete_attachment_response.get_status_code() == 204 + + + list_attachments_response = self.service.list_attachments( + rule_id=RULE_ID_1, + transaction_id=TRANSACTION_ID, + limit=1000, + offset=0 + ) + + assert list_attachments_response.get_status_code() == 200 + attachment_list = list_attachments_response.get_result() + assert attachment_list is not None + + assert attachment_list['total_count'] == 1 + + try: + attachment = self.get_attachment(RULE_ID_1, ATTACHMENT_ID_2) + pytest.fail(msg="Getting a non-existant attachment should not have succeeded!") + except ApiException as e: + assert e.code == 404 + assert e.message == "The requested resource was not found" diff --git a/test/unit/test_configuration_governance_v1.py b/test/unit/test_configuration_governance_v1.py new file mode 100644 index 00000000..84392767 --- /dev/null +++ b/test/unit/test_configuration_governance_v1.py @@ -0,0 +1,2475 @@ +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Unit Tests for ConfigurationGovernanceV1 +""" + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest +import re +import requests +import responses +import urllib +from ibm_platform_services.configuration_governance_v1 import * + + +service = ConfigurationGovernanceV1( + authenticator=NoAuthAuthenticator() + ) + +base_url = 'https://compliance.cloud.ibm.com' +service.set_service_url(base_url) + +############################################################################## +# Start of Service: Rules +############################################################################## +# region + +class TestCreateRules(): + """ + Test Class for create_rules + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_rules_all_params(self): + """ + create_rules() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules') + mock_response = '{"rules": [{"request_id": "3cebc877-58e7-44a5-a292-32114fa73558", "status_code": 201, "rule": {"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}, "errors": [{"code": "bad_request", "message": "The rule is missing an account ID"}], "trace": "861263b4-cee3-4514-8d8c-05d17308e6eb"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a RuleTargetAttribute model + rule_target_attribute_model = {} + rule_target_attribute_model['name'] = 'testString' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'testString' + + # Construct a dict representation of a TargetResource model + target_resource_model = {} + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'service' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + rule_required_config_model = {} + rule_required_config_model['description'] = 'Public access check' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + # Construct a dict representation of a EnforcementAction model + enforcement_action_model = {} + enforcement_action_model['action'] = 'audit_log' + + # Construct a dict representation of a RuleRequest model + rule_request_model = {} + rule_request_model['account_id'] = '531fc3e28bfc43c5a2cea07786d93f5c' + rule_request_model['name'] = 'Disable public access' + rule_request_model['description'] = 'Ensure that public access to account resources is disabled.' + rule_request_model['rule_type'] = 'user_defined' + rule_request_model['target'] = target_resource_model + rule_request_model['required_config'] = rule_required_config_model + rule_request_model['enforcement_actions'] = [enforcement_action_model] + rule_request_model['labels'] = ['testString'] + + # Construct a dict representation of a CreateRuleRequest model + create_rule_request_model = {} + create_rule_request_model['request_id'] = '3cebc877-58e7-44a5-a292-32114fa73558' + create_rule_request_model['rule'] = rule_request_model + + # Set up parameter values + rules = [create_rule_request_model] + transaction_id = 'testString' + + # Invoke method + response = service.create_rules( + rules, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['rules'] == [create_rule_request_model] + + + @responses.activate + def test_create_rules_required_params(self): + """ + test_create_rules_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules') + mock_response = '{"rules": [{"request_id": "3cebc877-58e7-44a5-a292-32114fa73558", "status_code": 201, "rule": {"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}, "errors": [{"code": "bad_request", "message": "The rule is missing an account ID"}], "trace": "861263b4-cee3-4514-8d8c-05d17308e6eb"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a RuleTargetAttribute model + rule_target_attribute_model = {} + rule_target_attribute_model['name'] = 'testString' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'testString' + + # Construct a dict representation of a TargetResource model + target_resource_model = {} + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'service' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + rule_required_config_model = {} + rule_required_config_model['description'] = 'Public access check' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + # Construct a dict representation of a EnforcementAction model + enforcement_action_model = {} + enforcement_action_model['action'] = 'audit_log' + + # Construct a dict representation of a RuleRequest model + rule_request_model = {} + rule_request_model['account_id'] = '531fc3e28bfc43c5a2cea07786d93f5c' + rule_request_model['name'] = 'Disable public access' + rule_request_model['description'] = 'Ensure that public access to account resources is disabled.' + rule_request_model['rule_type'] = 'user_defined' + rule_request_model['target'] = target_resource_model + rule_request_model['required_config'] = rule_required_config_model + rule_request_model['enforcement_actions'] = [enforcement_action_model] + rule_request_model['labels'] = ['testString'] + + # Construct a dict representation of a CreateRuleRequest model + create_rule_request_model = {} + create_rule_request_model['request_id'] = '3cebc877-58e7-44a5-a292-32114fa73558' + create_rule_request_model['rule'] = rule_request_model + + # Set up parameter values + rules = [create_rule_request_model] + + # Invoke method + response = service.create_rules( + rules, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['rules'] == [create_rule_request_model] + + + @responses.activate + def test_create_rules_value_error(self): + """ + test_create_rules_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules') + mock_response = '{"rules": [{"request_id": "3cebc877-58e7-44a5-a292-32114fa73558", "status_code": 201, "rule": {"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}, "errors": [{"code": "bad_request", "message": "The rule is missing an account ID"}], "trace": "861263b4-cee3-4514-8d8c-05d17308e6eb"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a RuleTargetAttribute model + rule_target_attribute_model = {} + rule_target_attribute_model['name'] = 'testString' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'testString' + + # Construct a dict representation of a TargetResource model + target_resource_model = {} + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'service' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + rule_required_config_model = {} + rule_required_config_model['description'] = 'Public access check' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + # Construct a dict representation of a EnforcementAction model + enforcement_action_model = {} + enforcement_action_model['action'] = 'audit_log' + + # Construct a dict representation of a RuleRequest model + rule_request_model = {} + rule_request_model['account_id'] = '531fc3e28bfc43c5a2cea07786d93f5c' + rule_request_model['name'] = 'Disable public access' + rule_request_model['description'] = 'Ensure that public access to account resources is disabled.' + rule_request_model['rule_type'] = 'user_defined' + rule_request_model['target'] = target_resource_model + rule_request_model['required_config'] = rule_required_config_model + rule_request_model['enforcement_actions'] = [enforcement_action_model] + rule_request_model['labels'] = ['testString'] + + # Construct a dict representation of a CreateRuleRequest model + create_rule_request_model = {} + create_rule_request_model['request_id'] = '3cebc877-58e7-44a5-a292-32114fa73558' + create_rule_request_model['rule'] = rule_request_model + + # Set up parameter values + rules = [create_rule_request_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rules": rules, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_rules(**req_copy) + + + +class TestListRules(): + """ + Test Class for list_rules + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_rules_all_params(self): + """ + list_rules() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules') + mock_response = '{"offset": 6, "limit": 1000, "total_count": 11, "first": {"href": "href"}, "last": {"href": "href"}, "rules": [{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + transaction_id = 'testString' + attached = True + labels = 'SOC2,ITCS300' + scopes = 'scope_id' + limit = 1000 + offset = 38 + + # Invoke method + response = service.list_rules( + account_id, + transaction_id=transaction_id, + attached=attached, + labels=labels, + scopes=scopes, + limit=limit, + offset=offset, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'account_id={}'.format(account_id) in query_string + assert 'attached={}'.format('true' if attached else 'false') in query_string + assert 'labels={}'.format(labels) in query_string + assert 'scopes={}'.format(scopes) in query_string + assert 'limit={}'.format(limit) in query_string + assert 'offset={}'.format(offset) in query_string + + + @responses.activate + def test_list_rules_required_params(self): + """ + test_list_rules_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules') + mock_response = '{"offset": 6, "limit": 1000, "total_count": 11, "first": {"href": "href"}, "last": {"href": "href"}, "rules": [{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + + # Invoke method + response = service.list_rules( + account_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'account_id={}'.format(account_id) in query_string + + + @responses.activate + def test_list_rules_value_error(self): + """ + test_list_rules_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules') + mock_response = '{"offset": 6, "limit": 1000, "total_count": 11, "first": {"href": "href"}, "last": {"href": "href"}, "rules": [{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "account_id": account_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_rules(**req_copy) + + + +class TestGetRule(): + """ + Test Class for get_rule + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_rule_all_params(self): + """ + get_rule() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + mock_response = '{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + transaction_id = 'testString' + + # Invoke method + response = service.get_rule( + rule_id, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_rule_required_params(self): + """ + test_get_rule_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + mock_response = '{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + + # Invoke method + response = service.get_rule( + rule_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_rule_value_error(self): + """ + test_get_rule_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + mock_response = '{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_rule(**req_copy) + + + +class TestUpdateRule(): + """ + Test Class for update_rule + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_rule_all_params(self): + """ + update_rule() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + mock_response = '{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuleTargetAttribute model + rule_target_attribute_model = {} + rule_target_attribute_model['name'] = 'testString' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'testString' + + # Construct a dict representation of a TargetResource model + target_resource_model = {} + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'service' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + rule_required_config_model = {} + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_false' + rule_required_config_model['value'] = 'testString' + + # Construct a dict representation of a EnforcementAction model + enforcement_action_model = {} + enforcement_action_model['action'] = 'audit_log' + + # Set up parameter values + rule_id = 'testString' + if_match = 'testString' + name = 'Disable public access' + description = 'Ensure that public access to account resources is disabled.' + target = target_resource_model + required_config = rule_required_config_model + enforcement_actions = [enforcement_action_model] + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + rule_type = 'user_defined' + labels = ['testString'] + transaction_id = 'testString' + + # Invoke method + response = service.update_rule( + rule_id, + if_match, + name, + description, + target, + required_config, + enforcement_actions, + account_id=account_id, + rule_type=rule_type, + labels=labels, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'Disable public access' + assert req_body['description'] == 'Ensure that public access to account resources is disabled.' + assert req_body['target'] == target_resource_model + assert req_body['required_config'] == rule_required_config_model + assert req_body['enforcement_actions'] == [enforcement_action_model] + assert req_body['account_id'] == '531fc3e28bfc43c5a2cea07786d93f5c' + assert req_body['rule_type'] == 'user_defined' + assert req_body['labels'] == ['testString'] + + + @responses.activate + def test_update_rule_required_params(self): + """ + test_update_rule_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + mock_response = '{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuleTargetAttribute model + rule_target_attribute_model = {} + rule_target_attribute_model['name'] = 'testString' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'testString' + + # Construct a dict representation of a TargetResource model + target_resource_model = {} + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'service' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + rule_required_config_model = {} + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_false' + rule_required_config_model['value'] = 'testString' + + # Construct a dict representation of a EnforcementAction model + enforcement_action_model = {} + enforcement_action_model['action'] = 'audit_log' + + # Set up parameter values + rule_id = 'testString' + if_match = 'testString' + name = 'Disable public access' + description = 'Ensure that public access to account resources is disabled.' + target = target_resource_model + required_config = rule_required_config_model + enforcement_actions = [enforcement_action_model] + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + rule_type = 'user_defined' + labels = ['testString'] + + # Invoke method + response = service.update_rule( + rule_id, + if_match, + name, + description, + target, + required_config, + enforcement_actions, + account_id=account_id, + rule_type=rule_type, + labels=labels, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'Disable public access' + assert req_body['description'] == 'Ensure that public access to account resources is disabled.' + assert req_body['target'] == target_resource_model + assert req_body['required_config'] == rule_required_config_model + assert req_body['enforcement_actions'] == [enforcement_action_model] + assert req_body['account_id'] == '531fc3e28bfc43c5a2cea07786d93f5c' + assert req_body['rule_type'] == 'user_defined' + assert req_body['labels'] == ['testString'] + + + @responses.activate + def test_update_rule_value_error(self): + """ + test_update_rule_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + mock_response = '{"account_id": "account_id", "name": "name", "description": "description", "rule_type": "user_defined", "target": {"service_name": "iam-groups", "resource_kind": "zone", "additional_target_attributes": [{"name": "name", "operator": "string_equals", "value": "value"}]}, "required_config": {"description": "description", "property": "public_access_enabled", "operator": "is_true", "value": "value"}, "enforcement_actions": [{"action": "audit_log"}], "labels": ["label"], "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "creation_date": "2020-01-10T05:23:19+0000", "created_by": "created_by", "modification_date": "modification_date", "modified_by": "modified_by", "number_of_attachments": 3}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuleTargetAttribute model + rule_target_attribute_model = {} + rule_target_attribute_model['name'] = 'testString' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'testString' + + # Construct a dict representation of a TargetResource model + target_resource_model = {} + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'service' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + # Construct a dict representation of a RuleRequiredConfigSingleProperty model + rule_required_config_model = {} + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_false' + rule_required_config_model['value'] = 'testString' + + # Construct a dict representation of a EnforcementAction model + enforcement_action_model = {} + enforcement_action_model['action'] = 'audit_log' + + # Set up parameter values + rule_id = 'testString' + if_match = 'testString' + name = 'Disable public access' + description = 'Ensure that public access to account resources is disabled.' + target = target_resource_model + required_config = rule_required_config_model + enforcement_actions = [enforcement_action_model] + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + rule_type = 'user_defined' + labels = ['testString'] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + "if_match": if_match, + "name": name, + "description": description, + "target": target, + "required_config": required_config, + "enforcement_actions": enforcement_actions, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_rule(**req_copy) + + + +class TestDeleteRule(): + """ + Test Class for delete_rule + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_rule_all_params(self): + """ + delete_rule() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + rule_id = 'testString' + transaction_id = 'testString' + + # Invoke method + response = service.delete_rule( + rule_id, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + + @responses.activate + def test_delete_rule_required_params(self): + """ + test_delete_rule_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + rule_id = 'testString' + + # Invoke method + response = service.delete_rule( + rule_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + + @responses.activate + def test_delete_rule_value_error(self): + """ + test_delete_rule_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + rule_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_rule(**req_copy) + + + +class TestCreateAttachments(): + """ + Test Class for create_attachments + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_attachments_all_params(self): + """ + create_attachments() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments') + mock_response = '{"attachments": [{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a RuleScope model + rule_scope_model = {} + rule_scope_model['note'] = 'My enterprise' + rule_scope_model['scope_id'] = '282cf433ac91493ba860480d92519990' + rule_scope_model['scope_type'] = 'enterprise' + + # Construct a dict representation of a AttachmentRequest model + attachment_request_model = {} + attachment_request_model['account_id'] = '531fc3e28bfc43c5a2cea07786d93f5c' + attachment_request_model['included_scope'] = rule_scope_model + attachment_request_model['excluded_scopes'] = [rule_scope_model] + + # Set up parameter values + rule_id = 'testString' + attachments = [attachment_request_model] + transaction_id = 'testString' + + # Invoke method + response = service.create_attachments( + rule_id, + attachments, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['attachments'] == [attachment_request_model] + + + @responses.activate + def test_create_attachments_required_params(self): + """ + test_create_attachments_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments') + mock_response = '{"attachments": [{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a RuleScope model + rule_scope_model = {} + rule_scope_model['note'] = 'My enterprise' + rule_scope_model['scope_id'] = '282cf433ac91493ba860480d92519990' + rule_scope_model['scope_type'] = 'enterprise' + + # Construct a dict representation of a AttachmentRequest model + attachment_request_model = {} + attachment_request_model['account_id'] = '531fc3e28bfc43c5a2cea07786d93f5c' + attachment_request_model['included_scope'] = rule_scope_model + attachment_request_model['excluded_scopes'] = [rule_scope_model] + + # Set up parameter values + rule_id = 'testString' + attachments = [attachment_request_model] + + # Invoke method + response = service.create_attachments( + rule_id, + attachments, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['attachments'] == [attachment_request_model] + + + @responses.activate + def test_create_attachments_value_error(self): + """ + test_create_attachments_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments') + mock_response = '{"attachments": [{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a RuleScope model + rule_scope_model = {} + rule_scope_model['note'] = 'My enterprise' + rule_scope_model['scope_id'] = '282cf433ac91493ba860480d92519990' + rule_scope_model['scope_type'] = 'enterprise' + + # Construct a dict representation of a AttachmentRequest model + attachment_request_model = {} + attachment_request_model['account_id'] = '531fc3e28bfc43c5a2cea07786d93f5c' + attachment_request_model['included_scope'] = rule_scope_model + attachment_request_model['excluded_scopes'] = [rule_scope_model] + + # Set up parameter values + rule_id = 'testString' + attachments = [attachment_request_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + "attachments": attachments, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_attachments(**req_copy) + + + +class TestListAttachments(): + """ + Test Class for list_attachments + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_attachments_all_params(self): + """ + list_attachments() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments') + mock_response = '{"offset": 6, "limit": 1000, "total_count": 11, "first": {"href": "href"}, "last": {"href": "href"}, "attachments": [{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + transaction_id = 'testString' + limit = 1000 + offset = 38 + + # Invoke method + response = service.list_attachments( + rule_id, + transaction_id=transaction_id, + limit=limit, + offset=offset, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'limit={}'.format(limit) in query_string + assert 'offset={}'.format(offset) in query_string + + + @responses.activate + def test_list_attachments_required_params(self): + """ + test_list_attachments_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments') + mock_response = '{"offset": 6, "limit": 1000, "total_count": 11, "first": {"href": "href"}, "last": {"href": "href"}, "attachments": [{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + + # Invoke method + response = service.list_attachments( + rule_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_list_attachments_value_error(self): + """ + test_list_attachments_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments') + mock_response = '{"offset": 6, "limit": 1000, "total_count": 11, "first": {"href": "href"}, "last": {"href": "href"}, "attachments": [{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_attachments(**req_copy) + + + +class TestGetAttachment(): + """ + Test Class for get_attachment + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_attachment_all_params(self): + """ + get_attachment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + mock_response = '{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + transaction_id = 'testString' + + # Invoke method + response = service.get_attachment( + rule_id, + attachment_id, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_attachment_required_params(self): + """ + test_get_attachment_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + mock_response = '{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + + # Invoke method + response = service.get_attachment( + rule_id, + attachment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_attachment_value_error(self): + """ + test_get_attachment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + mock_response = '{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + "attachment_id": attachment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_attachment(**req_copy) + + + +class TestUpdateAttachment(): + """ + Test Class for update_attachment + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_attachment_all_params(self): + """ + update_attachment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + mock_response = '{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuleScope model + rule_scope_model = {} + rule_scope_model['note'] = 'My enterprise' + rule_scope_model['scope_id'] = '282cf433ac91493ba860480d92519990' + rule_scope_model['scope_type'] = 'enterprise' + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + if_match = 'testString' + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + included_scope = rule_scope_model + excluded_scopes = [rule_scope_model] + transaction_id = 'testString' + + # Invoke method + response = service.update_attachment( + rule_id, + attachment_id, + if_match, + account_id, + included_scope, + excluded_scopes=excluded_scopes, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['account_id'] == '531fc3e28bfc43c5a2cea07786d93f5c' + assert req_body['included_scope'] == rule_scope_model + assert req_body['excluded_scopes'] == [rule_scope_model] + + + @responses.activate + def test_update_attachment_required_params(self): + """ + test_update_attachment_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + mock_response = '{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuleScope model + rule_scope_model = {} + rule_scope_model['note'] = 'My enterprise' + rule_scope_model['scope_id'] = '282cf433ac91493ba860480d92519990' + rule_scope_model['scope_type'] = 'enterprise' + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + if_match = 'testString' + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + included_scope = rule_scope_model + excluded_scopes = [rule_scope_model] + + # Invoke method + response = service.update_attachment( + rule_id, + attachment_id, + if_match, + account_id, + included_scope, + excluded_scopes=excluded_scopes, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['account_id'] == '531fc3e28bfc43c5a2cea07786d93f5c' + assert req_body['included_scope'] == rule_scope_model + assert req_body['excluded_scopes'] == [rule_scope_model] + + + @responses.activate + def test_update_attachment_value_error(self): + """ + test_update_attachment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + mock_response = '{"attachment_id": "attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2", "rule_id": "rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf", "account_id": "account_id", "included_scope": {"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}, "excluded_scopes": [{"note": "note", "scope_id": "scope_id", "scope_type": "enterprise"}]}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuleScope model + rule_scope_model = {} + rule_scope_model['note'] = 'My enterprise' + rule_scope_model['scope_id'] = '282cf433ac91493ba860480d92519990' + rule_scope_model['scope_type'] = 'enterprise' + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + if_match = 'testString' + account_id = '531fc3e28bfc43c5a2cea07786d93f5c' + included_scope = rule_scope_model + excluded_scopes = [rule_scope_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + "attachment_id": attachment_id, + "if_match": if_match, + "account_id": account_id, + "included_scope": included_scope, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_attachment(**req_copy) + + + +class TestDeleteAttachment(): + """ + Test Class for delete_attachment + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + request_url = urllib.parse.quote(request_url, safe=':/') + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_attachment_all_params(self): + """ + delete_attachment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + transaction_id = 'testString' + + # Invoke method + response = service.delete_attachment( + rule_id, + attachment_id, + transaction_id=transaction_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + + @responses.activate + def test_delete_attachment_required_params(self): + """ + test_delete_attachment_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + + # Invoke method + response = service.delete_attachment( + rule_id, + attachment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + + @responses.activate + def test_delete_attachment_value_error(self): + """ + test_delete_attachment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/config/v1/rules/testString/attachments/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + rule_id = 'testString' + attachment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "rule_id": rule_id, + "attachment_id": attachment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_attachment(**req_copy) + + + +# endregion +############################################################################## +# End of Service: Rules +############################################################################## + + +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestAttachment(): + """ + Test Class for Attachment + """ + + def test_attachment_serialization(self): + """ + Test serialization/deserialization for Attachment + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_scope_model = {} # RuleScope + rule_scope_model['note'] = 'testString' + rule_scope_model['scope_id'] = 'testString' + rule_scope_model['scope_type'] = 'enterprise' + + # Construct a json representation of a Attachment model + attachment_model_json = {} + attachment_model_json['attachment_id'] = 'attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2' + attachment_model_json['rule_id'] = 'rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf' + attachment_model_json['account_id'] = 'testString' + attachment_model_json['included_scope'] = rule_scope_model + attachment_model_json['excluded_scopes'] = [rule_scope_model] + + # Construct a model instance of Attachment by calling from_dict on the json representation + attachment_model = Attachment.from_dict(attachment_model_json) + assert attachment_model != False + + # Construct a model instance of Attachment by calling from_dict on the json representation + attachment_model_dict = Attachment.from_dict(attachment_model_json).__dict__ + attachment_model2 = Attachment(**attachment_model_dict) + + # Verify the model instances are equivalent + assert attachment_model == attachment_model2 + + # Convert model instance back to dict and verify no loss of data + attachment_model_json2 = attachment_model.to_dict() + assert attachment_model_json2 == attachment_model_json + +class TestAttachmentList(): + """ + Test Class for AttachmentList + """ + + def test_attachment_list_serialization(self): + """ + Test serialization/deserialization for AttachmentList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + link_model = {} # Link + link_model['href'] = 'testString' + + rule_scope_model = {} # RuleScope + rule_scope_model['note'] = 'testString' + rule_scope_model['scope_id'] = 'testString' + rule_scope_model['scope_type'] = 'enterprise' + + attachment_model = {} # Attachment + attachment_model['attachment_id'] = 'attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2' + attachment_model['rule_id'] = 'rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf' + attachment_model['account_id'] = 'testString' + attachment_model['included_scope'] = rule_scope_model + attachment_model['excluded_scopes'] = [rule_scope_model] + + # Construct a json representation of a AttachmentList model + attachment_list_model_json = {} + attachment_list_model_json['offset'] = 38 + attachment_list_model_json['limit'] = 1000 + attachment_list_model_json['total_count'] = 38 + attachment_list_model_json['first'] = link_model + attachment_list_model_json['last'] = link_model + attachment_list_model_json['attachments'] = [attachment_model] + + # Construct a model instance of AttachmentList by calling from_dict on the json representation + attachment_list_model = AttachmentList.from_dict(attachment_list_model_json) + assert attachment_list_model != False + + # Construct a model instance of AttachmentList by calling from_dict on the json representation + attachment_list_model_dict = AttachmentList.from_dict(attachment_list_model_json).__dict__ + attachment_list_model2 = AttachmentList(**attachment_list_model_dict) + + # Verify the model instances are equivalent + assert attachment_list_model == attachment_list_model2 + + # Convert model instance back to dict and verify no loss of data + attachment_list_model_json2 = attachment_list_model.to_dict() + assert attachment_list_model_json2 == attachment_list_model_json + +class TestAttachmentRequest(): + """ + Test Class for AttachmentRequest + """ + + def test_attachment_request_serialization(self): + """ + Test serialization/deserialization for AttachmentRequest + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_scope_model = {} # RuleScope + rule_scope_model['note'] = 'testString' + rule_scope_model['scope_id'] = 'testString' + rule_scope_model['scope_type'] = 'enterprise' + + # Construct a json representation of a AttachmentRequest model + attachment_request_model_json = {} + attachment_request_model_json['account_id'] = 'testString' + attachment_request_model_json['included_scope'] = rule_scope_model + attachment_request_model_json['excluded_scopes'] = [rule_scope_model] + + # Construct a model instance of AttachmentRequest by calling from_dict on the json representation + attachment_request_model = AttachmentRequest.from_dict(attachment_request_model_json) + assert attachment_request_model != False + + # Construct a model instance of AttachmentRequest by calling from_dict on the json representation + attachment_request_model_dict = AttachmentRequest.from_dict(attachment_request_model_json).__dict__ + attachment_request_model2 = AttachmentRequest(**attachment_request_model_dict) + + # Verify the model instances are equivalent + assert attachment_request_model == attachment_request_model2 + + # Convert model instance back to dict and verify no loss of data + attachment_request_model_json2 = attachment_request_model.to_dict() + assert attachment_request_model_json2 == attachment_request_model_json + +class TestCreateAttachmentsResponse(): + """ + Test Class for CreateAttachmentsResponse + """ + + def test_create_attachments_response_serialization(self): + """ + Test serialization/deserialization for CreateAttachmentsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_scope_model = {} # RuleScope + rule_scope_model['note'] = 'testString' + rule_scope_model['scope_id'] = 'testString' + rule_scope_model['scope_type'] = 'enterprise' + + attachment_model = {} # Attachment + attachment_model['attachment_id'] = 'attachment-fc7b9a77-1c85-406c-b346-f3f5bb9aa7e2' + attachment_model['rule_id'] = 'rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf' + attachment_model['account_id'] = 'testString' + attachment_model['included_scope'] = rule_scope_model + attachment_model['excluded_scopes'] = [rule_scope_model] + + # Construct a json representation of a CreateAttachmentsResponse model + create_attachments_response_model_json = {} + create_attachments_response_model_json['attachments'] = [attachment_model] + + # Construct a model instance of CreateAttachmentsResponse by calling from_dict on the json representation + create_attachments_response_model = CreateAttachmentsResponse.from_dict(create_attachments_response_model_json) + assert create_attachments_response_model != False + + # Construct a model instance of CreateAttachmentsResponse by calling from_dict on the json representation + create_attachments_response_model_dict = CreateAttachmentsResponse.from_dict(create_attachments_response_model_json).__dict__ + create_attachments_response_model2 = CreateAttachmentsResponse(**create_attachments_response_model_dict) + + # Verify the model instances are equivalent + assert create_attachments_response_model == create_attachments_response_model2 + + # Convert model instance back to dict and verify no loss of data + create_attachments_response_model_json2 = create_attachments_response_model.to_dict() + assert create_attachments_response_model_json2 == create_attachments_response_model_json + +class TestCreateRuleRequest(): + """ + Test Class for CreateRuleRequest + """ + + def test_create_rule_request_serialization(self): + """ + Test serialization/deserialization for CreateRuleRequest + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_target_attribute_model = {} # RuleTargetAttribute + rule_target_attribute_model['name'] = 'resource_id' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'f0f8f7994e754ff38f9d370201966561' + + target_resource_model = {} # TargetResource + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'zone' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + rule_required_config_model = {} # RuleRequiredConfigSingleProperty + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + enforcement_action_model = {} # EnforcementAction + enforcement_action_model['action'] = 'disallow' + + rule_request_model = {} # RuleRequest + rule_request_model['account_id'] = 'testString' + rule_request_model['name'] = 'testString' + rule_request_model['description'] = 'testString' + rule_request_model['rule_type'] = 'user_defined' + rule_request_model['target'] = target_resource_model + rule_request_model['required_config'] = rule_required_config_model + rule_request_model['enforcement_actions'] = [enforcement_action_model] + rule_request_model['labels'] = ['testString'] + + # Construct a json representation of a CreateRuleRequest model + create_rule_request_model_json = {} + create_rule_request_model_json['request_id'] = '3cebc877-58e7-44a5-a292-32114fa73558' + create_rule_request_model_json['rule'] = rule_request_model + + # Construct a model instance of CreateRuleRequest by calling from_dict on the json representation + create_rule_request_model = CreateRuleRequest.from_dict(create_rule_request_model_json) + assert create_rule_request_model != False + + # Construct a model instance of CreateRuleRequest by calling from_dict on the json representation + create_rule_request_model_dict = CreateRuleRequest.from_dict(create_rule_request_model_json).__dict__ + create_rule_request_model2 = CreateRuleRequest(**create_rule_request_model_dict) + + # Verify the model instances are equivalent + assert create_rule_request_model == create_rule_request_model2 + + # Convert model instance back to dict and verify no loss of data + create_rule_request_model_json2 = create_rule_request_model.to_dict() + assert create_rule_request_model_json2 == create_rule_request_model_json + +class TestCreateRuleResponse(): + """ + Test Class for CreateRuleResponse + """ + + def test_create_rule_response_serialization(self): + """ + Test serialization/deserialization for CreateRuleResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_target_attribute_model = {} # RuleTargetAttribute + rule_target_attribute_model['name'] = 'resource_id' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'f0f8f7994e754ff38f9d370201966561' + + target_resource_model = {} # TargetResource + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'zone' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + rule_required_config_model = {} # RuleRequiredConfigSingleProperty + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + enforcement_action_model = {} # EnforcementAction + enforcement_action_model['action'] = 'disallow' + + rule_model = {} # Rule + rule_model['account_id'] = 'testString' + rule_model['name'] = 'testString' + rule_model['description'] = 'testString' + rule_model['rule_type'] = 'user_defined' + rule_model['target'] = target_resource_model + rule_model['required_config'] = rule_required_config_model + rule_model['enforcement_actions'] = [enforcement_action_model] + rule_model['labels'] = ['testString'] + rule_model['rule_id'] = 'rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf' + rule_model['creation_date'] = '2020-01-10T05:23:19+0000' + rule_model['created_by'] = 'testString' + rule_model['modification_date'] = 'testString' + rule_model['modified_by'] = 'testString' + rule_model['number_of_attachments'] = 3 + + rule_response_error_model = {} # RuleResponseError + rule_response_error_model['code'] = 'bad_request' + rule_response_error_model['message'] = 'The rule is missing an account ID' + + # Construct a json representation of a CreateRuleResponse model + create_rule_response_model_json = {} + create_rule_response_model_json['request_id'] = '3cebc877-58e7-44a5-a292-32114fa73558' + create_rule_response_model_json['status_code'] = 201 + create_rule_response_model_json['rule'] = rule_model + create_rule_response_model_json['errors'] = [rule_response_error_model] + create_rule_response_model_json['trace'] = '861263b4-cee3-4514-8d8c-05d17308e6eb' + + # Construct a model instance of CreateRuleResponse by calling from_dict on the json representation + create_rule_response_model = CreateRuleResponse.from_dict(create_rule_response_model_json) + assert create_rule_response_model != False + + # Construct a model instance of CreateRuleResponse by calling from_dict on the json representation + create_rule_response_model_dict = CreateRuleResponse.from_dict(create_rule_response_model_json).__dict__ + create_rule_response_model2 = CreateRuleResponse(**create_rule_response_model_dict) + + # Verify the model instances are equivalent + assert create_rule_response_model == create_rule_response_model2 + + # Convert model instance back to dict and verify no loss of data + create_rule_response_model_json2 = create_rule_response_model.to_dict() + assert create_rule_response_model_json2 == create_rule_response_model_json + +class TestCreateRulesResponse(): + """ + Test Class for CreateRulesResponse + """ + + def test_create_rules_response_serialization(self): + """ + Test serialization/deserialization for CreateRulesResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_target_attribute_model = {} # RuleTargetAttribute + rule_target_attribute_model['name'] = 'resource_id' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'f0f8f7994e754ff38f9d370201966561' + + target_resource_model = {} # TargetResource + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'zone' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + rule_required_config_model = {} # RuleRequiredConfigSingleProperty + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + enforcement_action_model = {} # EnforcementAction + enforcement_action_model['action'] = 'disallow' + + rule_model = {} # Rule + rule_model['account_id'] = 'testString' + rule_model['name'] = 'testString' + rule_model['description'] = 'testString' + rule_model['rule_type'] = 'user_defined' + rule_model['target'] = target_resource_model + rule_model['required_config'] = rule_required_config_model + rule_model['enforcement_actions'] = [enforcement_action_model] + rule_model['labels'] = ['testString'] + rule_model['rule_id'] = 'rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf' + rule_model['creation_date'] = '2020-01-10T05:23:19+0000' + rule_model['created_by'] = 'testString' + rule_model['modification_date'] = 'testString' + rule_model['modified_by'] = 'testString' + rule_model['number_of_attachments'] = 3 + + rule_response_error_model = {} # RuleResponseError + rule_response_error_model['code'] = 'bad_request' + rule_response_error_model['message'] = 'The rule is missing an account ID' + + create_rule_response_model = {} # CreateRuleResponse + create_rule_response_model['request_id'] = '3cebc877-58e7-44a5-a292-32114fa73558' + create_rule_response_model['status_code'] = 201 + create_rule_response_model['rule'] = rule_model + create_rule_response_model['errors'] = [rule_response_error_model] + create_rule_response_model['trace'] = '861263b4-cee3-4514-8d8c-05d17308e6eb' + + # Construct a json representation of a CreateRulesResponse model + create_rules_response_model_json = {} + create_rules_response_model_json['rules'] = [create_rule_response_model] + + # Construct a model instance of CreateRulesResponse by calling from_dict on the json representation + create_rules_response_model = CreateRulesResponse.from_dict(create_rules_response_model_json) + assert create_rules_response_model != False + + # Construct a model instance of CreateRulesResponse by calling from_dict on the json representation + create_rules_response_model_dict = CreateRulesResponse.from_dict(create_rules_response_model_json).__dict__ + create_rules_response_model2 = CreateRulesResponse(**create_rules_response_model_dict) + + # Verify the model instances are equivalent + assert create_rules_response_model == create_rules_response_model2 + + # Convert model instance back to dict and verify no loss of data + create_rules_response_model_json2 = create_rules_response_model.to_dict() + assert create_rules_response_model_json2 == create_rules_response_model_json + +class TestEnforcementAction(): + """ + Test Class for EnforcementAction + """ + + def test_enforcement_action_serialization(self): + """ + Test serialization/deserialization for EnforcementAction + """ + + # Construct a json representation of a EnforcementAction model + enforcement_action_model_json = {} + enforcement_action_model_json['action'] = 'audit_log' + + # Construct a model instance of EnforcementAction by calling from_dict on the json representation + enforcement_action_model = EnforcementAction.from_dict(enforcement_action_model_json) + assert enforcement_action_model != False + + # Construct a model instance of EnforcementAction by calling from_dict on the json representation + enforcement_action_model_dict = EnforcementAction.from_dict(enforcement_action_model_json).__dict__ + enforcement_action_model2 = EnforcementAction(**enforcement_action_model_dict) + + # Verify the model instances are equivalent + assert enforcement_action_model == enforcement_action_model2 + + # Convert model instance back to dict and verify no loss of data + enforcement_action_model_json2 = enforcement_action_model.to_dict() + assert enforcement_action_model_json2 == enforcement_action_model_json + +class TestLink(): + """ + Test Class for Link + """ + + def test_link_serialization(self): + """ + Test serialization/deserialization for Link + """ + + # Construct a json representation of a Link model + link_model_json = {} + link_model_json['href'] = 'testString' + + # Construct a model instance of Link by calling from_dict on the json representation + link_model = Link.from_dict(link_model_json) + assert link_model != False + + # Construct a model instance of Link by calling from_dict on the json representation + link_model_dict = Link.from_dict(link_model_json).__dict__ + link_model2 = Link(**link_model_dict) + + # Verify the model instances are equivalent + assert link_model == link_model2 + + # Convert model instance back to dict and verify no loss of data + link_model_json2 = link_model.to_dict() + assert link_model_json2 == link_model_json + +class TestRule(): + """ + Test Class for Rule + """ + + def test_rule_serialization(self): + """ + Test serialization/deserialization for Rule + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_target_attribute_model = {} # RuleTargetAttribute + rule_target_attribute_model['name'] = 'resource_id' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'f0f8f7994e754ff38f9d370201966561' + + target_resource_model = {} # TargetResource + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'zone' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + rule_required_config_model = {} # RuleRequiredConfigSingleProperty + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + enforcement_action_model = {} # EnforcementAction + enforcement_action_model['action'] = 'disallow' + + # Construct a json representation of a Rule model + rule_model_json = {} + rule_model_json['account_id'] = 'testString' + rule_model_json['name'] = 'testString' + rule_model_json['description'] = 'testString' + rule_model_json['rule_type'] = 'user_defined' + rule_model_json['target'] = target_resource_model + rule_model_json['required_config'] = rule_required_config_model + rule_model_json['enforcement_actions'] = [enforcement_action_model] + rule_model_json['labels'] = ['testString'] + rule_model_json['rule_id'] = 'rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf' + rule_model_json['creation_date'] = '2020-01-10T05:23:19+0000' + rule_model_json['created_by'] = 'testString' + rule_model_json['modification_date'] = 'testString' + rule_model_json['modified_by'] = 'testString' + rule_model_json['number_of_attachments'] = 3 + + # Construct a model instance of Rule by calling from_dict on the json representation + rule_model = Rule.from_dict(rule_model_json) + assert rule_model != False + + # Construct a model instance of Rule by calling from_dict on the json representation + rule_model_dict = Rule.from_dict(rule_model_json).__dict__ + rule_model2 = Rule(**rule_model_dict) + + # Verify the model instances are equivalent + assert rule_model == rule_model2 + + # Convert model instance back to dict and verify no loss of data + rule_model_json2 = rule_model.to_dict() + assert rule_model_json2 == rule_model_json + +class TestRuleList(): + """ + Test Class for RuleList + """ + + def test_rule_list_serialization(self): + """ + Test serialization/deserialization for RuleList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + link_model = {} # Link + link_model['href'] = 'testString' + + rule_target_attribute_model = {} # RuleTargetAttribute + rule_target_attribute_model['name'] = 'resource_id' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'f0f8f7994e754ff38f9d370201966561' + + target_resource_model = {} # TargetResource + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'zone' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + rule_required_config_model = {} # RuleRequiredConfigSingleProperty + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + enforcement_action_model = {} # EnforcementAction + enforcement_action_model['action'] = 'disallow' + + rule_model = {} # Rule + rule_model['account_id'] = 'testString' + rule_model['name'] = 'testString' + rule_model['description'] = 'testString' + rule_model['rule_type'] = 'user_defined' + rule_model['target'] = target_resource_model + rule_model['required_config'] = rule_required_config_model + rule_model['enforcement_actions'] = [enforcement_action_model] + rule_model['labels'] = ['testString'] + rule_model['rule_id'] = 'rule-81f3db5e-f9db-4c46-9de3-a4a76e66adbf' + rule_model['creation_date'] = '2020-01-10T05:23:19+0000' + rule_model['created_by'] = 'testString' + rule_model['modification_date'] = 'testString' + rule_model['modified_by'] = 'testString' + rule_model['number_of_attachments'] = 3 + + # Construct a json representation of a RuleList model + rule_list_model_json = {} + rule_list_model_json['offset'] = 38 + rule_list_model_json['limit'] = 1000 + rule_list_model_json['total_count'] = 38 + rule_list_model_json['first'] = link_model + rule_list_model_json['last'] = link_model + rule_list_model_json['rules'] = [rule_model] + + # Construct a model instance of RuleList by calling from_dict on the json representation + rule_list_model = RuleList.from_dict(rule_list_model_json) + assert rule_list_model != False + + # Construct a model instance of RuleList by calling from_dict on the json representation + rule_list_model_dict = RuleList.from_dict(rule_list_model_json).__dict__ + rule_list_model2 = RuleList(**rule_list_model_dict) + + # Verify the model instances are equivalent + assert rule_list_model == rule_list_model2 + + # Convert model instance back to dict and verify no loss of data + rule_list_model_json2 = rule_list_model.to_dict() + assert rule_list_model_json2 == rule_list_model_json + +class TestRuleRequest(): + """ + Test Class for RuleRequest + """ + + def test_rule_request_serialization(self): + """ + Test serialization/deserialization for RuleRequest + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_target_attribute_model = {} # RuleTargetAttribute + rule_target_attribute_model['name'] = 'resource_id' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'f0f8f7994e754ff38f9d370201966561' + + target_resource_model = {} # TargetResource + target_resource_model['service_name'] = 'iam-groups' + target_resource_model['resource_kind'] = 'zone' + target_resource_model['additional_target_attributes'] = [rule_target_attribute_model] + + rule_required_config_model = {} # RuleRequiredConfigSingleProperty + rule_required_config_model['description'] = 'testString' + rule_required_config_model['property'] = 'public_access_enabled' + rule_required_config_model['operator'] = 'is_true' + rule_required_config_model['value'] = 'testString' + + enforcement_action_model = {} # EnforcementAction + enforcement_action_model['action'] = 'disallow' + + # Construct a json representation of a RuleRequest model + rule_request_model_json = {} + rule_request_model_json['account_id'] = 'testString' + rule_request_model_json['name'] = 'testString' + rule_request_model_json['description'] = 'testString' + rule_request_model_json['rule_type'] = 'user_defined' + rule_request_model_json['target'] = target_resource_model + rule_request_model_json['required_config'] = rule_required_config_model + rule_request_model_json['enforcement_actions'] = [enforcement_action_model] + rule_request_model_json['labels'] = ['testString'] + + # Construct a model instance of RuleRequest by calling from_dict on the json representation + rule_request_model = RuleRequest.from_dict(rule_request_model_json) + assert rule_request_model != False + + # Construct a model instance of RuleRequest by calling from_dict on the json representation + rule_request_model_dict = RuleRequest.from_dict(rule_request_model_json).__dict__ + rule_request_model2 = RuleRequest(**rule_request_model_dict) + + # Verify the model instances are equivalent + assert rule_request_model == rule_request_model2 + + # Convert model instance back to dict and verify no loss of data + rule_request_model_json2 = rule_request_model.to_dict() + assert rule_request_model_json2 == rule_request_model_json + +class TestRuleResponseError(): + """ + Test Class for RuleResponseError + """ + + def test_rule_response_error_serialization(self): + """ + Test serialization/deserialization for RuleResponseError + """ + + # Construct a json representation of a RuleResponseError model + rule_response_error_model_json = {} + rule_response_error_model_json['code'] = 'bad_request' + rule_response_error_model_json['message'] = 'The rule is missing an account ID' + + # Construct a model instance of RuleResponseError by calling from_dict on the json representation + rule_response_error_model = RuleResponseError.from_dict(rule_response_error_model_json) + assert rule_response_error_model != False + + # Construct a model instance of RuleResponseError by calling from_dict on the json representation + rule_response_error_model_dict = RuleResponseError.from_dict(rule_response_error_model_json).__dict__ + rule_response_error_model2 = RuleResponseError(**rule_response_error_model_dict) + + # Verify the model instances are equivalent + assert rule_response_error_model == rule_response_error_model2 + + # Convert model instance back to dict and verify no loss of data + rule_response_error_model_json2 = rule_response_error_model.to_dict() + assert rule_response_error_model_json2 == rule_response_error_model_json + +class TestRuleScope(): + """ + Test Class for RuleScope + """ + + def test_rule_scope_serialization(self): + """ + Test serialization/deserialization for RuleScope + """ + + # Construct a json representation of a RuleScope model + rule_scope_model_json = {} + rule_scope_model_json['note'] = 'testString' + rule_scope_model_json['scope_id'] = 'testString' + rule_scope_model_json['scope_type'] = 'enterprise' + + # Construct a model instance of RuleScope by calling from_dict on the json representation + rule_scope_model = RuleScope.from_dict(rule_scope_model_json) + assert rule_scope_model != False + + # Construct a model instance of RuleScope by calling from_dict on the json representation + rule_scope_model_dict = RuleScope.from_dict(rule_scope_model_json).__dict__ + rule_scope_model2 = RuleScope(**rule_scope_model_dict) + + # Verify the model instances are equivalent + assert rule_scope_model == rule_scope_model2 + + # Convert model instance back to dict and verify no loss of data + rule_scope_model_json2 = rule_scope_model.to_dict() + assert rule_scope_model_json2 == rule_scope_model_json + +class TestRuleSingleProperty(): + """ + Test Class for RuleSingleProperty + """ + + def test_rule_single_property_serialization(self): + """ + Test serialization/deserialization for RuleSingleProperty + """ + + # Construct a json representation of a RuleSingleProperty model + rule_single_property_model_json = {} + rule_single_property_model_json['description'] = 'testString' + rule_single_property_model_json['property'] = 'public_access_enabled' + rule_single_property_model_json['operator'] = 'is_true' + rule_single_property_model_json['value'] = 'testString' + + # Construct a model instance of RuleSingleProperty by calling from_dict on the json representation + rule_single_property_model = RuleSingleProperty.from_dict(rule_single_property_model_json) + assert rule_single_property_model != False + + # Construct a model instance of RuleSingleProperty by calling from_dict on the json representation + rule_single_property_model_dict = RuleSingleProperty.from_dict(rule_single_property_model_json).__dict__ + rule_single_property_model2 = RuleSingleProperty(**rule_single_property_model_dict) + + # Verify the model instances are equivalent + assert rule_single_property_model == rule_single_property_model2 + + # Convert model instance back to dict and verify no loss of data + rule_single_property_model_json2 = rule_single_property_model.to_dict() + assert rule_single_property_model_json2 == rule_single_property_model_json + +class TestRuleTargetAttribute(): + """ + Test Class for RuleTargetAttribute + """ + + def test_rule_target_attribute_serialization(self): + """ + Test serialization/deserialization for RuleTargetAttribute + """ + + # Construct a json representation of a RuleTargetAttribute model + rule_target_attribute_model_json = {} + rule_target_attribute_model_json['name'] = 'testString' + rule_target_attribute_model_json['operator'] = 'string_equals' + rule_target_attribute_model_json['value'] = 'testString' + + # Construct a model instance of RuleTargetAttribute by calling from_dict on the json representation + rule_target_attribute_model = RuleTargetAttribute.from_dict(rule_target_attribute_model_json) + assert rule_target_attribute_model != False + + # Construct a model instance of RuleTargetAttribute by calling from_dict on the json representation + rule_target_attribute_model_dict = RuleTargetAttribute.from_dict(rule_target_attribute_model_json).__dict__ + rule_target_attribute_model2 = RuleTargetAttribute(**rule_target_attribute_model_dict) + + # Verify the model instances are equivalent + assert rule_target_attribute_model == rule_target_attribute_model2 + + # Convert model instance back to dict and verify no loss of data + rule_target_attribute_model_json2 = rule_target_attribute_model.to_dict() + assert rule_target_attribute_model_json2 == rule_target_attribute_model_json + +class TestTargetResource(): + """ + Test Class for TargetResource + """ + + def test_target_resource_serialization(self): + """ + Test serialization/deserialization for TargetResource + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_target_attribute_model = {} # RuleTargetAttribute + rule_target_attribute_model['name'] = 'resource_id' + rule_target_attribute_model['operator'] = 'string_equals' + rule_target_attribute_model['value'] = 'f0f8f7994e754ff38f9d370201966561' + + # Construct a json representation of a TargetResource model + target_resource_model_json = {} + target_resource_model_json['service_name'] = 'iam-groups' + target_resource_model_json['resource_kind'] = 'zone' + target_resource_model_json['additional_target_attributes'] = [rule_target_attribute_model] + + # Construct a model instance of TargetResource by calling from_dict on the json representation + target_resource_model = TargetResource.from_dict(target_resource_model_json) + assert target_resource_model != False + + # Construct a model instance of TargetResource by calling from_dict on the json representation + target_resource_model_dict = TargetResource.from_dict(target_resource_model_json).__dict__ + target_resource_model2 = TargetResource(**target_resource_model_dict) + + # Verify the model instances are equivalent + assert target_resource_model == target_resource_model2 + + # Convert model instance back to dict and verify no loss of data + target_resource_model_json2 = target_resource_model.to_dict() + assert target_resource_model_json2 == target_resource_model_json + +class TestRuleConditionAndLvl2(): + """ + Test Class for RuleConditionAndLvl2 + """ + + def test_rule_condition_and_lvl2_serialization(self): + """ + Test serialization/deserialization for RuleConditionAndLvl2 + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_single_property_model = {} # RuleSingleProperty + rule_single_property_model['description'] = 'testString' + rule_single_property_model['property'] = 'public_access_enabled' + rule_single_property_model['operator'] = 'is_true' + rule_single_property_model['value'] = 'testString' + + # Construct a json representation of a RuleConditionAndLvl2 model + rule_condition_and_lvl2_model_json = {} + rule_condition_and_lvl2_model_json['description'] = 'testString' + rule_condition_and_lvl2_model_json['and'] = [rule_single_property_model] + + # Construct a model instance of RuleConditionAndLvl2 by calling from_dict on the json representation + rule_condition_and_lvl2_model = RuleConditionAndLvl2.from_dict(rule_condition_and_lvl2_model_json) + assert rule_condition_and_lvl2_model != False + + # Construct a model instance of RuleConditionAndLvl2 by calling from_dict on the json representation + rule_condition_and_lvl2_model_dict = RuleConditionAndLvl2.from_dict(rule_condition_and_lvl2_model_json).__dict__ + rule_condition_and_lvl2_model2 = RuleConditionAndLvl2(**rule_condition_and_lvl2_model_dict) + + # Verify the model instances are equivalent + assert rule_condition_and_lvl2_model == rule_condition_and_lvl2_model2 + + # Convert model instance back to dict and verify no loss of data + rule_condition_and_lvl2_model_json2 = rule_condition_and_lvl2_model.to_dict() + assert rule_condition_and_lvl2_model_json2 == rule_condition_and_lvl2_model_json + +class TestRuleConditionOrLvl2(): + """ + Test Class for RuleConditionOrLvl2 + """ + + def test_rule_condition_or_lvl2_serialization(self): + """ + Test serialization/deserialization for RuleConditionOrLvl2 + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_single_property_model = {} # RuleSingleProperty + rule_single_property_model['description'] = 'testString' + rule_single_property_model['property'] = 'public_access_enabled' + rule_single_property_model['operator'] = 'is_true' + rule_single_property_model['value'] = 'testString' + + # Construct a json representation of a RuleConditionOrLvl2 model + rule_condition_or_lvl2_model_json = {} + rule_condition_or_lvl2_model_json['description'] = 'testString' + rule_condition_or_lvl2_model_json['or'] = [rule_single_property_model] + + # Construct a model instance of RuleConditionOrLvl2 by calling from_dict on the json representation + rule_condition_or_lvl2_model = RuleConditionOrLvl2.from_dict(rule_condition_or_lvl2_model_json) + assert rule_condition_or_lvl2_model != False + + # Construct a model instance of RuleConditionOrLvl2 by calling from_dict on the json representation + rule_condition_or_lvl2_model_dict = RuleConditionOrLvl2.from_dict(rule_condition_or_lvl2_model_json).__dict__ + rule_condition_or_lvl2_model2 = RuleConditionOrLvl2(**rule_condition_or_lvl2_model_dict) + + # Verify the model instances are equivalent + assert rule_condition_or_lvl2_model == rule_condition_or_lvl2_model2 + + # Convert model instance back to dict and verify no loss of data + rule_condition_or_lvl2_model_json2 = rule_condition_or_lvl2_model.to_dict() + assert rule_condition_or_lvl2_model_json2 == rule_condition_or_lvl2_model_json + +class TestRuleConditionSingleProperty(): + """ + Test Class for RuleConditionSingleProperty + """ + + def test_rule_condition_single_property_serialization(self): + """ + Test serialization/deserialization for RuleConditionSingleProperty + """ + + # Construct a json representation of a RuleConditionSingleProperty model + rule_condition_single_property_model_json = {} + rule_condition_single_property_model_json['description'] = 'testString' + rule_condition_single_property_model_json['property'] = 'public_access_enabled' + rule_condition_single_property_model_json['operator'] = 'is_true' + rule_condition_single_property_model_json['value'] = 'testString' + + # Construct a model instance of RuleConditionSingleProperty by calling from_dict on the json representation + rule_condition_single_property_model = RuleConditionSingleProperty.from_dict(rule_condition_single_property_model_json) + assert rule_condition_single_property_model != False + + # Construct a model instance of RuleConditionSingleProperty by calling from_dict on the json representation + rule_condition_single_property_model_dict = RuleConditionSingleProperty.from_dict(rule_condition_single_property_model_json).__dict__ + rule_condition_single_property_model2 = RuleConditionSingleProperty(**rule_condition_single_property_model_dict) + + # Verify the model instances are equivalent + assert rule_condition_single_property_model == rule_condition_single_property_model2 + + # Convert model instance back to dict and verify no loss of data + rule_condition_single_property_model_json2 = rule_condition_single_property_model.to_dict() + assert rule_condition_single_property_model_json2 == rule_condition_single_property_model_json + +class TestRuleRequiredConfigSingleProperty(): + """ + Test Class for RuleRequiredConfigSingleProperty + """ + + def test_rule_required_config_single_property_serialization(self): + """ + Test serialization/deserialization for RuleRequiredConfigSingleProperty + """ + + # Construct a json representation of a RuleRequiredConfigSingleProperty model + rule_required_config_single_property_model_json = {} + rule_required_config_single_property_model_json['description'] = 'testString' + rule_required_config_single_property_model_json['property'] = 'public_access_enabled' + rule_required_config_single_property_model_json['operator'] = 'is_true' + rule_required_config_single_property_model_json['value'] = 'testString' + + # Construct a model instance of RuleRequiredConfigSingleProperty by calling from_dict on the json representation + rule_required_config_single_property_model = RuleRequiredConfigSingleProperty.from_dict(rule_required_config_single_property_model_json) + assert rule_required_config_single_property_model != False + + # Construct a model instance of RuleRequiredConfigSingleProperty by calling from_dict on the json representation + rule_required_config_single_property_model_dict = RuleRequiredConfigSingleProperty.from_dict(rule_required_config_single_property_model_json).__dict__ + rule_required_config_single_property_model2 = RuleRequiredConfigSingleProperty(**rule_required_config_single_property_model_dict) + + # Verify the model instances are equivalent + assert rule_required_config_single_property_model == rule_required_config_single_property_model2 + + # Convert model instance back to dict and verify no loss of data + rule_required_config_single_property_model_json2 = rule_required_config_single_property_model.to_dict() + assert rule_required_config_single_property_model_json2 == rule_required_config_single_property_model_json + +class TestRuleRequiredConfigMultiplePropertiesConditionAnd(): + """ + Test Class for RuleRequiredConfigMultiplePropertiesConditionAnd + """ + + def test_rule_required_config_multiple_properties_condition_and_serialization(self): + """ + Test serialization/deserialization for RuleRequiredConfigMultiplePropertiesConditionAnd + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_condition_model = {} # RuleConditionSingleProperty + rule_condition_model['description'] = 'testString' + rule_condition_model['property'] = 'public_access_enabled' + rule_condition_model['operator'] = 'is_true' + rule_condition_model['value'] = 'testString' + + # Construct a json representation of a RuleRequiredConfigMultiplePropertiesConditionAnd model + rule_required_config_multiple_properties_condition_and_model_json = {} + rule_required_config_multiple_properties_condition_and_model_json['description'] = 'testString' + rule_required_config_multiple_properties_condition_and_model_json['and'] = [rule_condition_model] + + # Construct a model instance of RuleRequiredConfigMultiplePropertiesConditionAnd by calling from_dict on the json representation + rule_required_config_multiple_properties_condition_and_model = RuleRequiredConfigMultiplePropertiesConditionAnd.from_dict(rule_required_config_multiple_properties_condition_and_model_json) + assert rule_required_config_multiple_properties_condition_and_model != False + + # Construct a model instance of RuleRequiredConfigMultiplePropertiesConditionAnd by calling from_dict on the json representation + rule_required_config_multiple_properties_condition_and_model_dict = RuleRequiredConfigMultiplePropertiesConditionAnd.from_dict(rule_required_config_multiple_properties_condition_and_model_json).__dict__ + rule_required_config_multiple_properties_condition_and_model2 = RuleRequiredConfigMultiplePropertiesConditionAnd(**rule_required_config_multiple_properties_condition_and_model_dict) + + # Verify the model instances are equivalent + assert rule_required_config_multiple_properties_condition_and_model == rule_required_config_multiple_properties_condition_and_model2 + + # Convert model instance back to dict and verify no loss of data + rule_required_config_multiple_properties_condition_and_model_json2 = rule_required_config_multiple_properties_condition_and_model.to_dict() + assert rule_required_config_multiple_properties_condition_and_model_json2 == rule_required_config_multiple_properties_condition_and_model_json + +class TestRuleRequiredConfigMultiplePropertiesConditionOr(): + """ + Test Class for RuleRequiredConfigMultiplePropertiesConditionOr + """ + + def test_rule_required_config_multiple_properties_condition_or_serialization(self): + """ + Test serialization/deserialization for RuleRequiredConfigMultiplePropertiesConditionOr + """ + + # Construct dict forms of any model objects needed in order to build this model. + + rule_condition_model = {} # RuleConditionSingleProperty + rule_condition_model['description'] = 'testString' + rule_condition_model['property'] = 'public_access_enabled' + rule_condition_model['operator'] = 'is_true' + rule_condition_model['value'] = 'testString' + + # Construct a json representation of a RuleRequiredConfigMultiplePropertiesConditionOr model + rule_required_config_multiple_properties_condition_or_model_json = {} + rule_required_config_multiple_properties_condition_or_model_json['description'] = 'testString' + rule_required_config_multiple_properties_condition_or_model_json['or'] = [rule_condition_model] + + # Construct a model instance of RuleRequiredConfigMultiplePropertiesConditionOr by calling from_dict on the json representation + rule_required_config_multiple_properties_condition_or_model = RuleRequiredConfigMultiplePropertiesConditionOr.from_dict(rule_required_config_multiple_properties_condition_or_model_json) + assert rule_required_config_multiple_properties_condition_or_model != False + + # Construct a model instance of RuleRequiredConfigMultiplePropertiesConditionOr by calling from_dict on the json representation + rule_required_config_multiple_properties_condition_or_model_dict = RuleRequiredConfigMultiplePropertiesConditionOr.from_dict(rule_required_config_multiple_properties_condition_or_model_json).__dict__ + rule_required_config_multiple_properties_condition_or_model2 = RuleRequiredConfigMultiplePropertiesConditionOr(**rule_required_config_multiple_properties_condition_or_model_dict) + + # Verify the model instances are equivalent + assert rule_required_config_multiple_properties_condition_or_model == rule_required_config_multiple_properties_condition_or_model2 + + # Convert model instance back to dict and verify no loss of data + rule_required_config_multiple_properties_condition_or_model_json2 = rule_required_config_multiple_properties_condition_or_model.to_dict() + assert rule_required_config_multiple_properties_condition_or_model_json2 == rule_required_config_multiple_properties_condition_or_model_json + + +# endregion +############################################################################## +# End of Model Tests +##############################################################################