def testMapRegion(self): """Verifies that the 'region' property affects the Maps API URL.""" m1 = test_utils.CreateMap({'title': 'no region'}) m2 = test_utils.CreateMap({'title': 'has region', 'region': 'in'}) with test_utils.RootLogin(): cm_config = maps.GetConfig( test_utils.SetupRequest('/.maps/' + m1.id), m1) self.assertTrue('region=' not in cm_config['maps_api_url']) cm_config = maps.GetConfig( test_utils.SetupRequest('/.maps/' + m2.id), m2) self.assertTrue('region=in' in cm_config['maps_api_url'])
def testWipe(self): map_object = test_utils.CreateMap() map_id = map_object.id with test_utils.RootLogin(): self.DoPost('/.admin/' + map_id, 'wipe=1&xsrf_token=XSRF') self.assertEquals(None, model.Map.Get(map_id)) self.assertEquals(None, model.Map.GetDeleted(map_id))
def testGet(self): map_object = test_utils.CreateMap() map_id = map_object.id with test_utils.RootLogin(): response = self.DoGet('/.admin/' + map_id) self.assertTrue('xyz.com' in response.body) self.assertTrue('title' in response.body)
def testMapIdInConfig_DraftMap(self): """Verifies the map ID is added to the map_root always.""" with test_utils.RootLogin(): my_map = test_utils.CreateMap() cfg = maps.GetConfig( test_utils.SetupRequest('/.maps/' + my_map.id), my_map) self.assertEqual(my_map.id, cfg['map_root']['id'])
def testDelete(self): map_object = test_utils.CreateMap() map_id = map_object.id with test_utils.RootLogin(): self.DoPost('/.admin/' + map_id, 'delete=1&xsrf_token=XSRF') self.assertTrue(model.Map.GetDeleted(map_id).is_deleted) self.DoPost('/.admin/' + map_id, 'undelete=1&xsrf_token=XSRF') self.assertFalse(model.Map.Get(map_id).is_deleted)
def testMapIdInConfig_PublishedMap(self): with test_utils.RootLogin(): my_map = test_utils.CreateMap() my_entry = model.CatalogEntry.Create(test_utils.PRIMARY_DOMAIN, 'label', my_map) cfg = maps.GetConfig(test_utils.SetupRequest( '/a/%s/label' % test_utils.PRIMARY_DOMAIN), catalog_entry=my_entry) self.assertEqual(my_map.id, cfg['map_root']['id'])
def testCheckAccessRaisesOnBadTarget(self): m = test_utils.CreateMap() # Roles that require a domain as the target for role in (perms.Role.CATALOG_EDITOR, perms.Role.MAP_CREATOR): # Test both no target and a target of the wrong class self.assertRaises(TypeError, perms.CheckAccess, role) self.assertRaises(TypeError, perms.CheckAccess, role, target=m) # Roles that require a map as a target for role in (perms.Role.MAP_OWNER, perms.Role.MAP_EDITOR, perms.Role.MAP_REVIEWER, perms.Role.MAP_VIEWER): # Test both no target and a target of the wrong class self.assertRaises(TypeError, perms.CheckAccess, role) self.assertRaises(TypeError, perms.CheckAccess, role, target='xyz.com')
def setUp(self): super(MapReviewTest, self).setUp() map_root = { 'id': 'map1', 'title': 'Map 1', 'layers': [{ 'id': '1', 'title': 'Emergency shelters', 'type': 'KML' }], 'topics': [{ 'id': 'shelter', 'title': 'Shelter', 'layer_ids': ['1'], 'crowd_enabled': True, 'cluster_radius': 456, 'questions': [{ 'id': 'q1', 'text': 'Is there space available?<br>', 'type': 'CHOICE', 'choices': [{ 'id': 'y', 'title': 'Yes', 'label': '[space]' }, { 'id': 'n', 'title': 'No', 'label': '[no space]' }] }, { 'id': 'q2', 'text': 'Are overnight stays allowed?', 'type': 'CHOICE', 'choices': [{ 'id': 'y', 'title': 'Yes', 'label': '[overnight]' }, { 'id': 'n', 'title': 'No', 'label': '[day only]' }] }, { 'id': 'q3', 'text': 'How many beds are open?', 'title': 'Beds', 'type': 'NUMBER' }, { 'id': 'q4', 'text': 'What is the phone number?', 'title': 'Phone', 'type': 'STRING' }] }, { 'id': 'water', 'title': 'Water', 'layer_ids': ['2'], 'crowd_enabled': True, 'cluster_radius': 123, 'questions': [{ 'id': 'q5', 'text': 'Is there water?', 'type': 'CHOICE', 'choices': [{ 'id': 'y', 'title': 'Yes', 'label': '[water]' }, { 'id': 'n', 'title': 'No', 'label': '[no water]' }] }] }, { 'id': 'flooding', 'title': 'Flooding', 'layer_ids': ['3', '4'], 'crowd_enabled': True, 'cluster_radius': 987, }] } self.map_object = test_utils.CreateMap(map_root, reviewers=['reviewer']) self.map_id = self.map_object.id self.topic1_id = '%s.shelter' % self.map_id self.q1_id = '%s.shelter.q1' % self.map_id self.q2_id = '%s.shelter.q2' % self.map_id self.q3_id = '%s.shelter.q3' % self.map_id self.q4_id = '%s.shelter.q4' % self.map_id self.SetTime(1300000000) self.cr1 = test_utils.NewCrowdReport(text='26 beds here', topic_ids=[self.topic1_id], answers={ self.q1_id: 'y', self.q3_id: 26, self.q4_id: '555-1234' }) self.topic2_id = '%s.water' % self.map_id self.q5_id = '%s.water.q5' % self.map_id self.SetTime(1300000001) self.cr2 = test_utils.NewCrowdReport( author='http://foo.com/abc', text='bottled water here </script>', topic_ids=[self.topic2_id], answers={self.q5_id: 'n'})
def testNotSignedIn(self): m = test_utils.CreateMap() self.assertFalse(perms.CheckAccess(perms.Role.MAP_EDITOR, target=m))
def testPublishedMaps(self): map1 = { 'title': 'Map 1', 'layers': [{ 'id': 12, 'type': 'KML', 'source': { 'kml': { 'url': 'x.com/a.kml' } } }, { 'id': 15, 'type': 'GEORSS', 'source': { 'georss': { 'url': 'y.com/b.xml' } } }] } map2 = { 'title': 'Map 2', 'layers': [{ 'id': 13, 'type': 'KML', 'source': { 'kml': { 'url': 'a.com/y.kml' } } }, { 'id': 17, 'type': 'GEORSS', 'source': { 'georss': { 'url': 'b.com/x.xml' } } }] } draft = { 'title': 'Map 2', 'layers': [{ 'id': 13, 'type': 'KML', 'source': { 'kml': { 'url': 'a.com/y.kml' } } }, { 'id': 17, 'type': 'GEORSS', 'source': { 'georss': { 'url': 'b.com/x.xml' } } }] } # Create and publish two maps with test_utils.RootLogin(): m1 = test_utils.CreateMap(map1) model.CatalogEntry.Create('xyz.com', 'label1', m1) m2 = test_utils.CreateMap(map2) model.CatalogEntry.Create('xyz.com', 'label2', m2) # Create a draft; should not be returned by api.Maps test_utils.CreateMap(draft) response = self.DoGet('/.api/maps') map1['id'] = m1.id # storing the map should have set its 'id' property map2['id'] = m2.id # storing the map should have set its 'id' property self.assertEquals([{ 'url': '/root/xyz.com/label2', 'map_root': map2 }, { 'url': '/root/xyz.com/label1', 'map_root': map1 }], json.loads(response.body))
def testPostJson(self): owner_login = test_utils.Login('map_owner') map_object = test_utils.CreateMap(owners=['map_owner']) map_id = map_object.id topic_id = map_id + '.gas' key = model.Authorization.Create(crowd_report_write_permission=True, source='http://client.com/', author_prefix='tel:+1', map_ids=[map_id]).id fields = { 'id': 'http://client.com/1', 'source': 'http://client.com/', 'author': 'tel:+15551234567', 'map_id': map_id, 'topic_ids': [topic_id], 'answers': { topic_id + '.1': 'yes' }, 'location': [37, -75], 'place_id': 'a.b.c', 'text': 'Hello' } config.Set('crowd_report_spam_phrases', ['rabbits']) report_dicts = [ dict(fields), # all valid dict(fields, id='http://elsewhere.com/1'), # ID not ok for source dict(fields, source='http://other.com/'), # unauthorized source dict(fields, author='tel:+445551234567'), # unauthorized author dict(fields, map_id='xyz'), # unauthorized map_id dict(fields, topic_ids=3.7), # topic_ids is not a list dict(fields, answers='what'), # answers is not a dictionary dict(fields, text=[3, 4]), # text is not a string dict(fields, place_id=9), # place_id is not a string dict(fields, location='a'), # location is not a list of two numbers dict(fields, text='Rabbits are bad!') # contains spam phrase ] # Shouldn't be allowed without the key. self.DoPost('/.api/reports', json.dumps(report_dicts), 403, content_type='application/json', https=True) # Shouldn't be allowed over HTTP. self.DoPost('/.api/reports?key=' + key, json.dumps(report_dicts), 403, content_type='application/json', https=False) # Should post successfully over HTTPS with the key. response = self.DoPost('/.api/reports?key=' + key, json.dumps(report_dicts), content_type='application/json', https=True) reports = json.loads(response.body) self.assertEquals(len(report_dicts), len(reports)) self.assertEquals('Hello', reports[0]['text']) for report_dict, result in zip(report_dicts, reports)[1:]: self.assertTrue( 'error' in result, 'Submitted %r expecting an error, ' 'but instead got %r' % (report_dict, result)) # When not signed in, a search query should fetch nothing. response = self.DoGet( '/.api/reports?ll=37,-75&topic_ids=1.gas&radii=100') reports = json.loads(response.body) self.assertEquals(0, len(reports)) # When signed in with view access to the map, we should get the report. with owner_login: response = self.DoGet( '/.api/reports?ll=37,-75&topic_ids=%s&radii=100' % topic_id) reports = json.loads(response.body) self.assertEquals(1, len(reports)) expected = report_dicts[0] self.assertEquals(expected['source'], reports[0]['source']) self.assertEquals(expected['author'], reports[0]['author']) self.assertEquals(expected['text'], reports[0]['text']) self.assertEquals(expected['topic_ids'], reports[0]['topic_ids']) self.assertEquals(expected['answers'], reports[0]['answers']) self.assertEquals(expected['location'], reports[0]['location']) self.assertEquals(expected['place_id'], reports[0]['place_id'])
def setUp(self): super(MapByIdTest, self).setUp() self.map = test_utils.CreateMap(owners=['owner'], editors=['editor'], viewers=['viewer'])
def setUp(self): super(PublishTest, self).setUp() perms.Grant('owner', perms.Role.CATALOG_EDITOR, 'xyz.com') self.map_object = test_utils.CreateMap(owners=['owner']) self.map_id = self.map_object.id
def testWipeNotAllowed(self): map_object = test_utils.CreateMap() map_id = map_object.id with test_utils.Login('unprivileged'): self.DoPost('/.admin/' + map_id, 'wipe=1&xsrf_token=XSRF', 403)
def testUserRoles(self): # pylint: disable=too-many-statements """Verifies that access permissions restrict user actions correctly.""" m = test_utils.CreateMap(owners=['owner'], editors=['editor'], reviewers=['reviewer'], viewers=['viewer']) with test_utils.RootLogin(): # An admin should have all map roles. self.assertEquals(set(perms.MAP_ROLES), GetRolesForMap(m)) # Verify an admin can perform all operations. model.Map.Get(m.id) version_id = m.PutNewVersion({}) m.SetWorldReadable(False) m.GetVersions() m.GetVersion(version_id) with test_utils.Login('owner'): # An owner should have all roles. self.assertEquals(set(perms.MAP_ROLES), GetRolesForMap(m)) # Verify the owner can perform expected operations. self.assertRaises(perms.AuthorizationError, model.Map.Create, {}, 'xyz.com') model.Map.Get(m.id) version_id = m.PutNewVersion({}) m.SetWorldReadable(False) m.GetVersions() m.GetVersion(version_id) with test_utils.Login('editor'): # Check editor roles. self.assertEquals({'MAP_EDITOR', 'MAP_REVIEWER', 'MAP_VIEWER'}, GetRolesForMap(m)) # Verify the editor can perform expected operations. self.assertRaises(perms.AuthorizationError, model.Map.Create, {}, 'xyz.com') model.Map.Get(m.id) version_id = m.PutNewVersion({}) self.assertRaises(perms.AuthorizationError, m.SetWorldReadable, False) m.GetVersions() m.GetVersion(version_id) with test_utils.Login('reviewer'): # Check reviewer roles. self.assertEquals({'MAP_REVIEWER', 'MAP_VIEWER'}, GetRolesForMap(m)) # Verify the reviewer can perform expected operations. self.assertRaises(perms.AuthorizationError, model.Map.Create, {}, 'xyz.com') model.Map.Get(m.id) self.assertRaises(perms.AuthorizationError, m.PutNewVersion, {}) self.assertRaises(perms.AuthorizationError, m.GetVersion, version_id) self.assertRaises(perms.AuthorizationError, m.GetVersions) with test_utils.Login('viewer'): # Check viewer roles. self.assertEquals({'MAP_VIEWER'}, GetRolesForMap(m)) # Verify the viewer can perform expected operations. self.assertRaises(perms.AuthorizationError, model.Map.Create, {}, 'xyz.com') model.Map.Get(m.id) self.assertRaises(perms.AuthorizationError, m.PutNewVersion, {}) self.assertRaises(perms.AuthorizationError, m.GetVersion, version_id) self.assertRaises(perms.AuthorizationError, m.GetVersions) with test_utils.Login('outsider'): # Check roles for an unknown user. self.assertEquals(set(), GetRolesForMap(m)) # Verify that all operations fail. self.assertRaises(perms.AuthorizationError, model.Map.Get, m.id) self.assertRaises(perms.AuthorizationError, m.PutNewVersion, {}) self.assertRaises(perms.AuthorizationError, m.GetVersions) self.assertRaises(perms.AuthorizationError, m.GetVersion, version_id) # Check roles for an unknown user on a world-readable map. m.model.world_readable = True self.assertEquals({'MAP_VIEWER'}, GetRolesForMap(m)) # Verify the user can perform only the expected operations. self.assertRaises(perms.AuthorizationError, model.Map.Create, {}, 'xyz.com') self.assertRaises(perms.AuthorizationError, m.PutNewVersion, {}) self.assertRaises(perms.AuthorizationError, m.SetWorldReadable, True) self.assertRaises(perms.AuthorizationError, m.GetVersion, version_id) self.assertRaises(perms.AuthorizationError, m.GetVersions)
def testSystem(self): """Tests map, metadata_fetch, and metadata, all working together.""" self.SetTime(FETCH_TIME) map_object = test_utils.CreateMap( { 'layers': [{ 'type': 'KML', 'source': { 'kml': { 'url': SOURCE_URL } } }, { 'type': 'GEORSS', 'source': { 'georss': { 'url': GEORSS_URL } } }] }, 'xyz.com', owners=['owner']) # Simulate the first map load. with test_utils.Login('owner'): response = self.DoGet('/xyz.com/.maps/' + map_object.id) # Get the metadata cache key mentioned in the map page. cache_key = re.search(r'"metadata_url": "/root/.metadata\?ck=(\w+)"', response.body).group(1) # The map load should have queued two metadata_fetch tasks. tasks = sorted(self.PopTasks('metadata')) self.assertEqual(2, len(tasks)) self.assertTrue(tasks[0]['url'].startswith('/root/.metadata_fetch')) self.assertTrue(tasks[1]['url'].startswith('/root/.metadata_fetch')) # Loading the map again should not queue redundant tasks. with test_utils.Login('owner'): self.DoGet('/xyz.com/.maps/' + map_object.id) self.assertEqual(0, len(self.PopTasks('metadata'))) # Execute the queued metadata_fetch tasks. self.mox.StubOutWithMock(urlfetch, 'fetch') urlfetch.fetch(GEORSS_URL, headers={}, deadline=30).AndReturn( utils.Struct(status_code=200, headers=RESPONSE_HEADERS, content=SIMPLE_GEORSS)) urlfetch.fetch(SOURCE_URL, headers={}, deadline=30).AndReturn( utils.Struct(status_code=200, headers=RESPONSE_HEADERS_2, content=SIMPLE_KML)) self.mox.ReplayAll() self.ExecuteTask(tasks[0]) self.SetTime(FETCH_TIME_2) self.ExecuteTask(tasks[1]) self.mox.VerifyAll() # metadata.py should now return the cached metadata. response = self.DoGet('/.metadata?ck=' + cache_key) self.assertEquals( { 'GEORSS:' + GEORSS_URL: { 'fetch_time': FETCH_TIME, 'fetch_status': 200, 'fetch_length': len(SIMPLE_GEORSS), 'fetch_last_modified': LAST_MODIFIED_STRING, 'fetch_etag': ETAG, 'update_time': LAST_MODIFIED_TIMESTAMP, 'length': len(SIMPLE_GEORSS), 'md5_hash': hashlib.md5(SIMPLE_GEORSS).hexdigest() }, 'KML:' + SOURCE_URL: { 'fetch_time': FETCH_TIME_2, 'fetch_status': 200, 'fetch_length': len(SIMPLE_KML), 'fetch_last_modified': LAST_MODIFIED_STRING_2, 'fetch_etag': ETAG_2, 'update_time': LAST_MODIFIED_TIMESTAMP_2, 'length': len(SIMPLE_KML), 'md5_hash': hashlib.md5(SIMPLE_KML).hexdigest() } }, json.loads(response.body))
def setUp(self): super(CardHandlerTest, self).setUp() map_object = test_utils.CreateMap(MAP_ROOT) self.map_id = map_object.id with test_utils.RootLogin(): model.CatalogEntry.Create('xyz.com', 'foo', map_object)