def setUp(self): self.mox = mox.Mox() self.testbed = testbed.Testbed() self.testbed.activate() root = os.path.dirname(__file__) or '.' self.testbed.init_datastore_v3_stub(require_indexes=True, root_path=root) self.testbed.init_taskqueue_stub(root_path=root) # Register memcache stub with a custom gettime function, so we can control # time in memcache through self.SetTime(..) # pylint: disable=unnecessary-lambda apiproxy_stub_map.apiproxy.RegisterStub( 'memcache', memcache_stub.MemcacheServiceStub(lambda: time.time())) # pylint: enable=unnecessary-lambda self.testbed.init_urlfetch_stub() self.testbed.init_user_stub() self.testbed.init_search_stub() self.original_datetime = datetime.datetime os.environ.pop('USER_EMAIL', None) os.environ.pop('USER_ID', None) os.environ.pop('USER_IS_ADMIN', None) os.environ.pop('USER_ORGANIZATION', None) config.Set('root_path', ROOT_PATH) config.Set('primary_domain', PRIMARY_DOMAIN) domains.Domain.Put(PRIMARY_DOMAIN) self.mox.stubs.Set(base_handler, 'GenerateXsrfToken', lambda uid, timestamp=None: 'XSRF') self.mox.stubs.Set(base_handler, 'ValidateXsrfToken', lambda uid, token: token == 'XSRF') self.id_counter = 0 self.mox.stubs.Set(utils, 'MakeRandomId', self.MakePredictableId) self.cookie_jar = None
def testConfig(self): """Tests storage of simple and structured values in Config entities.""" self.assertEquals(None, config.Get('k')) config.Set('k', 'value') self.assertEquals('value', config.Get('k')) config.Set('j', False) self.assertEquals({'k': 'value', 'j': False}, config.GetAll()) config.Set('k', [3, 4, {'a': 'b'}, None]) self.assertEquals([3, 4, {'a': 'b'}, None], config.Get('k')) config.Delete('k') self.assertEquals(None, config.Get('k'))
def get(self): # pylint: disable=g-bad-name """This endpoint is only for setting up data for system tests.""" _CheckIsDevServer() # For system tests, we pretend the app runs under "/crisismap". config.Set('root_path', '/crisismap') # Because there is no user logged in during system testing, we can't use # the usual access-controlled API (Map, CatalogEntry); we have to use # admin-level APIs (Config, MapModel, CatalogEntryModel, etc.) below. # Allow testing of behaviour controlled by flags in the ClientConfig. maps.ClientConfig.Create( 'google-test', allowed_referer_domains=['google.com'], urlshortener_api_url=('http://' + self.request.host + '/testbackend?service=urlshortener'), hide_footer=True, hide_share_button=False, hide_my_location_button=True, allow_embed_map_callback=True).put() # Allow tests of the tabbed UI. maps.ClientConfig.Create('google-test-tab', allowed_referer_domains=['google.com'], use_tab_panel=True).put() # Add the godzilla test map to the datastore with map ID '1'. self.PutTestMap('1', 'godzilla.json') # Add the test_maproot test map to the datastore with map ID '2' self.PutTestMap('2', 'test_maproot.json') # Add the gas_stations (with crowd reports) test map with map ID '3'. self.PutTestMap('3', 'gas_stations.json') # Add sharks test map with map ID '10'. sharks_maproot = _GetSharksMaproot(self.request.host) self.PutTestMapJson('10', sharks_maproot, json.dumps(sharks_maproot)) # Add catalog entries for some of the test maps config.Set('primary_domain', 'gmail.com') model.CatalogEntryModel.Put( 'test1', 'gmail.com', 'godzilla', model.Map.Get('1'), is_listed=True) model.CatalogEntryModel.Put( 'test1', 'gmail.com', 'gas-stations', model.Map.Get('3'), is_listed=True) model.CatalogEntryModel.Put( 'test1', 'gmail.com', 'sharks', model.Map.Get('10'), is_listed=True) model.CatalogEntry.FlushCaches('gmail.com') self.response.out.write('Test data written.')
def AssertGetFeaturesFromPlacesLayer(self, api_response_content, expected_results): """Verifies GetFeaturesFromPlacesLayer with given input and output. Prepares a mock for urlfetch to return given api_response_content on a call to the Places API. Verifies that GetJsonFromGooglePlacesApi returns expected_results given the urlfetch mock setup. Args: api_response_content: Content that urlfetch should return expected_results: an array of Places results that GetJsonFromGooglePlacesApi should return """ config.Set('google_api_server_key', 'someFakeApiKey') # Simulate a successful fetch from Places API by setting up a fake # for urlfetch url = ('https://maps.googleapis.com/maps/api/place/nearbysearch/json?' 'location=20.0%2C50.0' '&rankby=distance' '&types=pharmacy' '&key=someFakeApiKey') url_responses = {url: utils.Struct(content=api_response_content)} self.mox.stubs.Set(urlfetch, 'fetch', lambda url, **kwargs: url_responses[url]) # Get Features based on Google Places API results for the layer self.assertEquals( expected_results, card.GetFeaturesFromPlacesLayer( MAP_ROOT.get('layers')[3], ndb.GeoPt(20, 50))) self.mox.UnsetStubs()
def testUpdateMetadataWithZeroBandwidth(self): # FetchAndUpdateMetadata should not be called config.Set('metadata_max_megabytes_per_day_per_source', 0) metadata_fetch.FetchAndUpdateMetadata = lambda *args: self.fail() self.SetTime(1234567890) metadata_fetch.METADATA_CACHE.Set(SOURCE_ADDRESS, METADATA) metadata_fetch.UpdateMetadata(SOURCE_ADDRESS)
def get(self): # pylint: disable=g-bad-name """This endpoint is only for setting up data for system tests.""" if not users.IsDeveloper(): self.response.out.write('Not authorized.') return # For system tests, we pretend the app runs under "/crisismap". config.Set('root_path', '/crisismap') # Because there is no user logged in during system testing, we can't use # the usual access-controlled API (Map, CatalogEntry); we have to use # admin-level APIs (Config, MapModel, CatalogEntryModel, etc.) below. # Allow testing of behaviour controlled by flags in the ClientConfig. maps.ClientConfig.Create('google-test', allowed_referer_domains=['google.com'], hide_footer=True, hide_share_button=True, hide_my_location_button=True, allow_embed_map_callback=True).put() # Allow tests of the tabbed UI. maps.ClientConfig.Create('google-test-tab', allowed_referer_domains=['google.com'], use_tab_panel=True).put() # Add the godzilla test map to the datastore with map ID '1'. self.PutTestMap('1', 'godzilla.json') # Add the test_maproot test map to the datastore with map ID '2' self.PutTestMap('2', 'test_maproot.json') # Add the gas_stations (with crowd reports) test map with map ID '3'. self.PutTestMap('3', 'gas_stations.json') # Add a catalog entry with label 'godzilla' pointing at our test map. config.Set('primary_domain', 'gmail.com') model.CatalogEntryModel.Put('test1', 'gmail.com', 'godzilla', model.Map.Get('1'), is_listed=True) model.CatalogEntry.FlushCaches('gmail.com') self.response.out.write('Test data written.')
def testLoginAccessList(self): """Ensures that the login_access_list config setting is enforced.""" config.Set('login_access_list', ['*****@*****.**', '*****@*****.**']) _, response = self.RunTestHandler('GET', '/test', 302) self.assertRegexpMatches(response.headers['Location'], r'/\.login') with test_utils.Login('1'): _, response = self.RunTestHandler('GET', '/test', 200) self.assertEquals('test', response.body) with test_utils.Login('7'): _, response = self.RunTestHandler('GET', '/test', 403) self.assertTrue("you don't have permission" in response.body)
def testSpammyReport(self): config.Set('crowd_report_spam_phrases', ['rabbits', 'fluffy cats']) self.DoPost('/.api/reports', { 'cm-ll': '10,10', 'cm-topic-ids': 'foo', 'cm-text': 'no spam words' }) # Verify case-insensitive match for a single word. self.DoPost('/.api/reports', { 'cm-ll': '20,20', 'cm-topic-ids': 'foo', 'cm-text': 'i love Rabbits' }, status=403) # Verify case-insensitive match for a phrase. self.DoPost( '/.api/reports', { 'cm-ll': '10,10', 'cm-topic-ids': 'foo', 'cm-text': 'i love cats' # okay }) self.DoPost( '/.api/reports', { 'cm-ll': '20,20', 'cm-topic-ids': 'foo', 'cm-text': 'what FLUFFY cats' # matches a spam phrase }, status=403) # Confirm that none of the spammy reports were stored. response = self.DoGet( '/.api/reports?ll=20,20&topic_ids=foo&radii=1000') self.assertEquals([], json.loads(response.body)) # Confirm that the non-spammy reports were all stored. response = self.DoGet( '/.api/reports?ll=10,10&topic_ids=foo&radii=1000') self.assertEquals(2, len(json.loads(response.body)))
def testSetDetailsOnFilteredFeatures(self): config.Set('google_api_server_key', 'someFakeApiKey') # Simulate a successful fetch from Places API by setting up a fake urlfetch url_responses = {} helsinki_attrs = ['Listing by <a href="fakeurl1.com">FakeSite1</a>'] api_response_content = json.dumps({ 'status': 'OK', 'html_attributions': helsinki_attrs, 'result': { 'formatted_address': 'Street1', 'formatted_phone_number': '111-111-1111' } }) url = card.PLACES_API_DETAILS_URL + 'placeid=placeId1&key=someFakeApiKey' url_responses[url] = utils.Struct(content=api_response_content) columbus_attrs = ['Listing by <a href="fakeurl2.com">FakeSite2</a>'] api_response_content = json.dumps({ 'status': 'OK', 'html_attributions': columbus_attrs, 'result': { 'formatted_address': 'Street2', 'formatted_phone_number': '222-222-2222' } }) url = card.PLACES_API_DETAILS_URL + 'placeid=placeId2&key=someFakeApiKey' url_responses[url] = utils.Struct(content=api_response_content) self.mox.stubs.Set(urlfetch, 'fetch', lambda url, **kwargs: url_responses[url]) exp_features = [ ('Helsinki', '<div>Street1</div><div>111-111-1111</div>', helsinki_attrs), ('Columbus', '<div>Street2</div><div>222-222-2222</div>', columbus_attrs) ] features = PLACES_FEATURES[:] card.SetDetailsOnFilteredFeatures(features) self.assertEquals(exp_features, [(f.name, f.description_html, f.html_attrs) for f in features])
def setUp(self): test_utils.BaseTest.setUp(self) config.Set('primary_domain', 'primary.com')
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'])