def test_cache(self): cache.add('criteria:test_crit', self.crit) cache.add('criteria:test_crit:flags', mox.SameElementsAs(self.crit.flags.all())) cache.add('criteria:test_crit:users', mox.SameElementsAs(self.crit.users.all())) cache.add('criteria:test_crit:groups', mox.SameElementsAs(self.crit.groups.all())) self.mock.ReplayAll() cache_criteria(instance=self.crit) self.mock.VerifyAll()
def test_validate_networks(self): requested_networks = [('my_netid1', 'test', None), ('my_netid2', 'test2', None)] self.moxed_client.list_networks( id=mox.SameElementsAs(['my_netid1', 'my_netid2']), tenant_id=self.context.project_id, shared=False).AndReturn({'networks': self.nets2}) self.moxed_client.list_networks( id=mox.SameElementsAs(['my_netid1', 'my_netid2']), shared=True).AndReturn({'networks': []}) self.mox.ReplayAll() api = quantumapi.API() api.validate_networks(self.context, requested_networks)
def testExtract(self): """Tests legend_item_extractor's Extract method.""" static_icons = ['icon_href'] kml_colors = [ 'FF123456', '12ABCDEF', 'FF654321', legend_item_extractor.LINE_DEFAULT_KML_COLOR ] href_icon = ('<IconStyle><Icon><href>%s</href></Icon></IconStyle>' % static_icons[0]) colored_icon = """<IconStyle> <Icon><href>colored_icon_href</href></Icon> <color>%s</color> </IconStyle>""" % kml_colors[0] no_href = '<IconStyle><color>%s</color></IconStyle>' % kml_colors[1] linestyle = '<LineStyle><color>%s</color></LineStyle>' % kml_colors[2] polystyle = '<PolyStyle><color>%s</color></PolyStyle>' % kml_colors[2] color_style = '<color>Ignored</color>' kml = """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.2"> <Document> <name>test</name> <Style>%s</Style> <Style>%s</Style> <Style>%s</Style> <Style>%s</Style> <Style>%s</Style> <Style>%s</Style> <Style>%s</Style> </Document> </kml>""" % (href_icon, colored_icon, no_href, linestyle, polystyle, linestyle + polystyle, color_style) self.assertEquals( # Icons # pylint: disable=g-long-lambda ( mox.SameElementsAs( map(self.CreateIconFromString, [no_href, colored_icon, href_icon])), # Lines [self.CreateLineFromString(linestyle)], # Polygons mox.SameElementsAs([ self.CreatePolygonFromString(polystyle), self.CreatePolygonFromString(polystyle, linestyle) ]), # Static icons; Colors set(static_icons), set(self.CssColors(kml_colors))), legend_item_extractor.Extract(kml))
def testVerify(self): attrlist = ['uid', 'uidNumber', 'gidNumber', 'gecos', 'cn', 'homeDirectory', 'fullName', 'loginShell', 'modifyTimestamp'] filterstr = '(&TEST_FILTER(modifyTimestamp>=19700101000001Z))' mock_rlo = self.mox.CreateMock(ldap.ldapobject.ReconnectLDAPObject) mock_rlo.simple_bind_s( cred='TEST_BIND_PASSWORD', who='TEST_BIND_DN') mock_rlo.search_ext(base='TEST_BASE', filterstr=filterstr, scope=ldap.SCOPE_ONELEVEL, attrlist=mox.SameElementsAs(attrlist), serverctrls=mox.Func(self.compareSPRC())).AndReturn('TEST_RES') mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None, None, [])) self.mox.StubOutWithMock(ldap, 'ldapobject') ldap.ldapobject.ReconnectLDAPObject( uri='TEST_URI', retry_max='TEST_RETRY_MAX', retry_delay='TEST_RETRY_DELAY').AndReturn(mock_rlo) self.mox.ReplayAll() source = ldapsource.LdapSource(self.config) self.assertEquals(0, source.Verify(0))
def expect_hosts_query_and_lock(self, jobs, manager, running_hosts, do_lock=True): """Expect asking for a job's hosts and, potentially, lock them. job_status.gather_job_hostnames() should be mocked out prior to call. @param jobs: a lists of FakeJobs with a valid ID. @param manager: mocked out HostLockManager @param running_hosts: list of FakeHosts that should be listed as 'Running'. @param do_lock: If |manager| should expect |running_hosts| to get added and locked. @return nothing, but self.afe, job_status.gather_job_hostnames, and manager will have expectations set. """ used_hostnames = [] for job in jobs: job_status.gather_job_hostnames( mox.IgnoreArg(), job).InAnyOrder().AndReturn(job.hostnames) used_hostnames.extend([h for h in job.hostnames if h]) if used_hostnames: self.afe.get_hosts(mox.SameElementsAs(used_hostnames), status='Running').AndReturn(running_hosts) if do_lock: manager.lock([h.hostname for h in running_hosts])
def _get_instance_nw_info(self, number): api = quantumapi.API() self.mox.StubOutWithMock(api.db, 'instance_info_cache_update') api.db.instance_info_cache_update(mox.IgnoreArg(), self.instance['uuid'], mox.IgnoreArg()) port_data = number == 1 and self.port_data1 or self.port_data2 self.moxed_client.list_ports( tenant_id=self.instance['project_id'], device_id=self.instance['uuid']).AndReturn({'ports': port_data}) nets = number == 1 and self.nets1 or self.nets2 self.moxed_client.list_networks(tenant_id=self.instance['project_id'], shared=False).AndReturn( {'networks': nets}) self.moxed_client.list_networks(shared=True).AndReturn( {'networks': []}) for i in xrange(1, number + 1): subnet_data = i == 1 and self.subnet_data1 or self.subnet_data2 self.moxed_client.list_subnets( id=mox.SameElementsAs(['my_subid%s' % i])).AndReturn( {'subnets': subnet_data}) self.moxed_client.list_ports( network_id=subnet_data[0]['network_id'], device_owner='network:dhcp').AndReturn({'ports': []}) self.mox.ReplayAll() nw_inf = api.get_instance_nw_info(self.context, self.instance) for i in xrange(0, number): self._verify_nw_info(nw_inf, i)
def test_get_instance_nw_info_with_nets(self): """Test get instance_nw_info with networks passed in.""" api = quantumapi.API() self.mox.StubOutWithMock(api.db, 'instance_info_cache_update') api.db.instance_info_cache_update(mox.IgnoreArg(), self.instance['uuid'], mox.IgnoreArg()) self.moxed_client.list_ports( tenant_id=self.instance['project_id'], device_id=self.instance['uuid']).AndReturn( {'ports': self.port_data1}) self.moxed_client.list_subnets( id=mox.SameElementsAs(['my_subid1'])).AndReturn( {'subnets': self.subnet_data1}) self.moxed_client.list_ports(network_id='my_netid1', device_owner='network:dhcp').AndReturn( {'ports': self.dhcp_port_data1}) quantumv2.get_client(mox.IgnoreArg(), admin=True).MultipleTimes().AndReturn( self.moxed_client) self.mox.ReplayAll() nw_inf = api.get_instance_nw_info(self.context, self.instance, networks=self.nets1) self._verify_nw_info(nw_inf, 0)
def test_validate_networks_ex_1(self): requested_networks = [('my_netid1', 'test', None), ('my_netid2', 'test2', None)] self.moxed_client.list_networks( id=mox.SameElementsAs(['my_netid1', 'my_netid2']), tenant_id=self.context.project_id, shared=False).AndReturn({'networks': self.nets1}) self.moxed_client.list_networks( id=mox.SameElementsAs(['my_netid1', 'my_netid2']), shared=True).AndReturn({'networks': []}) self.mox.ReplayAll() api = quantumapi.API() try: api.validate_networks(self.context, requested_networks) except exception.NetworkNotFound as ex: self.assertTrue("my_netid2" in str(ex))
def test_property_name_to_values(self): self.assertEqual( { 'cat': [5], 'dog': mox.SameElementsAs([10, 15]), 'mouse': ['happy'] }, datastore_viewer._property_name_to_values( [self.entity1, self.entity2]))
def testGenerateTrendingInstallsCache(self): """Tests _GenerateTrendingInstallsCache.""" self.mox.StubOutWithMock(reports_cache.models.InstallLog, 'all') self.mox.StubOutWithMock(reports_cache.gae_util, 'QueryIterator') self.mox.StubOutWithMock(reports_cache.models.ReportsCache, 'SetTrendingInstalls') install_one = self.mox.CreateMockAnything() install_one.package = 'package_one' install_two = self.mox.CreateMockAnything() install_two.package = 'package_two' install_three = self.mox.CreateMockAnything() install_three.package = 'package_three' install_four = self.mox.CreateMockAnything() install_four.package = 'package_four' installs = [ install_one, install_one, install_two, install_three, install_four ] mock_query = self.mox.CreateMockAnything() reports_cache.models.InstallLog.all().AndReturn(mock_query) mock_query.filter('mtime >', mox.IsA( reports_cache.datetime.datetime)).AndReturn(mock_query) reports_cache.gae_util.QueryIterator(mock_query).AndReturn(installs) install_one.IsSuccess().AndReturn(True) install_one.IsSuccess().AndReturn(True) install_two.IsSuccess().AndReturn(False) install_three.IsSuccess().AndReturn(False) install_four.IsSuccess().AndReturn(True) expected_trending = { 'success': { 'packages': [ (install_one.package, 2, 66.666666666666657), (install_four.package, 1, 33.333333333333329), ], 'total': 3, }, 'failure': { 'packages': [ (install_two.package, 1, 50.0), (install_three.package, 1, 50.0), ], 'total': 2, }, } reports_cache.models.ReportsCache.SetTrendingInstalls( 1, mox.SameElementsAs(expected_trending)) self.mox.ReplayAll() reports_cache._GenerateTrendingInstallsCache(1) self.mox.VerifyAll()
def testGetShadowMap(self): test_shadow = ('cn=test,ou=People,dc=example,dc=com', {'uid': ['test'], 'shadowLastChange': ['11296'], 'shadowMax': ['99999'], 'shadowWarning': ['7'], 'shadowInactive': ['-1'], 'shadowExpire': ['-1'], 'shadowFlag': ['134537556'], 'modifyTimestamp': ['20070227012807Z'], 'userPassword': ['{CRYPT}p4ssw0rd']}) config = dict(self.config) attrlist = ['uid', 'shadowLastChange', 'shadowMin', 'shadowMax', 'shadowWarning', 'shadowInactive', 'shadowExpire', 'shadowFlag', 'userPassword', 'modifyTimestamp'] mock_rlo = self.mox.CreateMock(ldap.ldapobject.ReconnectLDAPObject) mock_rlo.simple_bind_s( cred='TEST_BIND_PASSWORD', who='TEST_BIND_DN') mock_rlo.search_ext(base='TEST_BASE', filterstr='TEST_FILTER', scope=ldap.SCOPE_ONELEVEL, attrlist=mox.SameElementsAs(attrlist), serverctrls=mox.Func(self.compareSPRC())).AndReturn('TEST_RES') mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_ENTRY, [test_shadow], None, [])) mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None, None, [])) self.mox.StubOutWithMock(ldap, 'ldapobject') ldap.ldapobject.ReconnectLDAPObject( uri='TEST_URI', retry_max='TEST_RETRY_MAX', retry_delay='TEST_RETRY_DELAY').AndReturn(mock_rlo) self.mox.ReplayAll() source = ldapsource.LdapSource(config) data = source.GetShadowMap() self.assertEqual(1, len(data)) ent = data.PopItem() self.assertEqual('test', ent.name) self.assertEqual('p4ssw0rd', ent.passwd)
def test_criteria_active_nothing_cached(self): self.mock.StubOutWithMock(middleware, 'cache_criteria') cache.get('criteria:all') cache.add('criteria:all', mox.SameElementsAs(Criteria.objects.all())) middleware.meets_criteria(self.request, self.criteria).AndReturn(True) cache.get('criteria:test_crit:flags') middleware.cache_criteria(instance=self.criteria) cache.get(u'flag_conflicts:test_flag').InAnyOrder() cache.add( u'flag_conflicts:test_flag', mox.SameElementsAs([])).InAnyOrder() cache.get(u'flag_conflicts:other_flag').InAnyOrder() cache.add( u'flag_conflicts:other_flag', mox.SameElementsAs([])).InAnyOrder() self.mock.ReplayAll() self.mw.process_request(self.request) self.mock.VerifyAll() self.assertDictEqual(self.request.affected_persist, {}) self.assertItemsEqual(self.request.affected_flags, [self.flag1.name, self.flag2.name])
def create_stack(self, template=None, time_constraints=None): if template is None: template = alarm_template temp = template_format.parse(template) template = tmpl.Template(temp) ctx = utils.dummy_context() ctx.tenant_id = 'test_tenant' stack = parser.Stack(ctx, utils.random_name(), template, disable_rollback=True) stack.store() self.m.StubOutWithMock(ceilometer.CeilometerClientPlugin, '_create') ceilometer.CeilometerClientPlugin._create().AndReturn(self.fa) al = copy.deepcopy(temp['Resources']['MEMAlarmHigh']['Properties']) al['description'] = mox.IgnoreArg() al['name'] = mox.IgnoreArg() al['alarm_actions'] = mox.IgnoreArg() al['insufficient_data_actions'] = None al['ok_actions'] = None al['repeat_actions'] = True al['enabled'] = True al['time_constraints'] = time_constraints if time_constraints else [] al['severity'] = 'low' rule = dict( period=60, evaluation_periods=1, threshold=50) for field in ['period', 'evaluation_periods', 'threshold']: del al[field] for field in ['statistic', 'comparison_operator', 'meter_name']: rule[field] = al[field] del al[field] if 'query' in al and al['query']: query = al['query'] else: query = [] if 'query' in al: del al['query'] if 'matching_metadata' in al and al['matching_metadata']: for k, v in al['matching_metadata'].items(): key = 'metadata.metering.' + k query.append(dict(field=key, op='eq', value=six.text_type(v))) if 'matching_metadata' in al: del al['matching_metadata'] if query: rule['query'] = mox.SameElementsAs(query) al['threshold_rule'] = rule al['type'] = 'threshold' self.m.StubOutWithMock(self.fa.alarms, 'create') self.fa.alarms.create(**al).AndReturn(FakeCeilometerAlarm()) return stack
def testGetPasswdMap(self): test_posix_account = ('cn=test,ou=People,dc=example,dc=com', {'uidNumber': [1000], 'gidNumber': [1000], 'uid': ['Testguy McTest'], 'cn': ['test'], 'homeDirectory': ['/home/test'], 'loginShell': ['/bin/sh'], 'userPassword': ['p4ssw0rd'], 'modifyTimestamp': ['20070227012807Z']}) config = dict(self.config) attrlist = ['uid', 'uidNumber', 'gidNumber', 'gecos', 'cn', 'homeDirectory', 'fullName', 'loginShell', 'modifyTimestamp'] mock_rlo = self.mox.CreateMock(ldap.ldapobject.ReconnectLDAPObject) mock_rlo.simple_bind_s( cred='TEST_BIND_PASSWORD', who='TEST_BIND_DN') mock_rlo.search_ext(base='TEST_BASE', filterstr='TEST_FILTER', scope=ldap.SCOPE_ONELEVEL, attrlist=mox.SameElementsAs(attrlist), serverctrls=mox.Func(self.compareSPRC())).AndReturn('TEST_RES') mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_ENTRY, [test_posix_account], None, [])) mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None, None, [])) self.mox.StubOutWithMock(ldap, 'ldapobject') ldap.ldapobject.ReconnectLDAPObject( uri='TEST_URI', retry_max='TEST_RETRY_MAX', retry_delay='TEST_RETRY_DELAY').AndReturn(mock_rlo) self.mox.ReplayAll() source = ldapsource.LdapSource(config) data = source.GetPasswdMap() self.assertEqual(1, len(data)) first = data.PopItem() self.assertEqual('Testguy McTest', first.name)
def testGetGroupMapBis(self): test_posix_group = ('cn=test,ou=Group,dc=example,dc=com', {'gidNumber': [1000], 'cn': ['testgroup'], 'member': ['cn=testguy,ou=People,dc=example,dc=com', 'cn=fooguy,ou=People,dc=example,dc=com', 'cn=barguy,ou=People,dc=example,dc=com'], 'modifyTimestamp': ['20070227012807Z']}) config = dict(self.config) config['rfc2307bis'] = 1 attrlist = ['cn', 'gidNumber', 'member', 'modifyTimestamp'] mock_rlo = self.mox.CreateMock(ldap.ldapobject.ReconnectLDAPObject) mock_rlo.simple_bind_s( cred='TEST_BIND_PASSWORD', who='TEST_BIND_DN') mock_rlo.search_ext(base='TEST_BASE', filterstr='TEST_FILTER', scope=ldap.SCOPE_ONELEVEL, attrlist=mox.SameElementsAs(attrlist), serverctrls=mox.Func(self.compareSPRC())).AndReturn('TEST_RES') mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_ENTRY, [test_posix_group], None, [])) mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None, None, [])) self.mox.StubOutWithMock(ldap, 'ldapobject') ldap.ldapobject.ReconnectLDAPObject( uri='TEST_URI', retry_max='TEST_RETRY_MAX', retry_delay='TEST_RETRY_DELAY').AndReturn(mock_rlo) self.mox.ReplayAll() source = ldapsource.LdapSource(config) data = source.GetGroupMap() self.assertEqual(1, len(data)) ent = data.PopItem() self.assertEqual('testgroup', ent.name) self.assertEqual(3, len(ent.members))
def testGetNetgroupMapWithDupes(self): test_posix_netgroup = ('cn=test,ou=netgroup,dc=example,dc=com', {'cn': ['test'], 'memberNisNetgroup': ['(-,hax0r,)'], 'nisNetgroupTriple': ['(-,hax0r,)'], 'modifyTimestamp': ['20070227012807Z'], }) config = dict(self.config) attrlist = ['cn', 'memberNisNetgroup', 'nisNetgroupTriple', 'modifyTimestamp'] mock_rlo = self.mox.CreateMock(ldap.ldapobject.ReconnectLDAPObject) mock_rlo.simple_bind_s( cred='TEST_BIND_PASSWORD', who='TEST_BIND_DN') mock_rlo.search(base='TEST_BASE', filterstr='TEST_FILTER', scope=ldap.SCOPE_ONELEVEL, attrlist=mox.SameElementsAs(attrlist)).AndReturn( 'TEST_RES') mock_rlo.result('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_ENTRY, [test_posix_netgroup])) mock_rlo.result('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None)) self.mox.StubOutWithMock(ldap, 'ldapobject') ldap.ldapobject.ReconnectLDAPObject( uri='TEST_URI', retry_max='TEST_RETRY_MAX', retry_delay='TEST_RETRY_DELAY').AndReturn(mock_rlo) self.mox.ReplayAll() source = ldapsource.LdapSource(config) data = source.GetNetgroupMap() self.assertEqual(1, len(data)) ent = data.PopItem() self.assertEqual('test', ent.name) self.assertEqual('(-,hax0r,)', ent.entries)
def testGetAutomountMap(self): test_automount = ('cn=user,ou=auto.home,ou=automounts,dc=example,dc=com', {'cn': ['user'], 'automountInformation': ['-tcp,rw home:/home/user'], 'modifyTimestamp': ['20070227012807Z'], }) config = dict(self.config) attrlist = ['cn', 'automountInformation', 'modifyTimestamp'] filterstr = '(objectclass=automount)' mock_rlo = self.mox.CreateMock(ldap.ldapobject.ReconnectLDAPObject) mock_rlo.simple_bind_s( cred='TEST_BIND_PASSWORD', who='TEST_BIND_DN') mock_rlo.search_ext(base='TEST_BASE', filterstr=filterstr, scope=ldap.SCOPE_ONELEVEL, attrlist=mox.SameElementsAs(attrlist), serverctrls=mox.Func(self.compareSPRC())).AndReturn('TEST_RES') mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_ENTRY, [test_automount], None, [])) mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None, None, [])) self.mox.StubOutWithMock(ldap, 'ldapobject') ldap.ldapobject.ReconnectLDAPObject( uri='TEST_URI', retry_max='TEST_RETRY_MAX', retry_delay='TEST_RETRY_DELAY').AndReturn(mock_rlo) self.mox.ReplayAll() source = ldapsource.LdapSource(config) data = source.GetAutomountMap(location='TEST_BASE') self.assertEqual(1, len(data)) ent = data.PopItem() self.assertEqual('user', ent.key) self.assertEqual('-tcp,rw', ent.options) self.assertEqual('home:/home/user', ent.location)
def testUnequalLists(self): """Should return False if the lists are not equal.""" self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c'])
def testExtractSeparatedPolyAndLineStyles(self): """Tests that Extract combines separated PolyStyle and LineStyle styles.""" kml_colors = [ 'AA123456', 'BB234567', 'CC345678', 'DD456789', legend_item_extractor.LINE_DEFAULT_KML_COLOR ] polystyle = '<PolyStyle><color>%s</color><width>%d</width></PolyStyle>' linestyle = '<LineStyle><color>%s</color><width>%d</width></LineStyle>' polystyles = [ polystyle % (kml_colors[0], 3), polystyle % (kml_colors[1], 4) ] linestyles = [ linestyle % (kml_colors[2], 5), linestyle % (kml_colors[3], 6) ] kml = """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.2"> <Document> <name>test</name> <Placemark> Separated PolyStyle and LineStyle should be composed into one polygon item. Should not exist as separate line and polygon items. Should be able to dig into normal StyleMap Styles. <Style>%s</Style> <StyleMap> <Pair> <key>normal</key> <Style>%s</Style> </Pair> <Pair> <key>highlight</key> <Style><PolyStyle>Should be ignored</PolyStyle></Style> </Pair> </StyleMap> </Placemark> <Placemark> <StyleMap> <Pair> <key>normal</key> <styleUrl>#a</styleUrl> </Pair> <Pair> Should be ignored <key>highlight</key> <styleUrl>#b</styleUrl> </Pair> </StyleMap> <styleUrl>#b</styleUrl> </Placemark> <Style id="a">%s</Style> <Style id="b">%s</Style> </Document> </kml>""" % (polystyles[0], linestyles[0], polystyles[1], linestyles[1]) self.assertEquals( # Line from shared style ( [], [self.CreateLineFromString(linestyles[1])], # Polygons mox.SameElementsAs([ self.CreatePolygonFromString(polystyles[0], linestyles[0]), self.CreatePolygonFromString(polystyles[1], linestyles[1]), self.CreatePolygonFromString(polystyles[1]) ]), # Icons and colors set(), set(self.CssColors(kml_colors))), legend_item_extractor.Extract(kml))
def _allocate_for_instance(self, net_idx=1, **kwargs): api = quantumapi.API() self.mox.StubOutWithMock(api, 'get_instance_nw_info') # Net idx is 1-based for compatibility with existing unit tests nets = self.nets[net_idx - 1] api.get_instance_nw_info(mox.IgnoreArg(), self.instance, networks=nets).AndReturn(None) ports = {} fixed_ips = {} req_net_ids = [] if 'requested_networks' in kwargs: for id, fixed_ip, port_id in kwargs['requested_networks']: if port_id: self.moxed_client.show_port(port_id).AndReturn({ 'port': { 'id': 'my_portid1', 'network_id': 'my_netid1' } }) ports['my_netid1'] = self.port_data1[0] id = 'my_netid1' else: fixed_ips[id] = fixed_ip req_net_ids.append(id) expected_network_order = req_net_ids else: expected_network_order = [n['id'] for n in nets] search_ids = [net['id'] for net in nets if net['id'] in req_net_ids] mox_list_network_params = dict(tenant_id=self.instance['project_id'], shared=False) if search_ids: mox_list_network_params['id'] = mox.SameElementsAs(search_ids) self.moxed_client.list_networks(**mox_list_network_params).AndReturn( {'networks': nets}) mox_list_network_params = dict(shared=True) if search_ids: mox_list_network_params['id'] = mox.SameElementsAs(search_ids) self.moxed_client.list_networks(**mox_list_network_params).AndReturn( {'networks': []}) for net_id in expected_network_order: port_req_body = { 'port': { 'device_id': self.instance['uuid'], 'device_owner': 'compute:nova', }, } port = ports.get(net_id, None) if port: port_id = port['id'] self.moxed_client.update_port( port_id, MyComparator(port_req_body)).AndReturn({'port': port}) else: fixed_ip = fixed_ips.get(net_id) if fixed_ip: port_req_body['port']['fixed_ip'] = fixed_ip port_req_body['port']['network_id'] = net_id port_req_body['port']['admin_state_up'] = True port_req_body['port']['tenant_id'] = \ self.instance['project_id'] res_port = {'port': {'id': 'fake'}} self.moxed_client.create_port( MyComparator(port_req_body)).AndReturn(res_port) self.mox.ReplayAll() api.allocate_for_instance(self.context, self.instance, **kwargs)
def testSortedLists(self): """Should return True if two lists are exactly equal.""" self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c'])
def testUnsortedLists(self): """Should return True if two lists are unequal but have same elements.""" self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1])
def testGetAutomountMasterMap(self): test_master_ou = ('ou=auto.master,ou=automounts,dc=example,dc=com', {'ou': ['auto.master']}) test_automount = ('cn=/home,ou=auto.master,ou=automounts,dc=example,dc=com', {'cn': ['/home'], 'automountInformation': ['ldap:ldap:ou=auto.home,' 'ou=automounts,dc=example,' 'dc=com'], 'modifyTimestamp': ['20070227012807Z']}) config = dict(self.config) # first search for the dn of ou=auto.master attrlist = ['dn'] filterstr = '(&(objectclass=automountMap)(ou=auto.master))' scope = ldap.SCOPE_SUBTREE mock_rlo = self.mox.CreateMock(ldap.ldapobject.ReconnectLDAPObject) mock_rlo.simple_bind_s( cred='TEST_BIND_PASSWORD', who='TEST_BIND_DN') mock_rlo.search_ext(base='TEST_BASE', filterstr=filterstr, scope=scope, attrlist=mox.SameElementsAs(attrlist), serverctrls=mox.Func(self.compareSPRC())).AndReturn('TEST_RES') mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_ENTRY, [test_master_ou], None, [])) mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None, None, [])) # then search for the entries under ou=auto.master attrlist = ['cn', 'automountInformation', 'modifyTimestamp'] filterstr = '(objectclass=automount)' scope = ldap.SCOPE_ONELEVEL base = 'ou=auto.master,ou=automounts,dc=example,dc=com' mock_rlo.search_ext(base=base, filterstr=filterstr, scope=scope, attrlist=mox.SameElementsAs(attrlist), serverctrls=mox.Func(self.compareSPRC())).AndReturn('TEST_RES') mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_ENTRY, [test_automount], None, [])) mock_rlo.result3('TEST_RES', all=0, timeout='TEST_TIMELIMIT').AndReturn( (ldap.RES_SEARCH_RESULT, None, None, [])) self.mox.StubOutWithMock(ldap, 'ldapobject') ldap.ldapobject.ReconnectLDAPObject( uri='TEST_URI', retry_max='TEST_RETRY_MAX', retry_delay='TEST_RETRY_DELAY').AndReturn(mock_rlo) self.mox.ReplayAll() source = ldapsource.LdapSource(config) data = source.GetAutomountMasterMap() self.assertEqual(1, len(data)) ent = data.PopItem() self.assertEqual('/home', ent.key) self.assertEqual('ou=auto.home,ou=automounts,dc=example,dc=com', ent.location) self.assertEqual(None, ent.options)
def testUnhashableLists(self): """Should return True if two lists have the same unhashable elements.""" self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}, {'a': 1}])
def testEmptyLists(self): """Should return True for two empty lists.""" self.assert_(mox.SameElementsAs([]) == [])
def testUnequalUnhashableLists(self): """Should return False if two lists with unhashable elements are unequal.""" self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])