def _test_floatingip_update_different_router(self): with contextlib.nested(self.subnet(cidr='10.0.0.0/24'), self.subnet(cidr='10.0.1.0/24')) as ( s1, s2): with contextlib.nested(self.port(subnet=s1), self.port(subnet=s2)) as (p1, p2): private_sub1 = {'subnet': {'id': p1['port']['fixed_ips'][0]['subnet_id']}} private_sub2 = {'subnet': {'id': p2['port']['fixed_ips'][0]['subnet_id']}} with self.subnet(cidr='12.0.0.0/24') as public_sub: with contextlib.nested( self.floatingip_no_assoc_with_public_sub( private_sub1, public_sub=public_sub), self.floatingip_no_assoc_with_public_sub( private_sub2, public_sub=public_sub)) as ( (fip1, r1), (fip2, r2)): self._assert_no_assoc_fip(fip1) self._assert_no_assoc_fip(fip2) fip1_r1_res = self._associate_and_assert_fip(fip1, p1) self.assertEqual(fip1_r1_res, r1['router']['id']) # The following operation will associate the floating # ip to a different router and should fail self._associate_and_assert_fip(fip1, p2, allow=False) # disassociate fip1 self._update( 'floatingips', fip1['floatingip']['id'], {'floatingip': {'port_id': None}}) fip2_r2_res = self._associate_and_assert_fip(fip2, p2) self.assertEqual(fip2_r2_res, r2['router']['id'])
def test_url_protocol_id(self, mocked_get_secret_key): """ PUSHTOKEN: Test url protocol id customization """ public_key, secret_key = crypto_sign_keypair() mocked_get_secret_key.return_value = secret_key user_public_key = base64.b64encode(public_key) fake = FakeTokenModel() token = PushTokenClass(fake) token.addToTokenInfo('partition', 0) token.addToTokenInfo('user_token_id', 123) token.addToTokenInfo('user_dsa_public_key', user_public_key) with nested(patch.dict(config), request_context_safety()): if 'mobile_app_protocol_id' in config: del config['mobile_app_protocol_id'] request_context['hsm'] = fake_hsm_wrapper # if no mobile_app_protocol_id is set, it should default # to lseqr message = 'here are the 2,750 quit you asked for. can i move' + \ 'to OT I level now? - tom' url, _ = token.create_challenge_url(transaction_id='1234567890', content_type=0, message=message, callback_url='foo') self.assertTrue(url.startswith('lseqr://')) # ------------------------------------------------------------------ -- fake = FakeTokenModel() token = PushTokenClass(fake) token.addToTokenInfo('partition', 0) token.addToTokenInfo('user_token_id', 123) token.addToTokenInfo('user_dsa_public_key', user_public_key) with nested(patch.dict(config, {'mobile_app_protocol_id': 'yolo'}), request_context_safety()): request_context['hsm'] = fake_hsm_wrapper message = 'here are the 2,750 quit you asked for. can i move' + \ 'to OT I level now? - tom' url, _ = token.create_challenge_url(transaction_id='1234567890', content_type=0, message=message, callback_url='foo') self.assertTrue(url.startswith('yolo://'))
def test_delete_pool(self): with contextlib.nested( self.subnet(), mock.patch.object(self.driver.plugin._core_plugin, 'get_subnet') ) as (subnet, mock_get_subnet): mock_get_subnet.return_value = subnet['subnet'] with contextlib.nested( self.pool(provider=LBAAS_PROVIDER_NAME), mock.patch.object(self.driver.plugin._core_plugin, 'delete_port'), mock.patch.object(self.driver.plugin._core_plugin, 'get_ports'), mock.patch.object(self.driver.plugin, 'get_pools'), mock.patch.object(self.driver.plugin, '_delete_db_pool') ) as (pool, mock_delete_port, mock_get_ports, mock_get_pools, mock_delete_db_pool): mock_delete_port.return_value = None mock_get_ports.return_value = [{'id': TESTPOOL_PORT_ID}] mock_get_pools.return_value = [] mock_delete_db_pool.return_value = None #reset the remove_resource() mock self.remove_resource_mock.reset_mock() # execute the method under test. self.driver.delete_pool(self.context, pool['pool']) pool_resource_path = "%s/%s" % ( (netscaler_driver.POOLS_RESOURCE, pool['pool']['id'])) # Assert that delete_resource was called # once with expected params. (self.remove_resource_mock .assert_called_once_with(None, pool_resource_path))
def update(): u"""Function defining all steps required to properly update application.""" # Django app refresh: with contextlib.nested( cd('/var/www/volontuloapp_org/volontulo'), prefix('workon volontulo') ): run('git checkout master') run('git pull') run('pip install -r requirements.txt') # Gulp frontend refresh: with contextlib.nested( cd('/var/www/volontuloapp_org/volontulo/volontulo') ): run('npm install .') run('./node_modules/gulp/bin/gulp.js build') # Django site refresh: with contextlib.nested( cd('/var/www/volontuloapp_org'), prefix('workon volontulo') ): run('python manage.py migrate --traceback') run('service apache2 restart')
def test_delete_pool_health_monitor(self): with contextlib.nested( self.subnet(), mock.patch.object(self.driver.plugin._core_plugin, 'get_subnet') ) as (subnet, mock_get_subnet): mock_get_subnet.return_value = subnet['subnet'] with self.pool(provider=LBAAS_PROVIDER_NAME) as pool: with contextlib.nested( self.health_monitor(pool_id=pool['pool']['id']), mock.patch.object(self.driver.plugin, '_delete_db_pool_health_monitor') ) as (health_monitor, mock_delete_db_monitor): mock_delete_db_monitor.return_value = None # reset the remove_resource() mock self.remove_resource_mock.reset_mock() # execute the method under test. self.driver.delete_pool_health_monitor( self.context, health_monitor['health_monitor'], pool['pool']['id']) monitor_resource_path = "%s/%s/%s/%s" % ( netscaler_driver.POOLS_RESOURCE, pool['pool']['id'], netscaler_driver.MONITORS_RESOURCE, health_monitor['health_monitor']['id']) # Assert that delete_resource was called once # with expected params. self.remove_resource_mock.assert_called_once_with( None, monitor_resource_path)
def test_routes_update_for_multiple_routers(self): routes1 = [{'destination': '135.207.0.0/16', 'nexthop': '10.0.0.3'}] routes2 = [{'destination': '12.0.0.0/8', 'nexthop': '10.0.0.4'}] with contextlib.nested( self.router(), self.router(), self.subnet(cidr='10.0.0.0/24')) as (r1, r2, s): with contextlib.nested( self.port(subnet=s, no_delete=True), self.port(subnet=s, no_delete=True)) as (p1, p2): body = self._routes_update_prepare(r1['router']['id'], None, p1['port']['id'], routes1) self.assertEqual(body['router']['routes'], routes1) body = self._routes_update_prepare(r2['router']['id'], None, p2['port']['id'], routes2) self.assertEqual(body['router']['routes'], routes2) self._routes_update_cleanup(p1['port']['id'], None, r1['router']['id'], []) self._routes_update_cleanup(p2['port']['id'], None, r2['router']['id'], [])
def test_to_swift_req_subrequest_proxy_access_log(self): container = 'bucket' obj = 'obj' method = 'GET' # force_swift_request_proxy_log is True req = Request.blank('/%s/%s' % (container, obj), environ={'REQUEST_METHOD': method, 'swift.proxy_access_log_made': True}, headers={'Authorization': 'AWS test:tester:hmac'}) with nested(patch.object(Request, 'get_response'), patch.object(Request, 'remote_user', 'authorized'), patch('swift3.cfg.CONF.force_swift_request_proxy_log', True)) \ as (m_swift_resp, m_remote_user, m_cfg): m_swift_resp.return_value = FakeSwiftResponse() s3_req = S3AclRequest(req.environ, MagicMock()) sw_req = s3_req.to_swift_req(method, container, obj) self.assertFalse(sw_req.environ['swift.proxy_access_log_made']) # force_swift_request_proxy_log is False req = Request.blank('/%s/%s' % (container, obj), environ={'REQUEST_METHOD': method, 'swift.proxy_access_log_made': True}, headers={'Authorization': 'AWS test:tester:hmac'}) with nested(patch.object(Request, 'get_response'), patch.object(Request, 'remote_user', 'authorized')) \ as (m_swift_resp, m_remote_user): m_swift_resp.return_value = FakeSwiftResponse() s3_req = S3AclRequest(req.environ, MagicMock()) sw_req = s3_req.to_swift_req(method, container, obj) self.assertTrue(sw_req.environ['swift.proxy_access_log_made'])
def test_no_file_changes(self): args = self.parser.parse_args( ["my_template", "my_json", "-o", "my_output", "-v"]) with contextlib.nested( # This requires some deep patching patch('__builtin__.open', self.mocked_open, create=True), patch('sys.stdout', new=StringIO()), patch('sys.stderr', new=StringIO()) ) as (_, fake_out, fake_err): with self.assertRaises(FileWontChange): cli.render(args.json, args.template, args.output_file, args.verbose) args = self.parser.parse_args( ["my_template", "my_json", "-o", "my_output"]) with contextlib.nested( # This requires some deep patching patch('__builtin__.open', self.mocked_open, create=True), patch('sys.stdout', new=StringIO()), patch('sys.stderr', new=StringIO()) ) as (_, fake_out, fake_err): with self.assertRaises(SystemExit) as cm: cli.render(args.json, args.template, args.output_file, args.verbose) self.assertEquals(cm.exception.message, 1)
def test_buttons(self, print_report, run_dialog, new_store): new_store.return_value = self.store self._create_domain() search = self._show_search() search.search.refresh() self.assertSensitive(search._details_slave, ['print_button']) self.click(search._details_slave.print_button) print_report.assert_called_once_with(StockDecreaseReport, search.results, list(search.results), filters=search.search.get_search_filters()) search.search.refresh() self.assertNotSensitive(search._details_slave, ['details_button']) search.results.select(search.results[0]) self.assertSensitive(search._details_slave, ['details_button']) with contextlib.nested( mock.patch.object(self.store, 'commit'), mock.patch.object(self.store, 'close')) as (commit, close): self.click(search._details_slave.details_button) run_dialog.assert_called_once_with(StockDecreaseDetailsDialog, search, self.store, search.results[0].stock_decrease) run_dialog.reset_mock() with contextlib.nested( mock.patch.object(self.store, 'commit'), mock.patch.object(self.store, 'close')) as (commit, close): search.results.emit('row_activated', search.results[0]) run_dialog.assert_called_once_with(StockDecreaseDetailsDialog, search, self.store, search.results[0].stock_decrease)
def test_do_forums_digests_already_scheduled(self): # patch _time_slice # patch get_digest_subscribers dt1 = datetime.datetime.utcnow() dt2 = dt1 + datetime.timedelta(days=1) dt3 = dt2 + datetime.timedelta(days=1) # Scheduling the task for the first time sends the digests: with nested( patch('notifier.tasks.get_digest_subscribers', return_value=(usern(n) for n in range(10))), patch('notifier.tasks._time_slice', return_value=(dt1, dt2)), patch('notifier.tasks.generate_and_send_digests') ) as (_gs, _ts, t): task_result = do_forums_digests.delay() self.assertTrue(task_result.successful()) self.assertEqual(t.delay.call_count, 1) # Scheduling the task with the same time slice again does nothing: with nested( patch('notifier.tasks.get_digest_subscribers', return_value=(usern(n) for n in range(10))), patch('notifier.tasks._time_slice', return_value=(dt1, dt2)), patch('notifier.tasks.generate_and_send_digests') ) as (_gs, _ts, t): task_result = do_forums_digests.delay() self.assertTrue(task_result.successful()) self.assertEqual(t.delay.call_count, 0) # Scheduling the task with a different time slice sends the digests: with nested( patch('notifier.tasks.get_digest_subscribers', return_value=(usern(n) for n in range(10))), patch('notifier.tasks._time_slice', return_value=(dt2, dt3)), patch('notifier.tasks.generate_and_send_digests') ) as (_gs, _ts, t): task_result = do_forums_digests.delay() self.assertTrue(task_result.successful()) self.assertEqual(t.delay.call_count, 1)
def test_update_firewall_policy_replace_rules(self): attrs = self._get_test_firewall_policy_attrs() with self.firewall_policy() as fwp: with contextlib.nested(self.firewall_rule(name='fwr1', no_delete=True), self.firewall_rule(name='fwr2', no_delete=True)) as fr1: fw_rule_ids = [r['firewall_rule']['id'] for r in fr1] data = {'firewall_policy': {'firewall_rules': fw_rule_ids}} req = self.new_update_request('firewall_policies', data, fwp['firewall_policy']['id']) req.get_response(self.ext_api) with contextlib.nested(self.firewall_rule(name='fwr3', no_delete=True), self.firewall_rule(name='fwr4', no_delete=True)) as fr2: fw_rule_ids = [r['firewall_rule']['id'] for r in fr2] attrs['firewall_rules'] = fw_rule_ids data = {'firewall_policy': {'firewall_rules': fw_rule_ids}} req = self.new_update_request('firewall_policies', data, fwp['firewall_policy']['id']) res = self.deserialize(self.fmt, req.get_response(self.ext_api)) attrs['audited'] = False for k, v in attrs.iteritems(): self.assertEqual(res['firewall_policy'][k], v)
def in_product(self, prefix=None): """Switch the functional tester to work in product context. :param prefix: target product prefix :return: context manager object """ # Force setting tester and test environment functional.FunctionalTestCaseSetup.setUp(self) @contextlib.contextmanager def in_product_testenv(product_id): try: # Backup active test env original = self._testenv self._testenv = original.product_testenv(product_id) yield self._testenv finally: self._testenv = original if prefix is None: default_product = self._testenv._default_product() return contextlib.nested(in_product_testenv(default_product), self._tester.in_product(self._tester)) else: product_href = self._testenv.get_env_href(prefix=prefix) return contextlib.nested(in_product_testenv(prefix), self._tester.in_product(self._tester, product_href()))
def test_edit_playbook(self): """ Users should be able to edit a playbook. """ # Without sending back with nested( mock.patch('reclient.ReClient._get_playbook'), mock.patch('reclient.utils.deserialize')) as (get_pb, ds): m_path = mock.MagicMock('path') m_path.name = 'test/example.json' get_pb.return_value = (mock.MagicMock('pb'), m_path) with mock.patch('reclient.utils.edit_playbook') as edit_pb: # Nothing is returned assert self.reclient.edit_playbook( PROJECT, ID, noop=True) is None # With sending back with nested( mock.patch('reclient.ReClient._get_playbook'), mock.patch('reclient.utils.deserialize')) as (get_pb, ds): m_path = mock.MagicMock('path') m_path.name = 'test/example.json' get_pb.return_value = (mock.MagicMock('pb'), m_path) with mock.patch('reclient.utils.edit_playbook') as edit_pb: with mock.patch('reclient.ReClient._send_playbook') as send_pb: result = self.reclient.edit_playbook( PROJECT, ID, noop=False) # The result should be from the call of _send_playbook assert result == send_pb()
def test_show_details(self, run_dialog, new_store): new_store.return_value = self.store sale = self.create_sale() product = self.create_product(stock=2) client = self.create_client() sale = self.create_sale(client=client) sale.add_sellable(sellable=product.sellable) self.create_returned_sale(sale) search = ReturnedSaleSearch(self.store) search.search.refresh() with contextlib.nested( mock.patch.object(self.store, 'commit'), mock.patch.object(self.store, 'close')) as (commit, close): search.results.double_click(0) self.assertEqual(run_dialog.call_count, 1) run_dialog.assert_called_once_with(ReturnedSaleDialog, search, self.store, search.results[0]) run_dialog.reset_mock() search.results.select(search.results[0]) self.assertSensitive(search._details_slave, ['details_button']) with contextlib.nested( mock.patch.object(self.store, 'commit'), mock.patch.object(self.store, 'close')) as (commit, close): self.click(search._details_slave.details_button) self.assertEqual(run_dialog.call_count, 1) run_dialog.assert_called_once_with(ReturnedSaleDialog, search, self.store, search.results[0])
def test_create_pgreport_csv(self): rows = [ ["username", "loc", "last_login"], [self.students[0].username, unicode(self.problems[0].location), "2014/1/1"], [self.students[1].username, unicode(self.problems[1].location), "2014/1/1"], ] progress_mock = MagicMock() progress_mock.get_raw.return_value = rows scontent_mock = MagicMock() cstore_mock = MagicMock() cstore_mock.fs.new_file().__exit__.return_value = False with nested( patch('pgreport.views.StaticContent', return_value=scontent_mock), patch('pgreport.views.contentstore', return_value=cstore_mock), patch('pgreport.views.ProgressReport', return_value=progress_mock), ) as (smock, cmock, pmock): create_pgreport_csv(self.course.id) smock.compute_location.assert_called_once_with(ANY, "progress_students.csv.gz") cmock.assert_called_once_with() cmock.return_value.find.assert_called_once_with(ANY) cmock.return_value.find.return_value.get_id.assert_called_once_with() progress_mock.get_raw.return_value = rows cstore_mock.fs.new_file().__enter__().write.side_effect = GridFSError() with nested( patch('pgreport.views.StaticContent', return_value=scontent_mock), patch('pgreport.views.contentstore', return_value=cstore_mock), patch('pgreport.views.ProgressReport', return_value=progress_mock), ) as (smock, cmock, pmock): with self.assertRaises(GridFSError): create_pgreport_csv(self.course.id)
def test_generate_length_tests(self): f1 = open(self.fastqfile1, 'r') f2 = open(self.fastqfile2, 'r') with contextlib.nested(f1, f2): fastqpairs = fastq.FastqFilePairs(f1, f2) testgen = fastqpairs.generate_length_tests() # First record status, rec1, rec2 = testgen.next() self.assertEqual(rec1[0], '@SEQ_ID1') self.assertEqual(status, 3) # Second record status, rec1, rec2 = testgen.next() self.assertEqual(status, 1) f1 = open(self.fastqfile1, 'r') f2 = open(self.fastqfile2, 'r') test_results = [] with contextlib.nested(f1, f2): fastqpairs = fastq.FastqFilePairs(f1, f2) for status, rec1, rec2 in fastqpairs.generate_length_tests(1): test_results.append(status) self.assertEqual(test_results, [3,1,3]) f1 = open(self.fastqfile1, 'r') f2 = open(self.fastqfile2, 'r') test_results = [] with contextlib.nested(f1, f2): fastqpairs = fastq.FastqFilePairs(f1, f2) for status, rec1, rec2 in fastqpairs.generate_length_tests(11): test_results.append(status) self.assertEqual(test_results, [0,0,0])
def test_create_member_on_different_subnet_multiple_ports(self): cfg.CONF.set_override("allow_overlapping_ips", "true") with self.network() as other_net: with contextlib.nested( self.subnet(), self.subnet(cidr="20.0.0.0/24"), self.subnet(cidr="30.0.0.0/24"), self.subnet(network=other_net, cidr="30.0.0.0/24"), ) as (vip_sub, pool_sub, member_sub1, member_sub2): with self.pool(provider="radware", subnet_id=pool_sub["subnet"]["id"]) as pool: with contextlib.nested( self.port(subnet=member_sub1, fixed_ips=[{"ip_address": "30.0.0.2"}]), self.port(subnet=member_sub2, fixed_ips=[{"ip_address": "30.0.0.2"}]), ): with self.member(pool_id=pool["pool"]["id"], address="30.0.0.2"): with self.vip(pool=pool, subnet=vip_sub): calls = [ mock.call( "POST", "/api/workflow/" + pool["pool"]["id"] + "/action/BaseCreate", mock.ANY, driver.TEMPLATE_HEADER, ) ] self.driver_rest_call_mock.assert_has_calls(calls, any_order=True) calls = self.driver_rest_call_mock.mock_calls params = calls[-2][1][2]["parameters"] m_sub_array = params["member_subnet_array"] m_mask_array = params["member_mask_array"] m_gw_array = params["member_gw_array"] self.assertEqual(m_sub_array, ["30.0.0.2"]) self.assertEqual(m_mask_array, ["255.255.255.255"]) self.assertEqual(m_gw_array, [pool_sub["subnet"]["gateway_ip"]])
def test_update_interface_ip_details(self): gwdict = dict(gateway='1.1.1.1', metric=50) ipdict = dict(cidr='1.1.1.1/24', broadcast='1.1.1.255', scope='global', ip_version=4, dynamic=False) with contextlib.nested( mock.patch.object(ip_lib.IpAddrCommand, 'add'), mock.patch.object(ip_lib.IpAddrCommand, 'delete') ) as (add_fn, del_fn): self.lbm.update_interface_ip_details("br0", "eth0", [ipdict], None) self.assertTrue(add_fn.called) self.assertTrue(del_fn.called) with contextlib.nested( mock.patch.object(ip_lib.IpRouteCommand, 'add_gateway'), mock.patch.object(ip_lib.IpRouteCommand, 'delete_gateway') ) as (addgw_fn, delgw_fn): self.lbm.update_interface_ip_details("br0", "eth0", None, gwdict) self.assertTrue(addgw_fn.called) self.assertTrue(delgw_fn.called)
def test_check_geonode_is_up(self): from contextlib import nested from geonode.maps.utils import check_geonode_is_up def blowup(): raise Exception("BOOM") with patch('geonode.maps.models.Layer.objects.gs_catalog') as mock_gs: mock_gs.get_workspaces.side_effect = blowup self.assertRaises(GeoNodeException, check_geonode_is_up) with nested( patch('geonode.maps.models.Layer.objects.gs_catalog'), patch('geonode.maps.models.Layer.objects.geonetwork') ) as (mock_gs, mock_gn): mock_gn.login.side_effect = blowup self.assertRaises(GeoNodeException, check_geonode_is_up) self.assertTrue(mock_gs.get_workspaces.called) with nested( patch('geonode.maps.models.Layer.objects.gs_catalog'), patch('geonode.maps.models.Layer.objects.geonetwork') ) as (mock_gs, mock_gn): # no assertion, this should just run without error check_geonode_is_up()
def test_PUT_object_with_long_names(self): for i in (220, 221): longname = 'o' * i path = '/V1.0/a/c2/' + longname with nested( patch("swiftonfile.swift.common.middleware." "check_constraints.get_container_info", self.container2_info_mock), patch("swiftonfile.swift.common.middleware." "check_constraints.POLICIES", self.policies_mock)): resp = Request.blank(path, environ={'REQUEST_METHOD': 'PUT'} ).get_response(self.test_check) self.assertEqual(resp.status_int, 200) longname = 'o' * 222 path = '/V1.0/a/c2/' + longname with nested( patch("swiftonfile.swift.common.middleware.check_constraints." "get_container_info", self.container2_info_mock), patch("swiftonfile.swift.common.middleware.check_constraints." "POLICIES", self.policies_mock)): resp = Request.blank(path, environ={'REQUEST_METHOD': 'PUT'} ).get_response(self.test_check) self.assertEqual(resp.status_int, 400) self.assertTrue('too long' in resp.body)
def test_run_synapse_check(): module = 'paasta_tools.monitoring.check_synapse_replication' parse_method = module + '.parse_synapse_check_options' replication_method = module + '.get_replication_for_services' check_replication_method = module + '.check_replication' mock_parse_options = mock.Mock() mock_parse_options.synapse_host_port = 'foo' mock_parse_options.services = ['wat', 'service', 'is'] mock_replication = {'wat': 2, 'service': 1, 'is': 0} for return_value in range(0, 4): with nested( mock.patch(parse_method, return_value=mock_parse_options), mock.patch(replication_method, return_value=mock_replication), mock.patch(check_replication_method, return_value=(return_value, 'CHECK'))): with pytest.raises(SystemExit) as error: run_synapse_check() assert error.value.code == return_value # Mock check results for those services mock_service_status = {'wat': 0, 'service': 1, 'is': 2} def mock_check(name, replication, warn, crit): return mock_service_status[name], 'CHECK' with nested(mock.patch(parse_method, return_value=mock_parse_options), mock.patch(replication_method, return_value=mock_replication), mock.patch(check_replication_method, new=mock_check)): with pytest.raises(SystemExit) as error: run_synapse_check() assert error.value.code == 2
def test_bind_port_cache(self): with contextlib.nested( self.subnet(), mock.patch(SERVER_POOL + '.rest_get_switch', return_value=True) ) as (sub, rmock): makeport = functools.partial(self.port, **{ 'subnet': sub, 'arg_list': (portbindings.HOST_ID,), portbindings.HOST_ID: 'hostname'}) with contextlib.nested(makeport(), makeport(), makeport()) as ports: # response from first should be cached rmock.assert_called_once_with('hostname') for port in ports: self.assertEqual(portbindings.VIF_TYPE_IVS, port['port'][portbindings.VIF_TYPE]) rmock.reset_mock() # expired cache should result in new calls mock.patch(DRIVER_MOD + '.CACHE_VSWITCH_TIME', new=0).start() with contextlib.nested(makeport(), makeport(), makeport()) as ports: self.assertEqual(3, rmock.call_count) for port in ports: self.assertEqual(portbindings.VIF_TYPE_IVS, port['port'][portbindings.VIF_TYPE])
def test_moderated_upload(self): """ Test if moderation flag works """ with self.settings(ADMIN_MODERATE_UPLOADS=False): layer_upload_url = reverse('layer_upload') self.client.login(username=self.user, password=self.passwd) # we get list of paths to shp files and list of suffixes input_paths, suffixes = self._get_input_paths() # we need file objects from above.. input_files = [open(fp, 'rb') for fp in input_paths] # ..but also specific mapping for upload files = dict(zip(['{}_file'.format(s) for s in suffixes], input_files)) # don't forget about renaming main file files['base_file'] = files.pop('shp_file') with contextlib.nested(*input_files): files['permissions'] = '{}' files['charset'] = 'utf-8' files['layer_title'] = 'test layer' resp = self.client.post(layer_upload_url, data=files) self.assertEqual(resp.status_code, 200) data = json.loads(resp.content) lname = data['url'].split(':')[-1] l = Layer.objects.get(name=lname) self.assertTrue(l.is_published) with self.settings(ADMIN_MODERATE_UPLOADS=True): layer_upload_url = reverse('layer_upload') self.client.login(username=self.user, password=self.passwd) # we get list of paths to shp files and list of suffixes input_paths, suffixes = self._get_input_paths() # we need file objects from above.. input_files = [open(fp, 'rb') for fp in input_paths] # ..but also specific mapping for upload files = dict(zip(['{}_file'.format(s) for s in suffixes], input_files)) # don't forget about renaming main file files['base_file'] = files.pop('shp_file') with contextlib.nested(*input_files): files['permissions'] = '{}' files['charset'] = 'utf-8' files['layer_title'] = 'test layer' resp = self.client.post(layer_upload_url, data=files) self.assertEqual(resp.status_code, 200) data = json.loads(resp.content) lname = data['url'].split(':')[-1] l = Layer.objects.get(name=lname) self.assertFalse(l.is_published)
def test_show_task_list(self): task = ProgressReportTask(self.func_mock) with nested(patch("sys.stdout", new_callable=StringIO.StringIO), patch("pgreport.tasks.celery")) as ( std_mock, cel_mock, ): stat_mock = MagicMock() stat_mock.active.return_value = {"queue": None} cel_mock.control.inspect.return_value = stat_mock task.show_task_list() cel_mock.control.inspect.assert_called_once_with() self.assertEquals(std_mock.getvalue(), "*** Active queues ***\n{}: []\n".format("queue")) status = {"args": "argment", "id": "task_id", "name": "task_name", "worker_pid": "worker_pid"} with nested(patch("sys.stdout", new_callable=StringIO.StringIO), patch("pgreport.tasks.celery")) as ( std_mock, cel_mock, ): stat_mock = MagicMock() stat_mock.active.return_value = {"queue": [status]} cel_mock.control.inspect.return_value = stat_mock task.show_task_list() self.assertEquals( std_mock.getvalue(), "*** Active queues ***\nqueue: [\n * Task id: {id}, Task args: {args}, Task name: {name}, Worker pid: {worker_pid}\n]\n".format( **status ), )
def test_url_protocol_id(self, mocked_get_secret_key): """ QRToken unittest: Test url protocol id customization """ mocked_get_secret_key.return_value = 'X' * 64 user_public_key = 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' fake = FakeTokenModel() token = QrTokenClass(fake) token.addToTokenInfo('user_token_id', 1234) token.addToTokenInfo('user_public_key', user_public_key) with nested(patch.dict(config), request_context_safety()): if 'mobile_app_protocol_id' in config: del config['mobile_app_protocol_id'] request_context['hsm'] = fake_hsm_wrapper # if no mobile_app_protocol_id is set, it should default # to lseqr message = 'here are the 2,750 quit you asked for. can i move' + \ 'to OT I level now? - tom' url, _ = token.create_challenge_url(transaction_id='1234567890', content_type=0, message=message, callback_url='foo', callback_sms_number='+491234') self.assertTrue(url.startswith('lseqr://')) # -------------------------------------------------------------------- - fake = FakeTokenModel() token = QrTokenClass(fake) token.addToTokenInfo('user_token_id', 1234) token.addToTokenInfo('user_public_key', user_public_key) with nested(patch.dict(config, {'mobile_app_protocol_id': 'yolo'}), request_context_safety()): request_context['hsm'] = fake_hsm_wrapper message = 'here are the 2,750 quit you asked for. can i move' + \ 'to OT I level now? - tom' url, _ = token.create_challenge_url(transaction_id='1234567890', content_type=0, message=message, callback_url='foo', callback_sms_number='+491234') self.assertTrue(url.startswith('yolo://'))
def draw(self, projection, camera, player_position, r): self.prog.vars.mvp = projection * camera with nested(self.prog): self.map.bind(self.map.id) self.tiles.bind(self.tiles.id) with nested(self.prog, self.map, self.tiles): self.prog.vars.playerLight = r*0.1 + 0.9 self.prog.vars.playerPosition = player_position.tuple() self.mesh.draw(GL_QUADS)
def test_multi_tenant_flip_alllocation(self): tenant1_id = _uuid() tenant2_id = _uuid() with contextlib.nested( self.network(tenant_id=tenant1_id), self.network(tenant_id=tenant2_id)) as (n1, n2): with contextlib.nested( self.subnet(network=n1, cidr='11.0.0.0/24'), self.subnet(network=n2, cidr='12.0.0.0/24'), self.subnet(cidr='13.0.0.0/24')) as (s1, s2, psub): with contextlib.nested( self.router(tenant_id=tenant1_id), self.router(tenant_id=tenant2_id), self.port(subnet=s1, tenant_id=tenant1_id), self.port(subnet=s2, tenant_id=tenant2_id)) as (r1, r2, p1, p2): self._set_net_external(psub['subnet']['network_id']) s1id = p1['port']['fixed_ips'][0]['subnet_id'] s2id = p2['port']['fixed_ips'][0]['subnet_id'] s1 = {'subnet': {'id': s1id}} s2 = {'subnet': {'id': s2id}} self._add_external_gateway_to_router( r1['router']['id'], psub['subnet']['network_id']) self._add_external_gateway_to_router( r2['router']['id'], psub['subnet']['network_id']) self._router_interface_action( 'add', r1['router']['id'], s1['subnet']['id'], None) self._router_interface_action( 'add', r2['router']['id'], s2['subnet']['id'], None) fl1 = self._make_floatingip_for_tenant_port( net_id=psub['subnet']['network_id'], port_id=p1['port']['id'], tenant_id=tenant1_id) self.httpPatch.stop() multiFloatPatch = mock.patch( HTTPCON, new=fake_server.VerifyMultiTenantFloatingIP) multiFloatPatch.start() fl2 = self._make_floatingip_for_tenant_port( net_id=psub['subnet']['network_id'], port_id=p2['port']['id'], tenant_id=tenant2_id) multiFloatPatch.stop() self.httpPatch.start() self._delete('floatingips', fl1['floatingip']['id']) self._delete('floatingips', fl2['floatingip']['id']) self._router_interface_action( 'remove', r1['router']['id'], s1['subnet']['id'], None) self._router_interface_action( 'remove', r2['router']['id'], s2['subnet']['id'], None)
def test_wait_stack_delete_for_instance_delete(self): name = "scs1" scn = self.create_servicechain_node() scn_id = scn['servicechain_node']['id'] scs = self.create_servicechain_spec(name=name, nodes=[scn_id]) sc_spec_id = scs['servicechain_spec']['id'] with mock.patch.object(simplechain_driver.HeatClient, 'create') as stack_create: stack_create.return_value = {'stack': { 'id': uuidutils.generate_uuid()}} sc_instance = self.create_servicechain_instance( name="sc_instance_1", servicechain_specs=[sc_spec_id]) self.assertEqual( sc_instance['servicechain_instance']['servicechain_specs'], [sc_spec_id]) # Verify that as part of delete service chain instance we call # get method for heat stack 5 times before giving up if the state # does not become DELETE_COMPLETE with contextlib.nested( mock.patch.object(simplechain_driver.HeatClient, 'delete'), mock.patch.object(simplechain_driver.HeatClient, 'get')) as ( stack_delete, stack_get): stack_get.return_value = MockStackObject('PENDING_DELETE') req = self.new_delete_request( 'servicechain_instances', sc_instance['servicechain_instance']['id']) res = req.get_response(self.ext_api) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) stack_delete.assert_called_once_with(mock.ANY) self.assertEqual(stack_get.call_count, STACK_DELETE_RETRIES) # Create and delete another service chain instance and verify that # we call get method for heat stack only once if the stack state # is DELETE_COMPLETE sc_instance = self.create_servicechain_instance( name="sc_instance_1", servicechain_specs=[sc_spec_id]) self.assertEqual( sc_instance['servicechain_instance']['servicechain_specs'], [sc_spec_id]) with contextlib.nested( mock.patch.object(simplechain_driver.HeatClient, 'delete'), mock.patch.object(simplechain_driver.HeatClient, 'get')) as ( stack_delete, stack_get): stack_get.return_value = MockStackObject('DELETE_COMPLETE') req = self.new_delete_request( 'servicechain_instances', sc_instance['servicechain_instance']['id']) res = req.get_response(self.ext_api) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) stack_delete.assert_called_once_with(mock.ANY) self.assertEqual(stack_get.call_count, 1)
def test_create_member_on_different_subnets(self): with contextlib.nested( self.subnet(), self.subnet(cidr='20.0.0.0/24'), self.subnet(cidr='30.0.0.0/24') ) as (vip_sub, pool_sub, member_sub): with self.pool(provider='radware', subnet_id=pool_sub['subnet']['id']) as pool: with contextlib.nested( self.port(subnet=vip_sub, fixed_ips=[{'ip_address': '10.0.0.2'}]), self.port(subnet=pool_sub, fixed_ips=[{'ip_address': '20.0.0.2'}]), self.port(subnet=member_sub, fixed_ips=[{'ip_address': '30.0.0.2'}]) ): with contextlib.nested( self.member(pool_id=pool['pool']['id'], address='10.0.0.2'), self.member(pool_id=pool['pool']['id'], address='20.0.0.2'), self.member(pool_id=pool['pool']['id'], address='30.0.0.2') ) as (member_vip, member_pool, member_out): with self.vip(pool=pool, subnet=vip_sub): calls = [ mock.call( 'POST', '/api/workflow/' + pool['pool']['id'] + '/action/BaseCreate', mock.ANY, driver.TEMPLATE_HEADER ) ] self.driver_rest_call_mock.assert_has_calls( calls, any_order=True) mock_calls = self.driver_rest_call_mock.mock_calls params = mock_calls[-2][1][2]['parameters'] member_subnet_array = params['member_subnet_array'] member_mask_array = params['member_mask_array'] member_gw_array = params['member_gw_array'] self.assertEqual(member_subnet_array, ['10.0.0.0', '255.255.255.255', '30.0.0.0']) self.assertEqual(member_mask_array, ['255.255.255.0', '255.255.255.255', '255.255.255.0']) self.assertEqual( member_gw_array, [pool_sub['subnet']['gateway_ip'], '255.255.255.255', pool_sub['subnet']['gateway_ip']])
def as_module(source, name="module"): resource_cm = [ limit_resource(resource.RLIMIT_NOFILE, 10), limit_resource(resource.RLIMIT_FSIZE, 0), limit_resource(resource.RLIMIT_NPROC, 0), ] module = imp.new_module(name) output = StringIO() with contextlib.nested(redirect_stdout(output), working_directory()): with contextlib.nested(*resource_cm): exec source in module.__dict__ return module, output.getvalue()
def test_wait_for_haproxy_state(): tests = [ # Service is immediately in the expected state [[True], 0, 1], # Service never enters the expected state [10 * [False], 1, 10], # Service enters the expected state on third poll [[False, False, True], 0, 3], ] for test in tests: mock_check_haproxy_state, expected_result, expected_mock_sleep_call_count = test with contextlib.nested( mock.patch('time.sleep'), mock.patch('subprocess.check_call'), mock.patch( 'nerve_tools.updown_service.check_haproxy_state', side_effect=mock_check_haproxy_state)) as (mock_sleep, _, _): actual_result = updown_service.wait_for_haproxy_state( 'service_three.main', 'down', 10, 1) assert expected_result == actual_result assert mock_sleep.call_count == expected_mock_sleep_call_count
def test_status_chronos_jobs_is_not_deployed(): jobs = [] complete_job_config = mock.Mock() complete_job_config.get_desired_state_human = mock.Mock() verbose = False with contextlib.nested( mock.patch( 'paasta_tools.chronos_serviceinit.format_chronos_job_status', autospec=True, return_value='job_status_output', ), mock.patch( 'paasta_tools.chronos_serviceinit.get_running_tasks_from_active_frameworks', autospec=True, return_value=[], ), ): actual = chronos_serviceinit.status_chronos_jobs( mock.Mock(), # Chronos client jobs, complete_job_config, verbose, ) assert 'not set up' in actual
def test_file_exists_fails(self): def fake_call_method(module, method, *args, **kwargs): if method == 'SearchDatastore_Task': return 'fake_exists_task' # Should never get here self.fail() def fake_wait_for_task(task_ref): if task_ref == 'fake_exists_task': raise error_util.FileNotFoundException() # Should never get here self.fail() with contextlib.nested( mock.patch.object(self.session, '_call_method', fake_call_method), mock.patch.object(self.session, '_wait_for_task', fake_wait_for_task)): ds_path = ds_util.DatastorePath('ds', 'fake/path') file_exists = ds_util.file_exists(self.session, 'fake-browser', ds_path, 'fake-file') self.assertFalse(file_exists)
def test_change_salesperson(self, new_store): with self.sysparam(CHANGE_SALESPERSON_AFTER_CONFIRMED=True): new_store.return_value = self.store app = self.create_app(SalesApp, u'sales') results = app.results results.select(results[0]) results[0].status = Sale.STATUS_CONFIRMED results[0].sale.status = Sale.STATUS_CONFIRMED app._update_toolbar() with contextlib.nested(mock.patch.object(app, 'run_dialog'), mock.patch.object(self.store, 'commit'), mock.patch.object(self.store, 'close')) as context: run_dialog = context[0] self.activate(app.ChangeSalesperson) args, kwargs = run_dialog.call_args self.assertEqual(kwargs['model'], results[0].sale) self.assertEqual(kwargs['store'], self.store) run_dialog.assert_called_once_with(SalesPersonEditor, store=self.store, model=results[0].sale)
def test_setup_network(self): with contextlib.nested( patch.object(NetworkAdapter, "_create_dvs"), patch.object(VMwareUtils, "get_vcenter_session", return_value=fake_inputs.MOB()), patch.object(VMwareUtils, "get_data_center", return_value=fake_inputs.fake_datacenter), patch.object(NetworkAdapter, "_create_dvpg"), patch.object( OvsvappInstaller, '_ovsvapp_input', return_value=fake_inputs.data)) as (dvs_object, vmwareutil, ovsvapputil, mock_create_dvpg, mock_ovsvapp_input): inputs = copy.deepcopy(fake_inputs.data) self.ovsvapp_installer.setup_network(inputs) self.assertTrue(mock_ovsvapp_input.called) self.assertTrue(vmwareutil.called) self.assertTrue(ovsvapputil.called) self.assertTrue(dvs_object.called) self.assertTrue(mock_create_dvpg.called)
def mainloop(self, display_banner=None): """Start the mainloop. If an optional banner argument is given, it will override the internally created default banner. """ with nested(self.builtin_trap, self.display_trap): # if you run stuff with -c <cmd>, raw hist is not updated # ensure that it's in sync self.history_manager.sync_inputs() while 1: try: self.interact(display_banner=display_banner) #self.interact_with_readline() # XXX for testing of a readline-decoupled repl loop, call # interact_with_readline above break except KeyboardInterrupt: # this should not be necessary, but KeyboardInterrupt # handling seems rather unpredictable... self.write("\nKeyboardInterrupt in interact()\n")
def getringtones(self, result): result = com_lgvx4400.Phone.getringtones(self, result) if not conversions.helperavailable('pvconv'): return result media = result['ringtone'] # get& convert the voice memo files with contextlib.nested(common.usetempfile('qcp'), common.usetempfile('wav')) as (_qcp_file, _wav_file): try: vmemo_files = self.listfiles(self.VoiceMemoDir) keys = vmemo_files.keys() for k in keys: if k.endswith('.qcp'): key_name = 'VoiceMemo' + k[-8:-4] file(_qcp_file, 'wb').write(self.getfilecontents(k, True)) conversions.convertqcptowav(_qcp_file, _wav_file) media[key_name] = file(_wav_file, 'rb').read() except: if __debug__: raise result['ringtone'] = media return result
def test_query_fails(self): """Tests failed execution of the query command.""" mock_options = self.setup_mock_options(shards="0") with contextlib.nested( patch('twitter.common.app.get_options', return_value=mock_options), patch('apache.aurora.admin.admin.make_admin_client', return_value=create_autospec(spec=AuroraClientAPI)), patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS)) as (_, mock_make_admin_client, _): api = mock_make_admin_client.return_value api.query.return_value = self.create_response(self.create_task()) try: query([self.TEST_CLUSTER, 'test_role', 'test_job'], mock_options) except SystemExit: pass else: assert 'Expected exception is not raised' api.query.assert_called_with(self.task_query())
def test_safe_domain_exclude_hosts_from_list(self): """Test successful execution of the sla_list_safe_domain command with exclude list option.""" mock_vector = self.create_mock_vector(self.create_hosts(3, 80, 100)) mock_options = self.setup_mock_options( exclude_list=','.join(['h0', 'h1'])) with contextlib.nested( patch('apache.aurora.client.commands.admin.AuroraClientAPI', new=Mock(spec=AuroraClientAPI)), patch('apache.aurora.client.commands.admin.print_results'), patch('apache.aurora.client.commands.admin.CLUSTERS', new=self.TEST_CLUSTERS), patch('twitter.common.app.get_options', return_value=mock_options)) as (mock_api, mock_print_results, test_clusters, mock_options): mock_api.return_value.sla_get_safe_domain_vector.return_value = mock_vector sla_list_safe_domain(['west', '50', '100s']) mock_vector.get_safe_hosts.assert_called_once_with( 50.0, 100.0, {}, DEFAULT_GROUPING) mock_print_results.assert_called_once_with(['h2'])
def test_run_server_success(self): calls = defaultdict(lambda: 0) def _initrp(conf_file, app_section, *args, **kwargs): calls['_initrp'] += 1 return ( {'__file__': 'test', 'workers': 0}, 'logger', 'log_name') def _loadapp(uri, name=None, **kwargs): calls['_loadapp'] += 1 with nested( mock.patch.object(wsgi, '_initrp', _initrp), mock.patch.object(wsgi, 'get_socket'), mock.patch.object(wsgi, 'drop_privileges'), mock.patch.object(wsgi, 'loadapp', _loadapp), mock.patch.object(wsgi, 'capture_stdio'), mock.patch.object(wsgi, 'run_server')): rc = wsgi.run_wsgi('conf_file', 'app_section') self.assertEqual(calls['_initrp'], 1) self.assertEqual(calls['_loadapp'], 1) self.assertEqual(rc, 0)
def tests_status_marathon_job_when_running_running_tasks_with_suspended_deployment(): client = mock.create_autospec(marathon.MarathonClient) app = mock.create_autospec(marathon.models.app.MarathonApp) client.get_app.return_value = app service = 'my_service' instance = 'my_instance' app_id = 'mock_app_id' normal_instance_count = 5 mock_tasks_running = 0 app.tasks_running = mock_tasks_running app.deployments = ['test_deployment'] app.instances = 0 app.tasks_running = 0 with contextlib.nested( mock.patch('paasta_tools.marathon_tools.is_app_id_running', return_value=True), mock.patch('paasta_tools.marathon_tools.get_app_queue_status', return_value=(True, 0)), ) as ( is_app_id_running_patch, get_app_queue_status_patch, ): output = marathon_serviceinit.status_marathon_job(service, instance, app_id, normal_instance_count, client) is_app_id_running_patch.assert_called_once_with(app_id, client) assert get_app_queue_status_patch.call_count == 0 assert 'Stopped' in output
def test_status_marathon_job_verbose(): client = mock.create_autospec(marathon.MarathonClient) app = mock.create_autospec(marathon.models.app.MarathonApp) client.get_app.return_value = app service = 'my_service' instance = 'my_instance' task = mock.Mock() with contextlib.nested( mock.patch('paasta_tools.marathon_serviceinit.marathon_tools.get_matching_appids'), mock.patch('paasta_tools.marathon_serviceinit.get_verbose_status_of_marathon_app'), mock.patch('paasta_tools.marathon_tools.is_app_id_running', return_value=True), ) as ( mock_get_matching_appids, mock_get_verbose_app, mock_is_app_id_running, ): mock_get_matching_appids.return_value = ['/app1'] mock_get_verbose_app.return_value = ([task], 'fake_return') tasks, out = marathon_serviceinit.status_marathon_job_verbose(service, instance, client) mock_is_app_id_running.assert_called_once_with('/app1', client) mock_get_matching_appids.assert_called_once_with(service, instance, client) mock_get_verbose_app.assert_called_once_with(app) assert tasks == [task] assert 'fake_return' in out
def _wait_for_add_chap_user(self, cmd, auth_username, auth_password, start): # Don't move 'import pexpect' to the begining of the file so that # a tempest can work. import pexpect lock = basic_lib.get_process_lock(self.hsnm_lock_file) with nested(self.hsnm_lock, lock): try: child = pexpect.spawn(cmd) child.expect('Secret: ', timeout=CHAP_TIMEOUT) child.sendline(auth_password) child.expect('Re-enter Secret: ', timeout=CHAP_TIMEOUT) child.sendline(auth_password) child.expect( 'The CHAP user information has ' 'been added successfully.', timeout=CHAP_TIMEOUT) except Exception: if time.time() - start >= EXEC_TIMEOUT: msg = basic_lib.output_err(642, user=auth_username) raise exception.HBSDError(message=msg) else: raise loopingcall.LoopingCallDone(True)
def test_fix_instance_volume_disk_paths(self): block_device_info = get_fake_block_dev_info() fake_vol_conn_info = ( block_device_info['block_device_mapping'][0]['connection_info']) with contextlib.nested( mock.patch.object(self._volumeops, '_get_volume_driver'), mock.patch.object(self._volumeops, 'ebs_root_in_block_devices') ) as (mock_get_volume_driver, mock_ebs_in_block_devices): fake_vol_driver = mock_get_volume_driver.return_value mock_ebs_in_block_devices.return_value = False self._volumeops.fix_instance_volume_disk_paths( mock.sentinel.instance_name, block_device_info) func = fake_vol_driver.fix_instance_volume_disk_path func.assert_called_once_with( mock.sentinel.instance_name, fake_vol_conn_info, 0)
def _test_cert_api(self, method, **kwargs): ctxt = context.RequestContext('fake_user', 'fake_project') rpcapi = cert_rpcapi.CertAPI() self.assertIsNotNone(rpcapi.client) self.assertEqual(rpcapi.client.target.topic, CONF.cert_topic) orig_prepare = rpcapi.client.prepare with contextlib.nested( mock.patch.object(rpcapi.client, 'call'), mock.patch.object(rpcapi.client, 'prepare'), mock.patch.object(rpcapi.client, 'can_send_version'), ) as (rpc_mock, prepare_mock, csv_mock): prepare_mock.return_value = rpcapi.client rpc_mock.return_value = 'foo' csv_mock.side_effect = ( lambda v: orig_prepare().can_send_version()) retval = getattr(rpcapi, method)(ctxt, **kwargs) self.assertEqual(retval, rpc_mock.return_value) prepare_mock.assert_called_once_with() rpc_mock.assert_called_once_with(ctxt, method, **kwargs)
def test_port_update(self): with contextlib.nested( mock.patch.object(ovs_lib.OVSBridge, 'get_vif_port_by_id'), mock.patch.object(self.agent.sg_agent, 'refresh_firewall')) as (get_vif_port_by_id, refresh_firewall): context = mock.Mock() vifport = ovs_lib.VifPort('port1', '1', 'id-1', 'mac-1', self.agent.int_br) # The OVS port does not exist. get_vif_port_by_id.return_value = None port = {'id': 'update-port-1'} self.agent.callback_nec.port_update(context, port=port) self.assertEqual(get_vif_port_by_id.call_count, 1) self.assertFalse(refresh_firewall.call_count) # The OVS port exists but no security group is associated. get_vif_port_by_id.return_value = vifport port = {'id': 'update-port-1'} self.agent.callback_nec.port_update(context, port=port) self.assertEqual(get_vif_port_by_id.call_count, 2) self.assertFalse(refresh_firewall.call_count) # The OVS port exists but a security group is associated. get_vif_port_by_id.return_value = vifport port = {'id': 'update-port-1', ext_sg.SECURITYGROUPS: ['default']} self.agent.callback_nec.port_update(context, port=port) self.assertEqual(get_vif_port_by_id.call_count, 3) self.assertEqual(refresh_firewall.call_count, 1) get_vif_port_by_id.return_value = None port = {'id': 'update-port-1', ext_sg.SECURITYGROUPS: ['default']} self.agent.callback_nec.port_update(context, port=port) self.assertEqual(get_vif_port_by_id.call_count, 4) self.assertEqual(refresh_firewall.call_count, 1)
def build_model(inputs, num_classes, is_training, update_bn, hparams): """Constructs the vision model being trained/evaled. Args: inputs: input features/images being fed to the image model build built. num_classes: number of output classes being predicted. is_training: is the model training or not. hparams: additional hyperparameters associated with the image model. Returns: The logits of the image model. """ scopes = setup_arg_scopes(is_training) with contextlib.nested(*scopes): if hparams.model_name == "pyramid_net": logits = build_shake_drop_model( inputs, num_classes, is_training) elif hparams.model_name == "wrn": logits = build_wrn_model( inputs, num_classes, hparams.wrn_size, update_bn) elif hparams.model_name == "shake_shake": logits = build_shake_shake_model( inputs, num_classes, hparams, is_training) return logits
def test_create_and_get_firewall(self): ctx = context.get_admin_context() name = 'firewall' with contextlib.nested( self.firewall_rule(name='fwr1', do_delete=False), self.firewall_rule(name='fwr2', do_delete=False), self.firewall_rule(name='fwr3', do_delete=False)) as fr: fw_rule_ids = [r['firewall_rule']['id'] for r in fr] with self.firewall_policy(firewall_rules=fw_rule_ids, do_delete=False) as fwp: fwp_id = fwp['firewall_policy']['id'] with self.router() as r: with self.firewall(name=name, firewall_policy_id=fwp_id, router_ids=[r['router']['id'] ]) as firewall: fw_create = firewall['firewall'] fw_expect = self._make_firewall_dict_with_rules( ctx, fw_create['id']) self.driver.update_firewall(ctx, VSE_ID, fw_expect) fw_get = self.driver.get_firewall(ctx, VSE_ID) self._compare_firewall_rule_lists( fwp_id, fw_get['firewall_rule_list'], fw_expect['firewall_rule_list'])
def test_process_network_devices_failed(self): device_info = {'current': [1, 2, 3]} agent = linuxbridge_neutron_agent.LinuxBridgeNeutronAgentRPC({}, 0, None) raise_exception = [0] def info_mock(msg): if raise_exception[0] < 2: raise_exception[0] += 1 else: raise RuntimeError() with mock.patch.object(agent.br_mgr, "update_devices") as update_devices: update_devices.side_effect = device_info with contextlib.nested( mock.patch.object(linuxbridge_neutron_agent.LOG, 'info'), mock.patch.object(agent, 'process_network_devices')) as ( log, process_network_devices): log.side_effect = info_mock process_network_devices.side_effect = RuntimeError with testtools.ExpectedException(RuntimeError): agent.daemon_loop() self.assertEqual(3, log.call_count)
def test_fdb_del_flows(self): self._prepare_l2_pop_ofports() fdb_entry = { 'net2': { 'network_type': 'gre', 'segment_id': 'tun2', 'ports': { 'ip_agent_2': [['mac', 'ip'], n_const.FLOODING_ENTRY] } } } with contextlib.nested( mock.patch.object(self.agent.tun_br, 'mod_flow'), mock.patch.object(self.agent.tun_br, 'delete_flows'), ) as (mod_flow_fn, del_flow_fn): self.agent.fdb_remove(None, fdb_entry) del_flow_fn.assert_called_with(table=constants.UCAST_TO_TUN, dl_vlan='vlan2', dl_dst='mac') mod_flow_fn.assert_called_with(table=constants.FLOOD_TO_TUN, priority=1, dl_vlan='vlan2', actions='strip_vlan,' 'set_tunnel:seg2,output:1')
def test_not_sale_cancel(self, new_store): new_store.return_value = self.store with self.sysparam(ALLOW_CANCEL_CONFIRMED_SALES=True): app = self.create_app(SalesApp, u'sales') sale_view = app.results[0] app.results.select(sale_view) sale_view.status = Sale.STATUS_CONFIRMED sale_view.sale.status = Sale.STATUS_CONFIRMED app._update_toolbar() for item in sale_view.sale.get_items(): item.quantity = 2 with contextlib.nested(mock.patch.object(app, 'run_dialog'), mock.patch.object(self.store, 'commit'), mock.patch.object(self.store, 'close')) as context: run_dialog = context[0] run_dialog.return_value = None self.activate(app.SalesCancel) msg_text = u"This will cancel the sale, Are you sure?" args, kwargs = run_dialog.call_args self.assertEqual(args, (NoteEditor, self.store)) self.assertEqual(kwargs['model'], None) self.assertEqual(kwargs['message_text'], msg_text) self.assertEqual(kwargs['label_text'], u"Reason") self.assertEqual(kwargs['mandatory'], True) self.assertEqual(kwargs['ok_button_label'], u"Cancel sale") self.assertEqual(kwargs['cancel_button_label'], u"Don't cancel") self.assertEqual(NoteEditor.retval, None) self.assertEqual(run_dialog.call_count, 1) self.assertEqual(sale_view.sale.status, Sale.STATUS_CONFIRMED)
def test_fdb_add_port(self): self._prepare_l2_pop_ofports() fdb_entry = { 'net1': { 'network_type': 'gre', 'segment_id': 'tun1', 'ports': { 'ip_agent_1': [['mac', 'ip']] } } } with contextlib.nested( mock.patch.object(self.agent.tun_br, 'add_flow'), mock.patch.object(self.agent.tun_br, 'mod_flow'), mock.patch.object(self.agent, 'setup_tunnel_port')) as (add_flow_fn, mod_flow_fn, add_tun_fn): self.agent.fdb_add(None, fdb_entry) self.assertFalse(add_tun_fn.called) fdb_entry['net1']['ports']['ip_agent_3'] = [['mac', 'ip']] self.agent.fdb_add(None, fdb_entry) add_tun_fn.assert_called_with('gre-ip_agent_3', 'ip_agent_3', 'gre')
def test_floatingip_delete(self): req = fakes.HTTPRequest.blank('') fip_val = {'address': '1.1.1.1', 'fixed_ip_id': '192.168.1.2'} with contextlib.nested( mock.patch.object(self.controller.network_api, 'disassociate_floating_ip'), mock.patch.object(self.controller.network_api, 'disassociate_and_release_floating_ip'), mock.patch.object(self.controller.network_api, 'release_floating_ip'), mock.patch.object(self.controller.network_api, 'get_instance_id_by_floating_address', return_value=None), mock.patch.object(self.controller.network_api, 'get_floating_ip', return_value=fip_val)) as (disoc_fip, dis_and_del, rel_fip, _, _): self.controller.delete(req, 1) self.assertFalse(disoc_fip.called) self.assertFalse(rel_fip.called) # Only disassociate_and_release_floating_ip is # called if using neutron self.assertTrue(dis_and_del.called)
def test_attach_volume_vmdk_invalid(self): connection_info = {'driver_volume_type': 'vmdk', 'serial': 'volume-fake-id', 'data': {'volume': 'vm-10', 'volume_id': 'volume-fake-id'}} instance = mock.MagicMock(name='fake-name', vm_state=vm_states.ACTIVE) vmdk_info = vm_util.VmdkInfo('fake-path', constants.ADAPTER_TYPE_IDE, constants.DISK_TYPE_PREALLOCATED, 1024, 'fake-device') with contextlib.nested( mock.patch.object(vm_util, 'get_vm_ref'), mock.patch.object(self._volumeops, '_get_volume_ref'), mock.patch.object(vm_util, 'get_vmdk_info', return_value=vmdk_info) ) as (get_vm_ref, get_volume_ref, get_vmdk_info): self.assertRaises(exception.Invalid, self._volumeops._attach_volume_vmdk, connection_info, instance) get_vm_ref.assert_called_once_with(self._volumeops._session, instance) get_volume_ref.assert_called_once_with( connection_info['data']['volume']) self.assertTrue(get_vmdk_info.called)
def test_status_chronos_jobs_get_running_tasks(): jobs = [{'name': 'my_service my_instance gityourmom configyourdad'}] complete_job_config = mock.Mock() complete_job_config.get_desired_state_human = mock.Mock() verbose = False with contextlib.nested( mock.patch( 'paasta_tools.chronos_serviceinit.format_chronos_job_status', autospec=True, return_value='job_status_output', ), mock.patch( 'paasta_tools.chronos_serviceinit.get_running_tasks_from_active_frameworks', autospec=True, return_value=[], ), ) as (_, mock_get_running_tasks): chronos_serviceinit.status_chronos_jobs( mock.Mock(), # Chronos client jobs, complete_job_config, verbose, ) assert mock_get_running_tasks.call_count == 1
def silence(filter_=lambda line: True, file_=stdout): """ Prevent lines matching `filter_` ending up on `file_` (defaults to stdout) """ if not filter_: yield return if not type(file_) == file: # Unable to filter because it's not a file instance. yield return saved_stdout = dup(file_.fileno()) stdout_file = PyFile_AsFile(file_) from cStringIO import StringIO filt_content = StringIO() with nested(fdopen(saved_stdout, "w"), fifo()) as (real_stdout, filename): try: tfr = threaded_file_reader(filename, filter_, real_stdout, filt_content) with tfr: # Redirect stdout to pipe freopen(filename, "w", stdout_file) try: yield filt_content finally: # Redirect stdout back to it's original place freopen("/dev/fd/%i" % saved_stdout, "w", stdout_file) except: print "Hit an exception. Filtered content:" print filt_content.getvalue() raise
def test_update_member(self): member_from = { 'admin_state_up': True, 'status': 'PENDING_UPDATE', 'status_description': None, 'weight': 5, 'address': '10.0.0.4', 'tenant_id': TENANT_ID, 'protocol_port': 555, 'id': MEMBER_ID, 'pool_id': POOL_ID} member_to = { 'admin_state_up': True, 'status': 'ACTIVE', 'status_description': None, 'weight': 10, 'address': '10.0.0.4', 'tenant_id': TENANT_ID, 'protocol_port': 555, 'id': MEMBER_ID, 'pool_id': POOL_ID} mapping = {'edge_id': EDGE_ID, 'edge_pool_id': EDGE_POOL_ID} with contextlib.nested( mock.patch.object(db, 'get_nsxv_edge_pool_mapping'), mock.patch.object(self.service_plugin._core_plugin.nsx_v, 'update_member') ) as (mock_get_mapping, mock_update_member): mock_get_mapping.return_value = mapping self.edge_driver.update_member(self.context, member_from, member_to) mock_update_member.assert_called_with(self.context, member_from, member_to, mapping)
def test_move_host_back_to_cluster(self): host = [{'name': 'fake-host', 'obj': 'host-obj'}] fake_inputs.data['host_name'] = 'fake-host' fake_inputs.data['vcenter_host'] = '10.10.10.10' fake_inputs.data['vcenter_https_port'] = 443 fake_inputs.data['vcenter_username'] = '******' fake_inputs.data['vcenter_password'] = '******' with contextlib.nested( patch.object(VMwareUtils, 'get_vcenter_session', return_value=fake_inputs.MOB), patch.object(VMwareUtils, 'get_view_ref'), patch.object(VMwareUtils, 'collect_properties', return_value=host), patch.object(OVSvAppUtil, 'get_host_parent', retunr_value=PrepFolder()), patch.object(VMwareUtils, 'get_cluster'), patch.object(move_host, 'get_ovsvapp_from_host'), patch.object(OVSvAppUtil, 'disable_ha_on_ovsvapp'), patch.object(OVSvAppUtil, 'move_host_back_to_cluster')) as ( mock_get_vcenter_session, mock_get_view_ref, mock_collect_properties, mock_get_host_parent, mock_get_cluster, mock_get_ovsvapp_from_host, mock_disable_ha_on_ovsvapp, mock_move_host_back_to_cluster): move_host.move_host_back_to_cluster(fake_inputs.data) self.assertTrue(mock_get_vcenter_session.called) self.assertTrue(mock_get_view_ref.called) self.assertTrue(mock_collect_properties.called) self.assertTrue(mock_get_host_parent.called) self.assertTrue(mock_get_cluster.called) self.assertTrue(mock_get_ovsvapp_from_host.called) self.assertTrue(mock_disable_ha_on_ovsvapp.called) self.assertTrue(mock_move_host_back_to_cluster.called)
def test_roll_back_host_info(self): db_api = self.vc_driver.db_api cluster_data = copy.deepcopy(fake_data.cluster_data_remove) current_hosts_list = [{'name': 1}, {'name': 2}] prop = Prop() prop.value = json.dumps( { "hlm_prop": "val1", "network_driver": { "cluster_dvs_mapping": "mapping", 'name': ['network_driver_name'] } }, ) ret = ['network_driver_name'] with contextlib.nested( mock.patch.object(db_api, "get_properties"), mock.patch.object(utils, "strip_current_ovsvapp_host_info")) as ( get_prop, strip_curr_ovsvapp): get_prop.return_value = [prop] strip_curr_ovsvapp.return_value = ret result = self.vc_driver.roll_back_host_info( self.context, current_hosts_list, cluster_data) self.assertEquals(None, result)
def test_killall_job_output(self): """Test kill output.""" mock_context = FakeAuroraCommandContext() with contextlib.nested( patch('apache.aurora.client.cli.jobs.Job.create_context', return_value=mock_context), patch('apache.aurora.client.cli.jobs.JobMonitor', return_value=self.get_monitor_mock()), patch('apache.aurora.client.factory.CLUSTERS', new=self.TEST_CLUSTERS)): api = mock_context.get_api('west') api.kill_job.return_value = self.create_simple_success_response() with temporary_file() as fp: fp.write(self.get_valid_config()) fp.flush() cmd = AuroraCommandLine() cmd.execute([ 'job', 'killall', '--no-batching', '--config=%s' % fp.name, self.TEST_JOBSPEC ]) assert mock_context.get_out() == ['Job killall succeeded'] assert mock_context.get_err() == []