desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests the get_managers method.'
def test_groupmember_manager(self):
norman = get_user_model().objects.get(username='norman') admin = get_user_model().objects.get(username='admin') self.assertFalse(self.bar.user_is_member(norman)) self.bar.join(norman) self.assertTrue(self.bar.user_is_member(norman)) self.assertTrue((norman not in self.bar.get_managers())) self.assertTrue((admin in self.bar.get_managers()))
'Verify pages that do not require login load without internal error'
def test_public_pages_render(self):
response = self.client.get('/groups/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/group/bar/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/group/bar/members/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/create/') self.assertEqual(302, response.status_code) response = self.client.get('/groups/group/bar/update/') self.assertEqual(302, response.status_code) response = self.client.get('/groups/group/bar/invite/') self.assertEqual(405, response.status_code)
'Verify pages that require login load without internal error'
def test_protected_pages_render(self):
self.assertTrue(self.client.login(username='admin', password='admin')) response = self.client.get('/groups/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/group/bar/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/group/bar/members/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/create/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/group/bar/update/') self.assertEqual(200, response.status_code) response = self.client.get('/groups/group/bar/invite/') self.assertEqual(405, response.status_code)
'Tests checking group membership'
def test_group_is_member(self):
anon = get_anonymous_user() normal = get_user_model().objects.get(username='norman') group = GroupProfile.objects.get(slug='bar') self.assert_((not group.user_is_member(anon))) self.assert_((not group.user_is_member(normal)))
'Tests adding a user to a group'
def test_group_add_member(self):
anon = get_anonymous_user() normal = get_user_model().objects.get(username='norman') group = GroupProfile.objects.get(slug='bar') group.join(normal) self.assert_(group.user_is_member(normal)) self.assertRaises(ValueError, (lambda : group.join(anon)))
'Tests inviting a registered user'
def test_invite_user(self):
normal = get_user_model().objects.get(username='norman') admin = get_user_model().objects.get(username='admin') group = GroupProfile.objects.get(slug='bar') group.invite(normal, admin, role='member', send=False) self.assert_(GroupInvitation.objects.filter(user=normal, from_user=admin, group=group).exists()) invite = GroupInvitation.objects.get(user=normal, from_user=admin, group=group) self.client.login(username='norman', password='norman') response = self.client.get('/groups/group/{group}/invite/{token}/'.format(group=group, token=invite.token)) self.assertEqual(200, response.status_code)
'Tests accepting an invitation'
def test_accept_invitation(self):
anon = get_anonymous_user() normal = get_user_model().objects.get(username='norman') admin = get_user_model().objects.get(username='admin') group = GroupProfile.objects.get(slug='bar') group.invite(normal, admin, role='member', send=False) invitation = GroupInvitation.objects.get(user=normal, from_user=admin, group=group) self.assertRaises(ValueError, (lambda : invitation.accept(anon))) self.assertRaises(ValueError, (lambda : invitation.accept(admin))) invitation.accept(normal) self.assert_(group.user_is_member(normal)) self.assert_((invitation.state == 'accepted'))
'Tests declining an invitation'
def test_decline_invitation(self):
anon = get_anonymous_user() normal = get_user_model().objects.get(username='norman') admin = get_user_model().objects.get(username='admin') group = GroupProfile.objects.get(slug='bar') group.invite(normal, admin, role='member', send=False) invitation = GroupInvitation.objects.get(user=normal, from_user=admin, group=group) self.assertRaises(ValueError, (lambda : invitation.decline(anon))) self.assertRaises(ValueError, (lambda : invitation.decline(admin))) invitation.decline(normal) self.assert_((not group.user_is_member(normal))) self.assert_((invitation.state == 'declined'))
'if Favorite exists for input user and type and pk of the input content_object, return it. else return None. impl note: can only be 0 or 1, per the class\'s unique_together.'
def favorite_for_user_and_content_object(self, user, content_object):
content_type = ContentType.objects.get_for_model(type(content_object)) result = self.filter(user=user, content_type=content_type, object_id=content_object.pk) if (len(result) > 0): return result[0] else: return None
'get the actual favorite objects for a user as a dict by content_type'
def bulk_favorite_objects(self, user):
favs = {} for m in (Document, Map, Layer, get_user_model()): ct = ContentType.objects.get_for_model(m) f = self.favorites_for_user(user).filter(content_type=ct) favs[ct.name] = m.objects.filter(id__in=f.values('object_id')) return favs
'call create view with valid user and content. then call again to check for idempotent.'
def test_create_favorite_view(self):
self.client.login(username=self.adm_un, password=self.adm_pw) response = self._get_response('add_favorite_document', ('1',)) favorites = Favorite.objects.all() self.assertEqual(favorites.count(), 1) ct = ContentType.objects.get_for_model(Document) self.assertEqual(favorites[0].content_type, ct) self.assertEqual(response.status_code, 200) json_content = json.loads(response.content) self.assertEqual(json_content['has_favorite'], 'true') expected_delete_url = reverse('delete_favorite', args=[favorites[0].pk]) self.assertEqual(json_content['delete_url'], expected_delete_url) response2 = self._get_response('add_favorite_document', ('1',)) favorites2 = Favorite.objects.all() self.assertEqual(favorites2.count(), 1) self.assertEqual(favorites2[0].content_type, ct) self.assertEqual(response2.status_code, 200) json_content2 = json.loads(response2.content) self.assertEqual(json_content2['has_favorite'], 'true') self.assertEqual(json_content2['delete_url'], expected_delete_url)
'call create view, not logged in. expect a redirect to login page.'
def test_create_favorite_view_login_required(self):
response = self._get_response('add_favorite_document', ('1',)) self.assertEqual(response.status_code, 302)
'call create view with object id that does not exist. expect not found.'
def test_create_favorite_view_id_not_found(self):
max_document_pk = Document.objects.aggregate(Max('pk')) pk_not_in_db = str((max_document_pk['pk__max'] + 1)) self.client.login(username=self.adm_un, password=self.adm_pw) response = self._get_response('add_favorite_document', (pk_not_in_db,)) self.assertEqual(response.status_code, 404)
'call delete view with valid user and favorite id. then call again to check for idempotent.'
def test_delete_favorite_view(self):
self.client.login(username=self.adm_un, password=self.adm_pw) response = self._get_response('add_favorite_document', ('1',)) favorites = Favorite.objects.all() self.assertEqual(favorites.count(), 1) ct = ContentType.objects.get_for_model(Document) self.assertEqual(favorites[0].content_type, ct) favorite_pk = favorites[0].pk response = self._get_response('delete_favorite', (favorite_pk,)) favorites = Favorite.objects.all() self.assertEqual(favorites.count(), 0) self.assertEqual(response.status_code, 200) json_content = json.loads(response.content) self.assertEqual(json_content['has_favorite'], 'false') response2 = self._get_response('delete_favorite', (favorite_pk,)) favorites2 = Favorite.objects.all() self.assertEqual(favorites2.count(), 0) self.assertEqual(response2.status_code, 200) json_content2 = json.loads(response2.content) self.assertEqual(json_content2['has_favorite'], 'false')
'call delete view, not logged in. expect a redirect to login page.'
def test_delete_favorite_view_login_required(self):
response = self._get_response('delete_favorite', ('1',)) self.assertEqual(response.status_code, 302)
'Returns a functional Django model based on current data'
def get_django_model(self, with_admin=False):
fields = [(f.name, f.get_django_field()) for f in self.fields.all()] return create_model(self.name, dict(fields), app_label=u'dynamic', module=u'geonode.contrib.dynamic', options={u'db_table': self.name, u'managed': False}, with_admin=with_admin)
''
def data_objects(self):
TheModel = self.get_django_model() return TheModel.using(DYNAMIC_DATASTORE)
'Returns the correct field type, instantiated with applicable settings'
def get_django_field(self):
settings = [(s.name, s.value) for s in self.settings.all()] settings = dict(settings) if (u'primary_key' in settings): settings[u'primary_key'] = bool(settings[u'primary_key']) if (u'blank' in settings): settings[u'blank'] = bool(settings[u'blank']) if (u'null' in settings): settings[u'null'] = bool(settings[u'null']) if (u'max_length' in settings): settings[u'max_length'] = int(settings[u'max_length']) field_type = getattr(models, self.type) return field_type(**settings)
'Test the creation of new sites'
def test_create_new_site(self):
response = self.api_client.post(self.api_site_url, data=self.slave2_data) self.assertEqual(response.status_code, 401) self.api_client.client.login(username=self.user, password=self.passwd) response = self.api_client.post(self.api_site_url, format='json', data=self.slave2_data) self.assertEqual(response.status_code, 201) self.assertTrue(Site.objects.filter(name='Slave2').exists())
'Test the deletion of sites also removes the SiteResources'
def test_delete_site(self):
response = self.client.delete(self.api_slave_detail_url, data={'name': 'Slave'}) self.assertEqual(response.status_code, 401) self.client.login(username=self.user, password=self.passwd) self.assertHttpAccepted(self.client.delete(self.api_slave_detail_url)) self.assertFalse(Site.objects.filter(name='Slave').exists()) self.assertFalse(SiteResources.objects.filter(site=self.slave_site).exists())
'Test that the detail page is not found of the resource is on another site'
def test_layer_detail_page_slave_site(self):
self.client.login(username=self.user, password=self.passwd) response = self.client.get(reverse('layer_detail', args=[Layer.objects.all()[0].alternate])) self.assertEqual(response.status_code, 404)
'Test that the detail page is allowed from the master site'
@override_settings(SITE_ID=1) def test_layer_detail_page_master_site(self):
self.client.login(username=self.user, password=self.passwd) response = self.client.get(reverse('layer_detail', args=[Layer.objects.all()[0].alternate])) self.assertEqual(response.status_code, 200)
'Test that the master site owns all the layers available in the database'
def test_master_site_all_layers(self):
self.assertEqual(SiteResources.objects.get(site=self.master_site).resources.count(), 8)
'Test that a normal site can see to the correct subset of layers'
def test_normal_site_subset_layers(self):
self.assertEqual(SiteResources.objects.get(site=self.slave_site).resources.count(), 7)
'Test that a non superuser, that can see different layers on different sites, can see the correct subset of layer on a normal site'
def test_non_superuser_normal_site_subset_layers(self):
anonymous_group = Group.objects.get(name='anonymous') for layer in Layer.objects.all()[:3]: remove_perm('view_resourcebase', self.bobby, layer.get_self_resource()) remove_perm('view_resourcebase', anonymous_group, layer.get_self_resource()) self.client.login(username='bobby', password='bob') response = self.client.get(self.api_layer_url) self.assertEquals(len(json.loads(response.content)['objects']), 5) self.client.logout() self.client.login(username=self.user, password=self.passwd) response = self.client.get(self.api_layer_url) self.assertEquals(len(json.loads(response.content)['objects']), 7)
'Test that a new site can\'t see any layer'
def test_new_site_cant_see_layers(self):
slave2 = Site.objects.create(name='Slave2', domain='slave2.test.org') self.assertEqual(SiteResources.objects.get(site=slave2).resources.count(), 0)
'Test that the layer_acls overridden function behaves correctly on a slave site'
def test_layer_acls_slave_site(self):
acls_site_url = reverse('layer_acls_dep') response = self.client.get(acls_site_url) self.assertValidJSONResponse(response) self.assertEqual(len(self.deserialize(response)['rw']), 0) self.assertEqual(len(self.deserialize(response)['ro']), 7) self.client.login(username='bobby', password='bob') response = self.client.get(acls_site_url) self.assertValidJSONResponse(response) self.assertEqual(len(self.deserialize(response)['rw']), 0) self.assertEqual(len(self.deserialize(response)['ro']), 7) self.client.logout() self.client.login(username=self.user, password=self.passwd) response = self.client.get(acls_site_url) self.assertValidJSONResponse(response) self.assertEqual(len(self.deserialize(response)['rw']), 7) self.assertEqual(len(self.deserialize(response)['ro']), 0)
'Test that the layer_acls overridden function behaves correctly on a master site'
@override_settings(SITE_ID=1) def test_layer_acls_master_site(self):
acls_site_url = reverse('layer_acls_dep') response = self.client.get(acls_site_url) self.assertValidJSONResponse(response) self.assertEqual(len(self.deserialize(response)['rw']), 0) self.assertEqual(len(self.deserialize(response)['ro']), 8) self.client.login(username='bobby', password='bob') response = self.client.get(acls_site_url) self.assertValidJSONResponse(response) self.assertEqual(len(self.deserialize(response)['rw']), 0) self.assertEqual(len(self.deserialize(response)['ro']), 8) self.client.logout() self.client.login(username=self.user, password=self.passwd) response = self.client.get(acls_site_url) self.assertValidJSONResponse(response) self.assertEqual(len(self.deserialize(response)['rw']), 8) self.assertEqual(len(self.deserialize(response)['ro']), 0)
'Test that the users belong to the correct site'
def test_people_belong_to_correct_site(self):
master_siteppl = SitePeople.objects.get(site=self.master_site) slave_siteppl = SitePeople.objects.get(site=self.slave_site) master_siteppl.people.add(self.admin) master_siteppl.people.add(self.bobby) slave_siteppl.people.add(self.admin) slave_siteppl.people.add(self.bobby) self.assertEqual(master_siteppl.people.count(), 2) self.assertEqual(slave_siteppl.people.count(), 7) Profile.objects.create(username='testsite', password='test1') self.assertEqual(master_siteppl.people.count(), 2) self.assertEqual(slave_siteppl.people.count(), 8)
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(DefaultMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(ResourceBaseMangler, self).decode(json_string) upload_sessions = [] for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) obj['fields']['owner'] = [self.owner] if ('distribution_url' in obj['fields']): if ((not (obj['fields']['distribution_url'] is None)) and ('layers' in obj['fields']['distribution_url'])): try: p = '(?P<protocol>http.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*)(?P<details_url>.*)' m = re.search(p, obj['fields']['distribution_url']) if ('http' in m.group('protocol')): obj['fields']['detail_url'] = (self.siteurl + m.group('details_url')) else: obj['fields']['detail_url'] = (self.siteurl + obj['fields']['distribution_url']) except: obj['fields']['detail_url'] = obj['fields']['distribution_url'] upload_sessions.append(self.add_upload_session(obj['pk'], obj['fields']['owner'])) default_obj.extend(upload_sessions) return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(LayerMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) obj['fields']['upload_session'] = obj['pk'] obj['fields']['service'] = None if self.datastore: obj['fields']['store'] = self.datastore else: obj['fields']['store'] = obj['fields']['name'] return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(LayerAttributesMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) obj['fields']['layer'] = (obj['fields']['layer'] + self.basepk) return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(MapLayersMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) obj['fields']['map'] = (obj['fields']['map'] + self.basepk) return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(DefaultMangler, self).decode(json_string) return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(ResourceBaseMangler, self).decode(json_string) upload_sessions = [] for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) obj['fields']['featured'] = False obj['fields']['rating'] = 0 obj['fields']['popular_count'] = 0 obj['fields']['share_count'] = 0 obj['fields']['is_published'] = True obj['fields']['thumbnail_url'] = '' if ('distribution_url' in obj['fields']): if ((not (obj['fields']['distribution_url'] is None)) and ('layers' in obj['fields']['distribution_url'])): obj['fields']['polymorphic_ctype'] = ['layers', 'layer'] try: p = '(?P<protocol>http.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*)(?P<details_url>.*)' m = re.search(p, obj['fields']['distribution_url']) if ('http' in m.group('protocol')): obj['fields']['detail_url'] = (self.siteurl + m.group('details_url')) else: obj['fields']['detail_url'] = (self.siteurl + obj['fields']['distribution_url']) except: obj['fields']['detail_url'] = obj['fields']['distribution_url'] else: obj['fields']['polymorphic_ctype'] = ['maps', 'map'] try: obj['fields'].pop('distribution_description', None) except: pass try: obj['fields'].pop('distribution_url', None) except: pass try: obj['fields'].pop('thumbnail', None) except: pass upload_sessions.append(self.add_upload_session(obj['pk'], obj['fields']['owner'])) default_obj.extend(upload_sessions) return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(LayerMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) from geonode.base.models import ResourceBase resource = ResourceBase.objects.get(pk=obj['pk']) obj['fields']['upload_session'] = obj['pk'] obj['fields']['service'] = None obj['fields']['charset'] = 'UTF-8' obj['fields']['title_en'] = resource.title obj['fields']['data_quality_statement_en'] = '' obj['fields']['regions'] = [] obj['fields']['supplemental_information_en'] = 'No information provided' obj['fields']['abstract_en'] = 'No abstract provided' obj['fields']['purpose_en'] = '' obj['fields']['constraints_other_en'] = '' obj['fields']['default_style'] = None if self.datastore: obj['fields']['store'] = self.datastore else: obj['fields']['store'] = obj['fields']['name'] try: obj['fields'].pop('popular_count', None) except: pass try: obj['fields'].pop('share_count', None) except: pass try: obj['fields'].pop('title', None) except: pass return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(LayerAttributesMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) obj['fields']['layer'] = (obj['fields']['layer'] + self.basepk) return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(MapMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) from geonode.base.models import ResourceBase resource = ResourceBase.objects.get(pk=obj['pk']) obj['fields']['urlsuffix'] = '' obj['fields']['title_en'] = resource.title obj['fields']['featuredurl'] = '' obj['fields']['data_quality_statement_en'] = None obj['fields']['supplemental_information_en'] = 'No information provided' obj['fields']['abstract_en'] = '' obj['fields']['purpose_en'] = None obj['fields']['constraints_other_en'] = None try: obj['fields'].pop('popular_count', None) except: pass try: obj['fields'].pop('share_count', None) except: pass try: obj['fields'].pop('title', None) except: pass return default_obj
'json_string is basicly string that you give to json.loads method'
def decode(self, json_string):
default_obj = super(MapLayersMangler, self).decode(json_string) for obj in default_obj: obj['pk'] = (obj['pk'] + self.basepk) obj['fields']['map'] = (obj['fields']['map'] + self.basepk) return default_obj
'Delete the jenkins node on which runs the amazon VM, this will both shutdown the VM and create a new one with a fresh geonode instance'
def redeployDemo(self):
nodes_data = json.loads(self.j.jenkins_open(Request((self.j.server + NODE_LIST)))) demo_node = self.getDemoNode(nodes_data) if (demo_node is not None): self.deleteNode(demo_node) self.buildJob(GEONODE_DEMO_JOB) print 're-deploy complete!' else: print 'No demo.genode.org node found on jenkins'
'Commodity method to get the correct jenkins node name, the name is composed by \'demo.geonode.org\' and the VM id'
def getDemoNode(self, nodes_data):
demo_node = None for node in nodes_data['computer']: if (GEONODE_DEMO_DOMAIN in node['displayName']): demo_node = node['displayName'] return demo_node
'Delete the jenkins node and shutdown the amazon VM'
def deleteNode(self, node_name):
print 'Deleting demo node' self.j.delete_node(node_name) print 'Deletion requested'
'Trigger a job build'
def buildJob(self, job):
print ('Building %s job' % job) self.j.build_job(job) print 'Build requested'
':param data: field info (title, help, etc..) :param widget_pack: internal wxWidgets to render'
def __init__(self, parent, title, msg, choices=None):
self.parent = parent self.title = None self.help_msg = None self.choices = choices self.do_layout(parent, title, msg)
'Looks up the attribute across all available panels and calls `Show()`'
def show(self, *args):
self._set_visibility('Show', *args)
'Looks up the attribute across all available panels and calls `Show()`'
def hide(self, *args):
self._set_visibility('Hide', *args)
'Checks for the existence `attr` on a given `panel` and performs `action` if found'
def _set_visibility(self, action, *args):
def _set_visibility(obj, attrs): for attr in attrs: if hasattr(obj, attr): instance = getattr(obj, attr) getattr(instance, action)() instance.Layout() for panel in [self, self.head_panel, self.foot_panel, self.config_panel]: _set_visibility(panel, args)
'itertools recipe: Collect data into fixed-length chunks or blocks'
def chunk(self, iterable, n, fillvalue=None):
args = ([iter(iterable)] * n) return izip_longest(fillvalue=fillvalue, *args)
'Reads the stdout of `process` and forwards lines and progress to any interested subscribers'
def _forward_stdout(self, process):
while True: line = process.stdout.readline() if (not line): break pub.send_message('console_update', msg=line) pub.send_message('progress_update', progress=self._extract_progress(line)) pub.send_message('execution_complete')
'Finds progress information in the text using the user-supplied regex and calculation instructions'
def _extract_progress(self, text):
find = partial(re.search, string=text.strip()) regex = unit(self.progress_regex) match = bind(regex, find) result = bind(match, self._calculate_progress) return result
'Calculates the final progress value found by the regex'
def _calculate_progress(self, match):
if (not self.progress_expr): return safe_float(match.group(1)) else: return self._eval_progress(match)
'Runs the user-supplied progress calculation rule'
def _eval_progress(self, match):
_locals = {k: safe_float(v) for (k, v) in match.groupdict().items()} if ('x' not in _locals): _locals['x'] = [safe_float(x) for x in match.groups()] try: return int(eval(self.progress_expr, {}, _locals)) except: return None
'returns the index of certain set of attributes (of a link) in the self.a list If the set of attributes is not found, returns None'
def previousIndex(self, attrs):
if (not attrs.has_key('href')): return None i = (-1) for a in self.a: i += 1 match = 0 if (a.has_key('href') and (a['href'] == attrs['href'])): if (a.has_key('title') or attrs.has_key('title')): if (a.has_key('title') and attrs.has_key('title') and (a['title'] == attrs['title'])): match = True else: match = True if match: return i
'Mock objects of this type will dynamically implement any requested member'
def __getattr__(self, key):
return random.choice(['world', math.pi])
'm 1 doc'
def m_1(self):
return __doc__
'm 3 doc'
def m_3(self):
__doc__ = 'new m 3 doc' return __doc__
'Override this as its busted. Please remove the function entirely once Dev10 438851 gets fixed.'
def test_true_compare_neg(self):
if ((sys.platform == 'cli') and (not ({} < 2))): printwith('Dev10 438851 has been fixed. Please remove this.')
'Override this as its busted. Please remove the function entirely once Dev10 438851 gets fixed.'
def test_compare_asbool_neg(self):
if ((sys.platform == 'cli') and (not ({} < 2))): printwith('Dev10 438851 has been fixed. Please remove this.')
'currently mainly test del list[slice]'
def test_slice(self):
test_str = testdata.long_string str_len = len(test_str) choices = ['', 0] numbers = [1, 2, 3, ((str_len / 2) - 1), (str_len / 2), ((str_len / 2) + 1), (str_len - 3), (str_len - 2), (str_len - 1), str_len, (str_len + 1), (str_len + 2), (str_len + 3), (str_len * 2)] numbers = numbers[::3] choices.extend(numbers) choices.extend([((-1) * x) for x in numbers]) for x in choices: for y in choices: for z in choices: if (z == 0): continue line = ('l = list(test_str); del l[%s:%s:%s]' % (str(x), str(y), str(z))) exec line printwith('case', ('del l[%s:%s:%s]' % (str(x), str(y), str(z)))) printwith('same', eval('l'), eval('len(l)'))
'test xrange with corner cases'
def test_xrange(self):
import sys import os if (os.name == 'posix'): print 'Skipping the xrange test on posix https://github.com/IronLanguages/main/issues/1607' return maxint = sys.maxint numbers = [1, 2, (maxint / 2), (maxint - 1), maxint, (maxint + 1), (maxint + 2)] choices = [0] choices.extend(numbers) choices.extend([((-1) * x) for x in numbers]) for x in choices: for y in choices: for z in choices: line = ('xrange(%s, %s, %s)' % (str(x), str(y), str(z))) printwith('case', line) try: xr = eval(line) xl = len(xr) cnt = 0 first = last = first2 = last2 = 'n/a' if (xl < 10): for x in xr: if (cnt == 0): first = x if (cnt == (xl - 1)): last = x cnt += 1 if (xl == 0): first2 = xr[0] if (xl > 1): (first2, last2) = (xr[0], xr[(xl - 1)]) printwith('same', xr, xl, first, last, first2, last2) except: printwith('same', sys.exc_type)
'Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info.'
def getOptionalRelease(self):
return self.optional
'Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, is None.'
def getMandatoryRelease(self):
return self.mandatory
'Sometimes remote output can become available after the prompt is printed locally.'
def EnsureInteractiveRemote(self, readError=True):
twoPlusTwoResult = self.ExecuteLine('2 + 2', readError) if ('4' == twoPlusTwoResult): return if ('' != twoPlusTwoResult): raise AssertionError, ('EnsureInteractive failed. 2+2 returned ' + twoPlusTwoResult) twoPlusTwoResult = self.EatToMarker('4\r\n') if ('4\r\n' != twoPlusTwoResult): raise AssertionError, ('EnsureInteractive failed. 2+2 returned ' + twoPlusTwoResult)
'Sometimes remote output can become available after the prompt is printed locally.'
def ExecuteLineRemote(self, line, expectedOutputLines=1):
result = self.ExecuteLine(line) if ('' != result): return result for i in xrange(expectedOutputLines): output = self.EatToMarker('\r\n') if (output == ''): raise AssertionError, ('ExecuteLineRemote failed. Returned empty after %s. Error is %s' % (result, self.ReadError())) result += output return result[0:(-2)]
'Standard constructor. Just copies a dictionary mapping PowerShell commands to names as members of this class.'
def __init__(self, data):
for (key, value) in data.items(): setattr(self, key, value)
''
def __init__(self, name, input=None):
self.name = name self.input = input
''
def __call__(self, *args, **kws):
return InvokeCommand(self.name, self.input, *args, **kws)
''
def __get__(self, instance, context=None):
return ShellCommand(self.name, instance)
''
def __repr__(self):
return ('<ShellCommand %s>' % self.name)
''
def __init__(self, data):
self.data = data
''
def __len__(self):
return self.data.Count
''
def __repr__(self):
if (self.data.Count == 0): return '' return str(self.out_string(Width=(System.Console.BufferWidth - 1))[0]).strip()
''
def __getitem__(self, index):
if (index >= self.data.Count): raise IndexError ret = self.data[index] if isinstance(ret, PSObject): return PSObjectWrapper(ret)
''
def __init__(self, data):
self.data = data
''
def __getattr__(self, name):
member = self.data.Members[name] if (member is not None): ret = member.Value if isinstance(ret, PSMethod): ret = InvokeToCallableAdapter(ret) return ret raise AttributeError(name)
''
def __repr__(self):
return self.data.Members['ToString'].Invoke()
''
def __init__(self, meth):
self.meth = meth
''
def __call__(self, *args):
return self.meth.Invoke(*args)
'Get all the methods with @accepts (and @returns) decorators Functions are assumed to be instance methods, unless decorated with @staticmethod'
def get_typed_methods(self):
FunctionType = type(ClrType.__dict__['dummy_function']) for (item_name, item) in self.__dict__.items(): function = None is_static = False if isinstance(item, FunctionType): (function, is_static) = (item, False) elif isinstance(item, staticmethod): (function, is_static) = (getattr(self, item_name), True) elif isinstance(item, property): if (item.fget and self.is_typed_method(item.fget)): if (item.fget.func_name == item_name): (yield TypedFunction(item.fget, False, item_name, None)) if (item.fset and self.is_typed_method(item.fset)): if (item.fset.func_name == item_name): (yield TypedFunction(item.fset, False, None, item_name)) continue else: continue if self.is_typed_method(function): (yield TypedFunction(function, is_static))
'TODO - Currently "t = clr.GetPythonType(clr.GetClrType(C)); t == C" will be False for C where C.__metaclass__ is ClrInterface, even though both t and C represent the same CLR type. This can be fixed by publishing a mapping between t and C in the IronPython runtime.'
def map_clr_type(self, clr_type):
pass
'Rotation around the X axis'
def Pitch(self, p):
self.RotationMatrix *= DirectX.Matrix.RotationX(p)
'Rotation around the Y axis'
def Yaw(self, y):
self.RotationMatrix *= DirectX.Matrix.RotationY(y)
'Rotation around the Z axis'
def Roll(self, r):
self.RotationMatrix *= DirectX.Matrix.RotationZ(r)
'Takes in a position to look at and an up vector to use to look at it with. The up vector will normally be the positive Y axis, but in the case where the position is directly above or below the position of the camera, you will need to set which direction up is in this case.'
def LookAt(self, position, up=DirectX.Vector3(0, 1, 0)):
zero = DirectX.Vector3(0, 0, 0) direction = (Vectorize(position) - self.Position) up = Vectorize(up) self.LookAtMatrix = DirectX.Matrix.LookAtLH(zero, direction, up) self.RotationMatrix = DirectX.Matrix.Identity
'Creates a basic object from the given paramters.'
def LoadBasicObject(self, type, name, color, *args):
mesh = BasicObject(self.Device, type, name, color, *args) self.Objects[mesh.Name] = mesh return mesh
'Loads a mesh and places it into an object based on the filename.'
def LoadMesh(self, name, filename):
mesh = MeshRenderable(self.Device, name, filename) self.Objects[mesh.Name] = mesh return mesh
'Creates a Camera with the given name.'
def CreateCamera(self, name):
cam = Camera(name) self.Objects[cam.Name] = cam if (self.ActiveCamera is None): self.ActiveCamera = cam return cam
'Creates the Direct3D device which is used to render the scene. Pops up a message box and returns False on failure (returns True on success).'
def InitGraphics(self, handle):
params = Direct3D.PresentParameters() params.Windowed = True params.SwapEffect = Direct3D.SwapEffect.Discard params.EnableAutoDepthStencil = True params.AutoDepthStencilFormat = Direct3D.DepthFormat.D16 self.Device = Direct3D.Device(0, Direct3D.DeviceType.Hardware, handle, Direct3D.CreateFlags.SoftwareVertexProcessing, params) self.Device.RenderState.ZBufferEnable = True self.Device.Transform.Projection = DirectX.Matrix.PerspectiveFovLH((System.Math.PI / 4.0), 1, 1, 100) self.Device.Transform.View = DirectX.Matrix.LookAtLH(DirectX.Vector3(0, 3, (-5)), DirectX.Vector3(0, 0, 0), DirectX.Vector3(0, 1, 0)) self.Device.RenderState.Ambient = Drawing.Color.White self.Paused = False return True
'Takes in either a class or an instance of a class. If obj is a class then this removes all instances of that class from all events. If the obj parameter is an instance then it removes only that instance from all events it is registered for. If obj is a sequence type then RemoveListener will be recursively called with the contents of the list (do NOT pass recursive sequences to this function or you will end up with an infinite loop).'
def RemoveListener(self, obj):
if operator.isSequenceType(obj): for x in obj: self.RemoveListener(x) else: for key in self.Listeners.Keys: self.RemoveListenerByInstance(key, obj) key = str(key) if hasattr(obj, key): if (issubclass(type(obj), type) or (type(obj) == ClassType)): self.RemoveListenerByType(key, obj) else: f = getattr(obj, key) self.RemoveListenerByInstance(key, f)
'Registers an object for all listeners that it has functions for. If obj is an instance of a class, this will register that instance. If obj is a class, then this object will attempt to construct an instance of it (without any parameters to the constructor) and then register that instance (this throws an exception if the constructor required args). Finally if obj is a sequence type this function will recursively call itself with the contents of the sequence. Do not pass in a recursive list to this method.'
def AddListener(self, obj):
if operator.isSequenceType(obj): for x in obj: self.AddListener(x) else: if (issubclass(type(obj), type) or (type(obj) == ClassType)): obj = obj() for key in self.Listeners.Keys: if hasattr(obj, str(key)): function = getattr(obj, str(key)) self.AddEventListener(key, function)
'Runs the application, registering the list of listeners given by the listeners parameter. Listeners can be an instance of a Listener class, it could be a class object of a listener class (in which case an instance will be created by calling the constructor with no params), or it could be a list of either of those.'
def Main(self, listeners=[]):
if (not hasattr(self, 'Initialized')): self.Init() if (not self.SceneManager.InitGraphics(self.Window.Handle)): Forms.MessageBox.Show('Could not init Direct3D.') else: if (listeners is not None): self.SceneManager.AddListener(listeners) self.Window.Show() self.SceneManager.Go(self.Window)
'Starts main in a background thread.'
def ThreadMain(self, listeners=[]):
if (not hasattr(self, 'Initialized')): self.Init() args = (listeners,) thread.start_new_thread(self.Main, args)
'Sometimes remote output can become available after the prompt is printed locally.'
def EnsureInteractiveRemote(self, readError=True):
twoPlusTwoResult = self.ExecuteLine('2 + 2', readError) if ('4' == twoPlusTwoResult): return if ('' != twoPlusTwoResult): raise AssertionError, ('EnsureInteractive failed. 2+2 returned ' + twoPlusTwoResult) twoPlusTwoResult = self.EatToMarker('4\r\n') if ('4\r\n' != twoPlusTwoResult): raise AssertionError, ('EnsureInteractive failed. 2+2 returned ' + twoPlusTwoResult)
'Sometimes remote output can become available after the prompt is printed locally.'
def ExecuteLineRemote(self, line, expectedOutputLines=1):
result = self.ExecuteLine(line) if ('' != result): return result for i in xrange(expectedOutputLines): output = self.EatToMarker('\r\n') if (output == ''): raise AssertionError, ('ExecuteLineRemote failed. Returned empty after %s. Error is %s' % (result, self.ReadError())) result += output return result[0:(-2)]
'Create a PackageFinder. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packages when consulting the index and links.'
def __init__(self, find_links, index_urls, allow_all_prereleases=False, trusted_hosts=None, process_dependency_links=False, session=None, format_control=None):
if (session is None): raise TypeError("PackageFinder() missing 1 required keyword argument: 'session'") self.find_links = [] for link in find_links: if link.startswith('~'): new_link = normalize_path(link) if os.path.exists(new_link): link = new_link self.find_links.append(link) self.index_urls = index_urls self.dependency_links = [] self.logged_links = set() self.format_control = (format_control or FormatControl(set(), set())) self.secure_origins = [('*', host, '*') for host in (trusted_hosts if trusted_hosts else [])] self.allow_all_prereleases = allow_all_prereleases self.process_dependency_links = process_dependency_links self.session = session if (not HAS_TLS): for link in itertools.chain(self.index_urls, self.find_links): parsed = urllib_parse.urlparse(link) if (parsed.scheme == 'https'): logger.warning('pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.') break
'Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls)'
@staticmethod def _sort_locations(locations, expand_dir=False):
files = [] urls = [] def sort_path(path): url = path_to_url(path) if (mimetypes.guess_type(url, strict=False)[0] == 'text/html'): urls.append(url) else: files.append(url) for url in locations: is_local_path = os.path.exists(url) is_file_url = url.startswith('file:') if (is_local_path or is_file_url): if is_local_path: path = url else: path = url_to_path(url) if os.path.isdir(path): if expand_dir: path = os.path.realpath(path) for item in os.listdir(path): sort_path(os.path.join(path, item)) elif is_file_url: urls.append(url) elif os.path.isfile(path): sort_path(path) else: logger.warning("Url '%s' is ignored: it is neither a file nor a directory.", url) elif is_url(url): urls.append(url) else: logger.warning("Url '%s' is ignored. It is either a non-existing path or lacks a specific scheme.", url) return (files, urls)
'Function used to generate link sort key for link tuples. The greater the return value, the more preferred it is. If not finding wheels, then sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min() 3. source archives Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal'
def _candidate_sort_key(self, candidate):
support_num = len(supported_tags) if candidate.location.is_wheel: wheel = Wheel(candidate.location.filename) if (not wheel.supported()): raise UnsupportedWheel(("%s is not a supported wheel for this platform. It can't be sorted." % wheel.filename)) pri = (- wheel.support_index_min()) else: pri = (- support_num) return (candidate.version, pri)
'Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations'
def _get_index_urls_locations(self, project_name):
def mkurl_pypi_url(url): loc = posixpath.join(url, urllib_parse.quote(project_name.lower())) if (not loc.endswith('/')): loc = (loc + '/') return loc return [mkurl_pypi_url(url) for url in self.index_urls]
'Find all available InstallationCandidate for project_name This checks index_urls, find_links and dependency_links. All versions found are returned as an InstallationCandidate list. See _link_package_versions for details on which files are accepted'
def find_all_candidates(self, project_name):
index_locations = self._get_index_urls_locations(project_name) (index_file_loc, index_url_loc) = self._sort_locations(index_locations) (fl_file_loc, fl_url_loc) = self._sort_locations(self.find_links, expand_dir=True) (dep_file_loc, dep_url_loc) = self._sort_locations(self.dependency_links) file_locations = (Link(url) for url in itertools.chain(index_file_loc, fl_file_loc, dep_file_loc)) url_locations = [link for link in itertools.chain((Link(url) for url in index_url_loc), (Link(url) for url in fl_url_loc), (Link(url) for url in dep_url_loc)) if self._validate_secure_origin(logger, link)] logger.debug('%d location(s) to search for versions of %s:', len(url_locations), project_name) for location in url_locations: logger.debug('* %s', location) canonical_name = canonicalize_name(project_name) formats = fmt_ctl_formats(self.format_control, canonical_name) search = Search(project_name, canonical_name, formats) find_links_versions = self._package_versions((Link(url, '-f') for url in self.find_links), search) page_versions = [] for page in self._get_pages(url_locations, project_name): logger.debug('Analyzing links from page %s', page.url) with indent_log(): page_versions.extend(self._package_versions(page.links, search)) dependency_versions = self._package_versions((Link(url) for url in self.dependency_links), search) if dependency_versions: logger.debug('dependency_links found: %s', ', '.join([version.location.url for version in dependency_versions])) file_versions = self._package_versions(file_locations, search) if file_versions: file_versions.sort(reverse=True) logger.debug('Local files found: %s', ', '.join([url_to_path(candidate.location.url) for candidate in file_versions])) return (((file_versions + find_links_versions) + page_versions) + dependency_versions)