def test_verify_action_to_sdc_not_created(mock_created, mock_action, mock_load): mock_created.return_value = False svc = Service() svc._status = "no_yes" svc._verify_action_to_sdc("yes", "action", action_type='lifecycleState') mock_created.assert_called() mock_action.assert_not_called() mock_load.assert_not_called()
def test_add_properties(mock_send_message_json): service = Service(name="test") service._identifier = "toto" service._unique_identifier = "toto" service._status = const.CERTIFIED with pytest.raises(AttributeError): service.add_property(Property(name="test", property_type="string")) service._status = const.DRAFT service.add_property(Property(name="test", property_type="string")) mock_send_message_json.assert_called_once()
def test_get_vnf_unique_id(mock_send): """Test Service get nf uid with One Vf""" svc = Service() svc.unique_identifier = "service_unique_identifier" mock_send.return_value = ARTIFACTS unique_id = svc.get_nf_unique_id(nf_name="ubuntu16test_VF 0") mock_send.assert_called_once_with( 'GET', 'Get nf unique ID', f"https://sdc.api.fe.simpledemo.onap.org:30207/sdc1/feProxy/rest/v1/catalog/services/{svc.unique_identifier}" ) assert unique_id == 'test_unique_id'
def test_init_no_name(): """Check init with no names.""" svc = Service() assert isinstance(svc, SdcResource) assert svc._identifier is None assert svc._version is None assert svc.name == "ONAP-test-Service" assert svc.headers["USER_ID"] == "cs0008" assert svc.distribution_status is None assert svc._distribution_id is None assert isinstance(svc._base_url(), str)
def test_get_tosca_result(requests_mock): if path.exists('/tmp/tosca_files'): shutil.rmtree('/tmp/tosca_files') with open('tests/data/test.csar', mode='rb') as file: file_content = file.read() requests_mock.get( 'https://sdc.api.be.simpledemo.onap.org:30204/sdc/v1/catalog/services/12/toscaModel', content=file_content) svc = Service() svc.identifier = "12" svc.get_tosca()
def test_load_metadata_bad_json(mock_send): mock_send.return_value = {'yolo': 'in the wood'} svc = Service() svc.identifier = "1" svc.load_metadata() assert svc._distribution_id is None mock_send.assert_called_once_with( 'GET', 'Get Metadata for ONAP-test-Service', 'https://sdc.api.fe.simpledemo.onap.org:30207/sdc1/feProxy/rest/v1/catalog/services/1/distribution', headers=headers_sdc_creator(svc.headers))
def test_vnf_two_vf_modules(): """Test parsing TOSCA file with two VNF which has associated one VFmodule""" service = Service(name="test") with open( Path( Path(__file__).resolve().parent, "data/service-VfwcdsService-template.yml"), "r") as template: service._tosca_template = yaml.safe_load(template.read()) assert len(service.vnfs) == 1 vnf = service.vnfs[0] assert len(vnf.vf_modules) == 4
def test_init_with_name(mock_exists): """Check init with no names.""" mock_exists.return_value = False svc = Service(name="YOLO") assert svc._identifier == None assert svc._version == None assert svc.name == "YOLO" assert svc.created() == False assert svc.headers["USER_ID"] == "cs0008" assert svc.distribution_status is None assert svc._distribution_id is None assert isinstance(svc._base_url(), str)
def test_pnf_modules_one(): """Test parsing TOSCA file with one PNF which has associated one PNFmodule""" service = Service(name="test") with open( Path( Path(__file__).resolve().parent, "data/service-TestPnfVsp-template.yml"), "r") as pnf: service._tosca_template = yaml.safe_load(pnf.read()) assert len(service.pnfs) == 1 pnf = service.pnfs[0] assert pnf.name == "test_pnf_vsp 0" assert pnf.node_template_type == "org.openecomp.resource.pnf.TestPnfVsp"
def test_declare_resources_and_properties(mock_declare_input, mock_add_property, mock_add_resource): service = Service( name="test", resources=[SdcResource()], properties=[Property(name="test", property_type="string")], inputs=[Property(name="test", property_type="string")]) service.declare_resources_and_properties() mock_add_resource.assert_called_once() mock_add_property.assert_called_once() mock_declare_input.assert_called_once()
def test_service_networks(): service = Service(name="test") with open( Path( Path(__file__).resolve().parent, "data/service-TestServiceFyx-template.yml"), "r") as service_file: service._tosca_template = yaml.safe_load(service_file.read()) assert len(service.networks) == 1 network = service.networks[0] assert network.name == "NeutronNet 0" assert network.node_template_type == "org.openecomp.resource.vl.nodes.heat.network.neutron.Net"
def test_service_upload_tca_artifact(): """Integration tests for Service.""" response = requests.post("{}/reset".format(SDC.base_front_url)) response.raise_for_status() vendor = Vendor(name="test") vendor.onboard() vsp = Vsp(name="test", package=open( "{}/ubuntu16.zip".format( os.path.dirname(os.path.abspath(__file__))), 'rb')) vsp.vendor = vendor vsp.onboard() vf = Vf(name='test', vsp=vsp) vf.onboard() svc = Service(name='test') svc.create() svc.add_resource(vf) assert svc.status == const.DRAFT payload_file = open( "{}/tca_clampnode.yaml".format( os.path.dirname(os.path.abspath(__file__))), 'rb') data = payload_file.read() svc.add_artifact_to_vf(vnf_name="test", artifact_type="DCAE_INVENTORY_BLUEPRINT", artifact_name="tca_clampnode.yaml", artifact=data) payload_file.close()
def test_subscribe_service(): requests.get(f"{Customer.base_url}/reset") customer = Customer.create(global_customer_id="test_global_customer_id", subscriber_name="test_subscriber_name", subscriber_type="test_subscriber_type") assert len(list(customer.service_subscriptions)) == 0 service = Service("test_service") service.unique_uuid = str(uuid4()) customer.subscribe_service(service) assert len(list(customer.service_subscriptions)) == 1 assert customer.get_service_subscription_by_service_type(service.name)
def test_vnf_vf_modules_one(): """Test parsing TOSCA file with one VNF which has associated one VFmodule""" service = Service(name="test") with open( Path( Path(__file__).resolve().parent, "data/service-Ubuntu16-template.yml"), "r") as ubuntu: service._tosca_template = yaml.safe_load(ubuntu.read()) assert len(service.vnfs) == 1 vnf = service.vnfs[0] assert vnf.name == "ubuntu16_VF 0" assert vnf.node_template_type == "org.openecomp.resource.vf.Ubuntu16Vf" assert vnf.vf_modules assert vnf.vf_modules[ 0].name == "ubuntu16_vf0..Ubuntu16Vf..base_ubuntu16..module-0"
def test_get_tosca_no_result(mock_send): if path.exists('/tmp/tosca_files'): shutil.rmtree('/tmp/tosca_files') mock_send.return_value = {} svc = Service() svc.identifier = "12" svc.get_tosca() headers = headers_sdc_creator(svc.headers) headers['Accept'] = 'application/octet-stream' mock_send.assert_called_once_with( 'GET', 'Download Tosca Model for ONAP-test-Service', 'https://sdc.api.be.simpledemo.onap.org:30204/sdc/v1/catalog/services/12/toscaModel', headers=headers) assert not path.exists('/tmp/tosca_files')
def test_add_artifact_to_vf(mock_send_message, mock_load, mock_add): """Test Service add artifact""" svc = Service() mock_add.return_value = "54321" result = svc.add_artifact_to_vf(vnf_name="ubuntu16test_VF 0", artifact_type="DCAE_INVENTORY_BLUEPRINT", artifact_name="clampnode.yaml", artifact="data".encode('utf-8')) mock_send_message.assert_called() method, description, url = mock_send_message.call_args[0] assert method == "POST" assert description == "Add artifact to vf" assert url == ( "https://sdc.api.fe.simpledemo.onap.org:30207/sdc1/feProxy/rest/v1/catalog/services/" f"{svc.unique_identifier}/resourceInstance/54321/artifacts")
def test_service_category(mock_resource_category, mock_created): mock_created.return_value = False service = Service(name="test") _ = service.category mock_resource_category.assert_called_once_with(name="Network Service") mock_resource_category.reset_mock() service = Service(name="test", category="test") _ = service.category mock_resource_category.assert_called_once_with(name="test") mock_resource_category.reset_mock() mock_created.return_value = True _ = service.category mock_resource_category.assert_called_once_with(name="test")
def test_service_components(mock_send_message_json): service = Service(name="test") service.unique_identifier = "toto" mock_send_message_json.return_value = {} assert len(list(service.components)) == 0 mock_send_message_json.reset_mock() mock_send_message_json.side_effect = [COMPONENTS, COMPONENT] components = list(service.components) assert len(components) == 1 assert mock_send_message_json.call_count == 2 component = components[0] assert component.actual_component_uid == "374f0a98-a280-43f1-9e6c-00b436782ce7" assert component.sdc_resource.unique_uuid == "3c027ba1-8d3a-4b59-9394-d748fec5e42c"
def execute(self): """Onboard service.""" super().execute() if "instantiation_type" in self.yaml_template[self.service_name]: instantiation_type: ServiceInstantiationType = ServiceInstantiationType( self.yaml_template[self.service_name]["instantiation_type"]) else: instantiation_type: ServiceInstantiationType = ServiceInstantiationType.A_LA_CARTE service: Service = Service(name=self.service_name, instantiation_type=instantiation_type) if not service.created(): service.create() self.declare_resources(service) self.assign_properties(service) # If the service is already distributed, do not try to checkin/onboard (replay of tests) # checkin is done if needed # If service is replayed, no need to try to re-onboard the model if not service.distributed: try: service.checkin() except (APIError, ResourceNotFound): # Retry as checkin may be a bit long # Temp workaround to avoid internal race in SDC time.sleep(10) service.checkin() service.onboard()
def execute(self): """Onboard service. Use settings values: - VL_NAME, - VF_NAME, - PNF_NAME, - SERVICE_NAME, - SERVICE_INSTANTIATION_TYPE. """ super().execute() service: Service = Service( name=settings.SERVICE_NAME, instantiation_type=settings.SERVICE_INSTANTIATION_TYPE) if not service.created(): service.create() if settings.VL_NAME != "": vl: Vl = Vl(name=settings.VL_NAME) service.add_resource(vl) if settings.VF_NAME != "": vf: Vf = Vf(name=settings.VF_NAME) service.add_resource(vf) if settings.PNF_NAME != "": pnf: Pnf = Pnf(name=settings.PNF_NAME) service.add_resource(pnf) # If the service is already distributed, do not try to checkin/onboard (replay of tests) # checkin is done if needed # If service is replayed, no need to try to re-onboard the model if not service.distributed: time.sleep(10) service.checkin() service.onboard()
def test_Loop_customization(): """Integration tests for Loop Instance.""" requests.get("{}/reset".format(Clamp._base_url)) Clamp(cert=('LICENSE', '')) svc = Service(name="service01") loop_template = Clamp.check_loop_template(service=svc) response = requests.post("{}/reset".format(Clamp._base_url)) response.raise_for_status() loop = LoopInstance(template=loop_template, name="instance01", details={}) loop.create() loop.update_microservice_policy() #add op policy FrequencyLimiter that already exists in clamp loop.add_operational_policy( policy_type="onap.policies.controlloop.guard.common.FrequencyLimiter", policy_version="1.0.0") #only frequency configuration is available in mock clamp loop.add_op_policy_config(loop.add_frequency_limiter, limit=1) submit = loop.act_on_loop_policy(loop.submit) assert submit stop = loop.act_on_loop_policy(loop.stop) assert stop restart = loop.act_on_loop_policy(loop.restart) assert restart deploy = loop.deploy_microservice_to_dcae() assert deploy loop.undeploy_microservice_from_dcae() new_details = loop._update_loop_details() assert new_details["components"]["DCAE"]["componentState"][ "stateName"] == "MICROSERVICE_UNINSTALLED_SUCCESSFULLY"
def execute(self): """Onboard service.""" super().execute() # retrieve the Vf vf = None for sdc_vf in Vf.get_all(): if sdc_vf.name == settings.VF_NAME: vf = sdc_vf self._logger.debug("Vf retrieved %s", vf) service: Service = Service(name=self.service_name, resources=[vf]) service.create() self._logger.info(" Service %s created", service) if not service.distributed: service.add_resource(vf) # we add the artifact to the first VNF self._logger.info("Try to add blueprint to %s", vf.name) payload_file = open( settings.CONFIGURATION_PATH + 'tca-microservice.yaml', 'rb') data = payload_file.read() self._logger.info("DCAE INVENTORY BLUEPRINT file retrieved") service.add_artifact_to_vf( vnf_name=vf.name, artifact_type="DCAE_INVENTORY_BLUEPRINT", artifact_name="tca-microservice.yaml", artifact=data) payload_file.close() service.checkin() service.onboard() self._logger.info("DCAE INVENTORY BLUEPRINT ADDED")
def test_check_loop_template_none(mock_send_message_json): """Test Clamp's class method.""" svc = Service(name='test') mock_send_message_json.return_value = {} with pytest.raises(ValueError): template = Clamp.check_loop_template(service=svc) assert template is None
def test_service_onboard_unknown(): """Integration tests for Service.""" response = requests.post("{}/reset".format(SDC.base_front_url)) response.raise_for_status() vendor = Vendor(name="test") vendor.onboard() vsp = Vsp(name="test", package=open( "{}/ubuntu16.zip".format( os.path.dirname(os.path.abspath(__file__))), 'rb')) vsp.vendor = vendor vsp.onboard() vf = Vf(name='test', vsp=vsp) vf.onboard() svc = Service(name='test', resources=[vf]) svc.onboard() assert svc.distributed
def test_check_loop_template(mock_send_message_json): """Test Clamp's class method.""" svc = Service(name='test') mock_send_message_json.return_value = TEMPLATES template = Clamp.check_loop_template(service=svc) mock_send_message_json.assert_called_once_with( 'GET', 'Get Loop Templates', (f"{Clamp.base_url()}/templates/")) assert template == "test_template"
def test_check_loop_template_none(mock_send_message_json): """Test Clamp's class method.""" svc = Service(name='test') mock_send_message_json.return_value = {} with pytest.raises(ResourceNotFound) as exc: template = Clamp.check_loop_template(service=svc) assert template is None assert exc.type is ResourceNotFound
def test_tosca_template_no_tosca_model(mock_unzip): service = Service(name="test") getter_mock = mock.Mock(wraps=Service.tosca_model.fget) getter_mock.return_value = False mock_tosca_model = Service.tosca_model.getter(getter_mock) with mock.patch.object(Service, 'tosca_model', mock_tosca_model): service.tosca_template mock_unzip.assert_not_called()
def test_tosca_model(mock_send): service = Service(name="test") service.identifier = "toto" service.tosca_model mock_send.assert_called_once_with( "GET", "Download Tosca Model for test", "https://sdc.api.be.simpledemo.onap.org:30204/sdc/v1/catalog/services/toto/toscaModel", exception=mock.ANY, headers={ 'Content-Type': 'application/json', 'Accept': 'application/octet-stream', 'USER_ID': 'cs0008', 'Authorization': 'Basic YWFpOktwOGJKNFNYc3pNMFdYbGhhazNlSGxjc2UyZ0F3ODR2YW9HR21KdlV5MlU=', 'X-ECOMP-InstanceID': 'onapsdk' })
def test_load_metadata_OK(mock_send): mock_send.return_value = { 'distributionStatusOfServiceList': [{ 'distributionID': "11" }, { 'distributionID': "12" }] } svc = Service() svc.identifier = "1" svc.load_metadata() assert svc._distribution_id == "11" mock_send.assert_called_once_with( 'GET', 'Get Metadata for ONAP-test-Service', 'https://sdc.api.fe.simpledemo.onap.org:30207/sdc1/feProxy/rest/v1/catalog/services/1/distribution', headers=headers_sdc_creator(svc.headers))
def test_pnf_no_template(): getter_mock = mock.Mock(wraps=Service.tosca_template.fget) getter_mock.return_value = False mock_status = Service.tosca_template.getter(getter_mock) with mock.patch.object(Service, 'tosca_template', mock_status): with pytest.raises(AttributeError): service = Service(name="test") service.pnfs