def setUp(self): name = "testnode" self.properties = { 'vcloud_config': self.vcloud_config, 'floatingip': self.test_config['floatingip'] } self.ctx = MockCloudifyContext( node_id=name, node_name=name, properties={}, target=MockCloudifyContext(node_id="target", properties=self.properties), source=MockCloudifyContext( node_id="source", properties={'vcloud_config': self.vcloud_config}, runtime_properties={ VCLOUD_VAPP_NAME: self.test_config['test_vm'] })) ctx_patch1 = mock.patch('network_plugin.floatingip.ctx', self.ctx) ctx_patch2 = mock.patch('vcloud_plugin_common.ctx', self.ctx) ctx_patch1.start() ctx_patch2.start() self.addCleanup(ctx_patch1.stop) self.addCleanup(ctx_patch2.stop) super(self.__class__, self).setUp()
def setUp(self): name = "testnode" self.ctx = MockCloudifyContext( node_id=name, node_name=name, properties={}, target=MockCloudifyContext( node_id="target", properties={ "nat": self.test_config['public_nat']['nat'], 'use_external_resource': False, "rules": {} }), source=MockCloudifyContext( node_id="source", properties={"vcloud_config": self.vcloud_config}, runtime_properties={ VCLOUD_VAPP_NAME: self.test_config['public_nat']['test_vm'], VCLOUD_NETWORK_NAME: self.test_config['public_nat']['network_name'] })) ctx_patch1 = mock.patch('network_plugin.public_nat.ctx', self.ctx) ctx_patch2 = mock.patch('vcloud_plugin_common.ctx', self.ctx) ctx_patch1.start() ctx_patch2.start() self.addCleanup(ctx_patch1.stop) self.addCleanup(ctx_patch2.stop) super(self.__class__, self).setUp()
def test_serial_operation_install(self, list_fn): _ctx = MockCloudifyContext(node_id='test_node', deployment_id='test_deployment', index=7) # Check that we raise if the preceder is not 'started'. _ctx._context['workflow_id'] = 'install' current_ctx.set(_ctx) _caller = Mock() @serial_operation() def run_op_install_only(ctx=_ctx, **kwargs): _caller() list_fn.return_value = [ Mock(id='test_node{x}'.format(x=n), index=n, state='uninitialized') for n in range(0, 6) ] self.assertRaises(CloudifySerializationRetry, run_op_install_only) self.assertFalse(_caller.called) list_fn.return_value = [ Mock(id='test_node{x}'.format(x=n), index=n, state='started' if n < 7 else 'uninitialized') for n in range(3, 10) if n != 7 ] run_op_install_only() self.assertTrue(_caller.called) current_ctx.clear()
def _run(self, ctx_kwargs, expected_script_path, actual_script_path, return_result=False, pass_parameter=False): def mock_download_resource(script_path): self.assertEqual(script_path, expected_script_path) return actual_script_path if 'properties' not in ctx_kwargs: ctx_kwargs['properties'] = {} if 'process' not in ctx_kwargs['properties']: ctx_kwargs['properties']['process'] = {} process_config = ctx_kwargs['properties']['process'] process_config.update({ 'ctx_proxy_type': self.ctx_proxy_type }) ctx = MockCloudifyContext(**ctx_kwargs) ctx.download_resource = mock_download_resource if pass_parameter: result = tasks.run(expected_script_path, ctx=ctx) else: result = tasks.run(ctx=ctx) if return_result: return ctx, result else: return ctx
def _get_ctx(self): ctx = MockCloudifyContext( node_name='mock_node_name', node_id='node_id', deployment_id='mock_deployment_id', properties=NODE_PROPS, runtime_properties=RUNTIME_PROPS, relationships=RELS, operation=OP_CTX ) ctx.node.type_hierarchy = ['cloudify.nodes.Root'] compute_ctx = MockCloudifyContext( node_name='mock_compute_node_name', node_id='compute_node_id', deployment_id='mock_deployment_id', properties=COMPUTE_NODE_PROPS, runtime_properties=RUNTIME_PROPS, relationships=RELS, operation=OP_CTX ) compute_ctx.node.type_hierarchy = \ ['cloudify.nodes.Root', 'cloudify.nodes.Compute'] relationship_ctx = MockCloudifyContext( deployment_id='mock_deployment_id', source=ctx, target=compute_ctx) return relationship_ctx
def _gen_ctx(self): _ctx = MockCloudifyContext( deployment_id="deployment_id" ) _graph = Mock() _graph.id = 'i_am_graph' _graph.tasks_iter = Mock(return_value=['task1']) _graph.remove_task = Mock(return_value=None) _ctx.graph_mode = Mock(return_value=_graph) _ctx.deployment.scaling_groups = { 'one_scale': { 'members': ['one'], 'properties': {'current_instances': 10} }, 'alfa_types': { 'members': ['a_type', 'b_type'], 'properties': {'current_instances': 55} } } modification = Mock() modification.id = "transaction_id" modification.added.node_instances = [] modification.removed.node_instances = [] modification.rollback = Mock() modification.finish = Mock() _ctx.deployment.start_modification = Mock(return_value=modification) _ctx._get_modification = modification current_ctx.set(_ctx) return _ctx
def test_serial_operation_install_workflow(self, _mock, list_fn): _ctx = MockCloudifyContext(node_id='test_node', deployment_id='test_deployment', index=7) # Check that we raise if the preceder is not 'started'. _ctx._context['workflow_id'] = 'install' current_ctx.set(_ctx) _mock.side_effect = lambda: rest_client_mock.MockRestclient() _caller = Mock() @serial_operation(workflows=['scale']) def run_op_neither(ctx=_ctx, **kwargs): _caller() list_fn.return_value = [ Mock(id='test_node{x}'.format(x=n), index=n, state='started' if n == 6 else 'uninitialized') for n in range(0, 6) ] run_op_neither() self.assertTrue(_caller.called) current_ctx.clear()
def test_execute_jinja_block_parse(self): _ctx = MockCloudifyContext('node_name', properties={'hosts': ['test123.test'], 'port': -1, 'ssl': False, 'verify': False}, runtime_properties={}) __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'template6.yaml'), 'r') as f: template = f.read() _ctx.get_resource = MagicMock(return_value=template) _ctx.logger.setLevel(logging.DEBUG) current_ctx.set(_ctx) custom_list = [{'key1': 'val1'}, {'key2': 'val2'}, ['element1', 'element2']] params = {'custom_list': custom_list} with requests_mock.mock( real_http=True) as m: m.post('http://test123.test:80/v1/post_jinja_block', text="resp") tasks.execute(params, 'mock_param') parsed_list = _ctx.instance.runtime_properties.get( 'calls')[0].get('payload').get('jinja_block') self.assertListEqual(parsed_list, custom_list)
def test_execute_overwrite_host_response_expecation(self): _ctx = MockCloudifyContext('node_name', properties={'hosts': ['test123.test'], 'port': 12345, 'ssl': 'true', 'verify': True}, runtime_properties={}) __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'template3.yaml'), 'r') as f: template = f.read() _ctx.get_resource = MagicMock(return_value=template) _ctx.logger.setLevel(logging.DEBUG) current_ctx.set(_ctx) with requests_mock.mock() as m: m.put('https://hostfrom%20template.test:12345/v1/put_%20response3', json=json.load( file(os.path.join(__location__, 'put_response3.json'), 'r')), status_code=200) with self.assertRaises(RecoverableError) as context: tasks.execute({}, 'mock_param') self.assertSequenceEqual( 'Trying one more time...\n' "Response value:wrong_value " "does not match regexp: proper_value|good" " from response_expectation", str(context.exception.message))
def test_execute_nonrecoverable_response(self): _ctx = MockCloudifyContext('node_name', properties={'hosts': ['test123.test'], 'port': 12345, 'ssl': 'true', 'verify': True}, runtime_properties={}) __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'template4.yaml'), 'r') as f: template = f.read() _ctx.get_resource = MagicMock(return_value=template) _ctx.logger.setLevel(logging.DEBUG) current_ctx.set(_ctx) with requests_mock.mock() as m: m.get('https://test123.test:12345/v1/get_response1', json=json.load( file(os.path.join(__location__, 'get_response1.json'), 'r')), status_code=200) with self.assertRaises(NonRecoverableError) as context: tasks.execute({}, 'mock_param') self.assertSequenceEqual( 'Giving up... \n' "Response value: active matches " "regexp:active from nonrecoverable_response. ", str(context.exception.message))
def test_execute_http_xml(self): _ctx = MockCloudifyContext('node_name', properties={'hosts': ['test123.test'], 'port': -1, 'ssl': False, 'verify': False}, runtime_properties={}) __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'template5.yaml'), 'r') as f: template = f.read() _ctx.get_resource = MagicMock(return_value=template) _ctx.logger.setLevel(logging.DEBUG) current_ctx.set(_ctx) with requests_mock.mock() as m: m.get('http://test123.test:80/v1/get_response5', text=file(os.path.join(__location__, 'get_response5.xml'), 'r').read(), status_code=200) tasks.execute({}, 'mock_param') # _ctx = current_ctx.get_ctx() self.assertDictEqual( _ctx.instance.runtime_properties.get('result_properties'), {'UUID': '111111111111111111111111111111', 'CPUID': 'ABS:FFF222777'})
def get_mock_ctx(test_name, mock_node_type, retry_number=0, node_props=NODE_PROPS): def mock_retry(_): return 'RETRIED' operation = { 'retry_number': retry_number } target_node_ctx = MockCloudifyContext( node_id=test_name, node_name=test_name, node_type=mock_node_type, deployment_id=test_name, operation=operation, properties=node_props ) ctx = MockCloudifyContext( target=target_node_ctx ) ctx.operation._operation_context = {'name': 'some.test'} ctx.operation.retry = lambda msg: mock_retry(msg) return ctx
def test_unlink(self): _target = MockCloudifyContext( 'target', properties={}, runtime_properties={ 'resource_id': 'target_id', 'name': 'target', 'ip': '1.2.3.4' } ) _source = MockCloudifyContext( 'source', properties={}, runtime_properties={ 'resource_id': 'source_id', 'name': 'source' } ) _ctx = MockCloudifyContext( target=_target, source=_source ) current_ctx.set(_ctx) network_tasks.unlink(ctx=_ctx) self.assertEqual(_source.instance.runtime_properties, { 'resource_id': 'source_id', 'name': 'source'}) self.assertEqual(_target.instance.runtime_properties, { 'ip': None, 'resource_id': 'target_id', 'name': 'target'})
def _gen_relation_ctx(self): _target = MockCloudifyContext('target', properties={}, runtime_properties={}) _source = MockCloudifyContext('source', properties={}, runtime_properties={}) _ctx = MockCloudifyContext(target=_target, source=_source) _ctx._source.node.properties["connection_config"] = { "username": "******", "password": "******", "host": "vcenter_ip", "port": 443, "datacenter_name": "vcenter_datacenter", "resource_pool_name": "vcenter_resource_pool", "auto_placement": "vsphere_auto_placement", "allow_insecure": True } _ctx._target.node.properties["connection_config"] = { "username": "******", "password": "******", "host": "vcenter_ip", "port": 443, "datacenter_name": "vcenter_datacenter", "resource_pool_name": "vcenter_resource_pool", "auto_placement": "vsphere_auto_placement", "allow_insecure": True } current_ctx.set(_ctx) return _ctx
def test_vm_config_validation(self): ctx = MockCloudifyContext(node_id='node', properties={'cloudify_agent': { 'distro': 'Ubuntu', 'distro_codename': 'trusty'}}) self.assertRaises(NonRecoverableError, m, ctx) ctx = MockCloudifyContext(node_id='node', properties={'cloudify_agent': { 'distro': 'Ubuntu'}, 'distro_codename': 'trusty', 'ip': '192.168.0.1' }) self.assertRaises(NonRecoverableError, m, ctx) ctx = MockCloudifyContext(node_id='node', properties={ 'cloudify_agent': { 'distro': 'Ubuntu', 'distro_codename': 'trusty', 'user': getpass.getuser()}, 'ip': '192.168.0.1' }) self.assertRaises(NonRecoverableError, m, ctx) ctx = MockCloudifyContext(node_id='node', properties={ 'cloudify_agent': { 'user': getpass.getuser(), 'key': KEY_FILE_PATH, 'home_dir': self._get_home_dir(), 'distro': 'Ubuntu', 'distro_codename': 'trusty', }, 'ip': '192.168.0.1' }) m(ctx)
def test_create_with_download(self): subnettarget = MockRelationshipContext( target=MockCloudifyContext('subnet')) subnettarget.target.node.type_hierarchy =\ ['cloudify.nodes.aws.ec2.Subnet'] ctx = MockCloudifyContext("test_create") ctx.download_resource = MagicMock(return_value='abc') with patch(PATCH_PREFIX + 'LambdaBase'),\ patch(PATCH_PREFIX + 'utils') as utils,\ patch(PATCH_PREFIX + 'path_exists', MagicMock(return_value=False)),\ patch(PATCH_PREFIX + 'os_remove', MagicMock(return_value=True)),\ patch(PATCH_PREFIX + 'open', MagicMock(return_value=StringIO(u"test"))): fun = function.LambdaFunction(ctx) fun.logger = MagicMock() fun.resource_id = 'test_function' fake_client = self.make_client_function( 'create_function', return_value={'FunctionArn': 'test_function_arn', 'FunctionName': 'test_function'}) fun.client = fake_client resource_config = {'VpcConfig': {'SubnetIds': []}, 'Code': {'ZipFile': True}} utils.find_rels_by_node_type = MagicMock( return_value=[subnettarget]) utils.get_resource_id = MagicMock(return_value='test_id') utils.find_rel_by_node_type = MagicMock(return_value=subnettarget) utils.get_resource_id = MagicMock(return_value='Role') function.create(ctx, fun, resource_config) self.assertEqual(True, resource_config['Code']['ZipFile']) self.assertEqual({'SubnetIds': []}, resource_config['VpcConfig'])
def setUp(self): super(VolumeTestCase, self).setUp() self.volume_test_dict = self.test_config['volume'] name = 'volume' self.properties = { 'volume': { 'name': self.volume_test_dict['name'], 'size': self.volume_test_dict['size'] }, 'use_external_resource': True, 'resource_id': self.volume_test_dict['name_exists'], 'vcloud_config': self.vcloud_config } self.target = MockCloudifyContext( node_id="target", properties={'vcloud_config': self.vcloud_config}, runtime_properties={VCLOUD_VAPP_NAME: self.test_config['test_vm']}) self.source = MockCloudifyContext(node_id="source", properties=self.properties) self.nodectx = cfy_mocks.MockCloudifyContext( node_id=name, node_name=name, properties=self.properties) self.relationctx = cfy_mocks.MockCloudifyContext(node_id=name, node_name=name, target=self.target, source=self.source) self.ctx = self.nodectx ctx_patch1 = mock.patch('server_plugin.volume.ctx', self.nodectx) ctx_patch2 = mock.patch('vcloud_plugin_common.ctx', self.nodectx) ctx_patch1.start() ctx_patch2.start() self.addCleanup(ctx_patch1.stop) self.addCleanup(ctx_patch2.stop)
def _gen_ctx(self): _ctx = MockCloudifyContext('node_name', properties={ "connection_config": { "username": "******", "password": "******", "host": "vcenter_ip", "port": 443, "datacenter_name": "vcenter_datacenter", "resource_pool_name": "vcenter_resource_pool", "auto_placement": "vsphere_auto_placement", "allow_insecure": True } }, runtime_properties={}) _ctx._execution_id = "execution_id" _ctx.instance.host_ip = None _ctx._operation = mock.Mock() current_ctx.set(_ctx) return _ctx
def get_mock_ctx(self, test_name, test_properties=NODE_PROPS, runtime_properties=RUNTIME_PROPS, node_type=DEPLOYMENT_PROXY_TYPE, retry_number=0, operation_name=""): operation = {'retry_number': retry_number} ctx = MockCloudifyContext( node_id=test_name, deployment_id=test_name, operation=operation, properties=test_properties, ) ctx.instance._runtime_properties = DirtyTrackingDict( runtime_properties) ctx.operation._operation_context = {'name': operation_name} ctx.node.type_hierarchy = ['cloudify.nodes.Root', node_type] ctx.get_resource_and_render = mock.Mock( return_value="resource_and_render") ctx.get_resource = mock.Mock(return_value="get_resource") try: ctx.node.type = node_type except AttributeError: ctx.logger.error('Failed to set node type attribute.') current_ctx.set(ctx) return ctx
def test_execute_as_relationship(self): _source_ctx = MockCloudifyContext('source_name', properties={}, runtime_properties={}) _target_ctx = MockCloudifyContext('target_name', properties={}, runtime_properties={}) _ctx = MockCloudifyContext("execution_id", target=_target_ctx, source=_source_ctx) current_ctx.set(_ctx) mock_execute = mock.Mock(return_value=None) with mock.patch("cloudify_rest.tasks._execute", mock_execute): tasks.execute_as_relationship(ctx=_ctx) mock_execute.assert_called_with(params={}, template_file=None, auth=None, ctx=_ctx, instance_props={}, node_props={}, prerender=False, remove_calls=False, retry_count=1, retry_sleep=15, resource_callback=_ctx.get_resource, save_path=None)
def _gen_ctx(self): _ctx = MockCloudifyContext('node_name', properties={}, runtime_properties={}) _ctx._execution_id = "execution_id" current_ctx.set(_ctx) return _ctx
def test_throw_cloudify_exceptions(self): # create without error fake_ctx = MockCloudifyContext( 'node_name', properties={}, ) fake_ctx._operation = Mock() fake_ctx.operation._operation_retry = None current_ctx.set(fake_ctx) fake_ctx.instance._runtime_properties = DirtyTrackingDict({"c": "d"}) @utils.throw_cloudify_exceptions def test(*argc, **kwargs): return argc, kwargs fake_ctx._operation.name = "cloudify.interfaces.lifecycle.create" self.assertEqual(test(ctx=fake_ctx), ((), {'ctx': fake_ctx})) self.assertEqual(fake_ctx.instance._runtime_properties, {"c": "d"}) # delete without error fake_ctx.instance._runtime_properties = DirtyTrackingDict({"a": "b"}) fake_ctx._operation.name = "cloudify.interfaces.lifecycle.delete" self.assertEqual(test(ctx=fake_ctx), ((), {'ctx': fake_ctx})) self.assertFalse(fake_ctx.instance._runtime_properties) # delete postponed by gcp fake_ctx.instance._runtime_properties = DirtyTrackingDict( {"_operation": "b"}) fake_ctx._operation.name = "cloudify.interfaces.lifecycle.delete" self.assertEqual(test(ctx=fake_ctx), ((), {'ctx': fake_ctx})) self.assertEqual(fake_ctx.instance._runtime_properties, {"_operation": "b"}) # postponed by cloudify @utils.throw_cloudify_exceptions def test(ctx, *argc, **kwargs): ctx.operation._operation_retry = 'Should be retried' return argc, kwargs fake_ctx.instance._runtime_properties = DirtyTrackingDict({"a": "b"}) fake_ctx._operation.name = "cloudify.interfaces.lifecycle.delete" self.assertEqual(test(ctx=fake_ctx), ((), {})) self.assertEqual(fake_ctx.instance._runtime_properties, {"a": "b"}) # postponed by exeption @utils.throw_cloudify_exceptions def test(ctx, *argc, **kwargs): raise Exception('Should be retried') fake_ctx.instance._runtime_properties = DirtyTrackingDict({"a": "b"}) fake_ctx._operation.name = "cloudify.interfaces.lifecycle.delete" with self.assertRaises(NonRecoverableError): test(ctx=fake_ctx) self.assertEqual(fake_ctx.instance._runtime_properties, {"a": "b"})
def mock_context(agent_ssl_cert, agent_properties=None, agent_runtime_properties=None, agent_context=None, **kwargs): agent_context = agent_context or {} agent_properties = agent_properties or {} agent_runtime_properties = agent_runtime_properties or {} context = { 'node_id': 'test_node', 'node_name': 'test_node', 'blueprint_id': 'test_blueprint', 'deployment_id': 'test_deployment', 'execution_id': 'test_execution', 'rest_token': 'test_token', 'properties': { 'cloudify_agent': agent_properties }, 'runtime_properties': { 'cloudify_agent': agent_runtime_properties }, 'managers': [{ 'networks': { 'default': '127.0.0.1' }, 'ca_cert_content': agent_ssl_cert.DUMMY_CERT, 'hostname': 'cloudify' }], 'brokers': [{ 'networks': { 'default': '127.0.0.1' }, 'ca_cert_content': agent_ssl_cert.DUMMY_CERT }], 'bootstrap_context': BootstrapContext(bootstrap_context={'cloudify_agent': agent_context}), 'tenant': { 'name': 'default_tenant', 'rabbitmq_username': '******', 'rabbitmq_password': '******', 'rabbitmq_vhost': '/' } } context.update(kwargs) context = MockCloudifyContext(**context) context.installer = MagicMock() context._get_current_object = lambda: context return context
def setUp(self): _ctx = MockCloudifyContext('node_name', properties={}, runtime_properties={}) _ctx._execution_id = "execution_id" _ctx.instance.host_ip = None current_ctx.set(_ctx) return _ctx
def _gen_relation_ctx(self): _target_ctx = MockCloudifyContext('node_name', properties={}, runtime_properties={}) _target_ctx.instance.host_ip = None _ctx = MockCloudifyContext(target=_target_ctx) _ctx._execution_id = "execution_id" current_ctx.set(_ctx) return _ctx
def _gen_ctx(self): _ctx = MockCloudifyContext( 'node_name', properties={}, ) _ctx._execution_id = "execution_id" _ctx.instance.host_ip = None _ctx.instance._runtime_properties = DirtyTrackingDict({}) _ctx.get_resource = mock.Mock(return_value=TEMPLATE.encode("utf-8")) current_ctx.set(_ctx) return _ctx
def _gen_ctx(self): _ctx = MockCloudifyContext( 'node_name', properties={}, runtime_properties={} ) _ctx._execution_id = "execution_id" _ctx.instance.host_ip = None current_ctx.set(_ctx) return _ctx
def test_autoscale_from_bootstrap_context(self): node_id = 'node_id' ctx = MockCloudifyContext( deployment_id='test', node_id=node_id, runtime_properties={ 'ip': '192.168.0.1' }, properties={ 'cloudify_agent': { 'user': getpass.getuser(), 'home_dir': self._get_home_dir(), 'key': KEY_FILE_PATH, 'distro': 'Ubuntu', 'distro_codename': 'trusty' } }, bootstrap_context=BootstrapContext({ 'cloudify_agent': { 'min_workers': 2, 'max_workers': 5, } }) ) conf = m(ctx) self.assertEqual(conf['min_workers'], 2) self.assertEqual(conf['max_workers'], 5) ctx = MockCloudifyContext( deployment_id='test', node_id=node_id, runtime_properties={ 'ip': '192.168.0.1' }, properties={ 'cloudify_agent': { 'user': getpass.getuser(), 'home_dir': self._get_home_dir(), 'key': KEY_FILE_PATH, 'distro': 'Ubuntu', 'distro_codename': 'trusty' } }, bootstrap_context=BootstrapContext({ 'cloudify_agent': { 'min_workers': 0, 'max_workers': 5, } }) ) conf = m(ctx) self.assertEqual(conf['min_workers'], 0) self.assertEqual(conf['max_workers'], 5)
def _gen_ctx(self): _ctx = MockCloudifyContext( 'node_name', properties={}, ) _ctx._execution_id = "execution_id" _ctx.instance.host_ip = None _ctx.instance._runtime_properties = DirtyTrackingDict({}) current_ctx.set(_ctx) return _ctx
def test_execute_http_no_exception(self): _ctx = MockCloudifyContext('node_name', properties={'hosts': ['--fake.cake--', 'test123.test'], 'port': -1, 'ssl': False, 'verify': False}, runtime_properties={}) __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'template1.yaml'), 'r') as f: template = f.read() _ctx.get_resource = MagicMock(return_value=template) _ctx.logger.setLevel(logging.DEBUG) current_ctx.set(_ctx) params = {'USER': '******'} with requests_mock.mock( real_http=True) as m: # real_http to check fake uri and get ex # call 1 m.get('http://test123.test:80/testuser/test_rest/get', json=json.load( file(os.path.join(__location__, 'get_response1.json'), 'r')), status_code=200) def _match_request_text(request): return '101' in (request.text or '') # call 2 m.post('http://test123.test:80/test_rest/posts', additional_matcher=_match_request_text, request_headers={'Content-type': 'test/type'}, text='resp') # call 1 m.get('http://test123.test:80/get', json=json.load( file(os.path.join(__location__, 'get_response2.json'), 'r')), status_code=200) tasks.execute(params, 'mock_param') # _ctx = current_ctx.get_ctx() self.assertDictEqual( _ctx.instance.runtime_properties.get('result_properties'), {'nested_key0': u'nested_value1', 'nested_key1': u'nested_value2', 'id0': u'1', 'id1': u'101', 'owner1': {'id': 'Bob'}, 'owner2': {'colour': 'red', 'name': 'bed', 'id': 'Carol'}, 'owner0': {'colour': 'black', 'name': 'book'}})
def _instance_ctx(self): _ctx = MockCloudifyContext('node_name', properties={ 'd': 'c', 'b': 'a' }, runtime_properties={ 'a': 'b', 'c': 'd' }) _ctx.download_resource = Mock( side_effect=download_resource_side_effect) current_ctx.set(_ctx) return _ctx
def mock_instance_ctx(self, test_name, use_external_resource=False, instance_id='i-nstance', operation_name='create'): """ Creates a mock context for the instance tests """ test_node_id = test_name test_properties = { constants.AWS_CONFIG_PROPERTY: {}, 'use_external_resource': use_external_resource, 'resource_id': '', 'name': '', 'tags': {}, 'image_id': TEST_AMI_IMAGE_ID, 'instance_type': TEST_INSTANCE_TYPE, 'cloudify_agent': {}, 'agent_config': {}, 'parameters': { 'security_group_ids': ['sg-73cd3f1e'], 'instance_initiated_shutdown_behavior': 'stop' } } runtime_properties = {'aws_resource_id': instance_id} operation = {'name': operation_name, 'retry_number': 0} ctx = MockCloudifyContext(node_id=test_node_id, properties=test_properties, operation=operation, runtime_properties=runtime_properties) ctx.node.type_hierarchy = ['cloudify.nodes.Compute'] return ctx
def test_op_upgrade(self, mock_execute_command): # test operation upgrade """ :upgrade operation test: """ props = { 'component_name': 'test_node', 'namespace': 'onap', 'tiller_port': '8888', 'tiller_ip': '1.1.1.1', 'tls_enable': 'false', 'config_dir': '/tmp' } args = {'revision': '1', 'config': '', 'chart_repo': 'repo', 'chart_version': '2', 'config_set': 'config_set', 'config_json': '', 'config_url': '', 'config_format': 'format', 'repo_user': '', 'repo_user_passwd': ''} mock_ctx = MockCloudifyContext(node_id='test_node_id', node_name='test_node_name', properties=props) try: current_ctx.set(mock_ctx) with mock.patch('plugin.tasks.get_current_helm_value'): with mock.patch('plugin.tasks.get_helm_history'): with mock.patch('plugin.tasks.gen_config_str'): plugin.tasks.upgrade(**args) finally: current_ctx.clear()
def mock_context(agent_properties=None, agent_runtime_properties=None, agent_context=None): if not agent_properties: agent_properties = {} if not agent_runtime_properties: agent_runtime_properties = {} context = MockCloudifyContext( node_id='test_node', node_name='test_node', blueprint_id='test_blueprint', deployment_id='test_deployment', execution_id='test_execution', properties={'cloudify_agent': agent_properties}, runtime_properties={'cloudify_agent': agent_runtime_properties}, bootstrap_context=BootstrapContext( bootstrap_context={'cloudify_agent': agent_context}) ) context.installer = MagicMock() context._get_current_object = lambda: context return context
def _gen_ctx(self): _ctx = MockCloudifyContext( 'node_name', properties={ "connection_config": { "username": "******", "password": "******", "host": "vcenter_ip", "port": 443, "datacenter_name": "vcenter_datacenter", "resource_pool_name": "vcenter_resource_pool", "auto_placement": "vsphere_auto_placement", "allow_insecure": True } }, runtime_properties={} ) _ctx._execution_id = "execution_id" _ctx.instance.host_ip = None current_ctx.set(_ctx) return _ctx
def mock_ctx(self, **kwargs): ctx = MockCloudifyContext(**kwargs) ctx.download_resource = lambda s_path: s_path return ctx
def test_sg(self): neutron_client = self.get_neutron_client() # Test: group with all defaults + delete name = self.name_prefix + 'sg1' ctx = MockCloudifyContext( node_id='__cloudify_id_' + name, properties={ 'security_group': { 'name': name, 'description': 'SG-DESC', }, 'rules': [] } ) self.assertThereIsNo('security_group', name=name) cfy_sg.create(ctx) self.assertThereIsOne('security_group', name=name) # By default SG should have 2 egress rules and no ingress rules for direction, count in ('egress', 2), ('ingress', 0): rules = neutron_client.cosmo_list( 'security_group_rule', security_group_id=ctx.runtime_properties['external_id'], direction=direction ) ls = list(rules) # print(ls) self.assertEquals(len(ls), count) cfy_sg.delete(ctx) self.assertThereIsNo('security_group', name=name) # Test: Disabled egress name = self.name_prefix + 'sg2' ctx2 = MockCloudifyContext( node_id='__cloudify_id_' + name, properties={ 'security_group': { 'name': name, 'description': 'SG-DESC', }, 'rules': [], 'disable_egress': True, } ) self.assertThereIsNo('security_group', name=name) cfy_sg.create(ctx2) self.assertThereIsOne('security_group', name=name) rules = neutron_client.cosmo_list( 'security_group_rule', security_group_id=ctx2.runtime_properties['external_id'], ) ls = list(rules) self.assertEquals(len(ls), 0) cfy_sg.delete(ctx2) # Test: Exception when providing egress rule and "disable_egress" ctx2.properties['rules'] = [{ 'direction': 'egress', 'port': 80, }] self.assertThereIsNo('security_group', name=name) self.assertRaises(RuntimeError, cfy_sg.create, ctx2) # Test: One egress rule del ctx2.properties['disable_egress'] cfy_sg.create(ctx2) self.assertThereIsOne('security_group', name=name) rules = neutron_client.cosmo_list( 'security_group_rule', security_group_id=ctx2.runtime_properties['external_id'], direction='egress', ) ls = list(rules) self.assertEquals(len(ls), 1)