def test_good_configuration_dynamic_scaling(self): automatic_scaling = appinfo.AutomaticScaling( min_pending_latency='1.0s', max_pending_latency='2.0s', min_idle_instances=1, max_idle_instances=2) error_handlers = [appinfo.ErrorHandlers(file='error.html')] handlers = [appinfo.URLMap()] env_variables = appinfo.EnvironmentVariables() info = appinfo.AppInfoExternal( application='app', module='module1', version='1', runtime='python27', threadsafe=False, automatic_scaling=automatic_scaling, skip_files=r'\*.gif', error_handlers=error_handlers, handlers=handlers, inbound_services=['warmup'], env_variables=env_variables, ) backend_entry = backendinfo.BackendEntry(name='dynamic', instances='3', options='public, dynamic', start='handler') application_configuration.ModuleConfiguration._parse_configuration( '/appdir/app.yaml').AndReturn((info, [])) os.path.getmtime('/appdir/app.yaml').AndReturn(10) self.mox.ReplayAll() module_config = application_configuration.ModuleConfiguration( '/appdir/app.yaml') config = application_configuration.BackendConfiguration( module_config, None, backend_entry) self.mox.VerifyAll() self.assertEqual(os.path.realpath('/appdir'), config.application_root) self.assertEqual('app', config.application) self.assertEqual('dynamic', config.module_name) self.assertEqual('1', config.major_version) self.assertRegexpMatches(config.version_id, r'dynamic:1\.\d+') self.assertEqual('python27', config.runtime) self.assertFalse(config.threadsafe) self.assertEqual(None, config.automatic_scaling) self.assertEqual(None, config.manual_scaling) self.assertEqual(appinfo.BasicScaling(max_instances='3'), config.basic_scaling) self.assertEqual(info.GetNormalizedLibraries(), config.normalized_libraries) self.assertEqual(r'\*.gif', config.skip_files) self.assertEqual(error_handlers, config.error_handlers) start_handler = appinfo.URLMap(url='/_ah/start', script=backend_entry.start, login='******') self.assertEqual([start_handler] + handlers, config.handlers) self.assertEqual(['warmup'], config.inbound_services) self.assertEqual(env_variables, config.env_variables)
def setUp(self): self.mox = mox.Mox() self.tmpdir = tempfile.mkdtemp() module_configuration = ModuleConfigurationStub( application_root=self.tmpdir, error_handlers=[ appinfo.ErrorHandlers(error_code='over_quota', file='foo.html'), appinfo.ErrorHandlers(error_code='default', file='error.html'), ]) self.runtime_config = runtime_config_pb2.Config() self.runtime_config.app_id = 'app' self.runtime_config.version_id = 'version' self.runtime_config.api_port = 12345 self.runtime_config.application_root = self.tmpdir self.runtime_config.datacenter = 'us1' self.runtime_config.instance_id = 'abc3dzac4' self.runtime_config.auth_domain = 'gmail.com' self.runtime_config_getter = lambda: self.runtime_config self.proxy = http_runtime.HttpRuntimeProxy(['/runtime'], self.runtime_config_getter, module_configuration, env={'foo': 'bar'}) self.process = self.mox.CreateMock(subprocess.Popen) self.process.stdin = self.mox.CreateMockAnything() self.process.stdout = self.mox.CreateMockAnything() self.mox.StubOutWithMock(safe_subprocess, 'start_process') self.mox.StubOutWithMock(httplib.HTTPConnection, 'connect') self.mox.StubOutWithMock(httplib.HTTPConnection, 'request') self.mox.StubOutWithMock(httplib.HTTPConnection, 'getresponse') self.mox.StubOutWithMock(httplib.HTTPConnection, 'close') self.mox.StubOutWithMock(login, 'get_user_info') self.mox.StubOutWithMock(shutdown, 'async_quit') self.url_map = appinfo.URLMap(url=r'/(get|post).*', script=r'\1.py')
def setUp(self): self.mox = mox.Mox() self.tmpdir = tempfile.mkdtemp() module_configuration = ModuleConfigurationStub( application_root=self.tmpdir) self.runtime_config = runtime_config_pb2.Config() self.runtime_config.app_id = 'app' self.runtime_config.version_id = 'version' self.runtime_config.api_port = 12345 self.runtime_config.application_root = self.tmpdir self.runtime_config.datacenter = 'us1' self.runtime_config.instance_id = 'abc3dzac4' self.runtime_config.auth_domain = 'gmail.com' self.runtime_config_getter = lambda: self.runtime_config self.proxy = http_runtime.HttpRuntimeProxy( ['/runtime'], self.runtime_config_getter, module_configuration, env={'foo': 'bar'}, start_process_flavor=http_runtime.START_PROCESS_REVERSE) self.mox.StubOutWithMock(self.proxy, '_process_lock') self.process = self.mox.CreateMock(subprocess.Popen) self.process.stdin = self.mox.CreateMockAnything() self.mox.StubOutWithMock(safe_subprocess, 'start_process_file') self.mox.StubOutWithMock(os, 'remove') self.mox.StubOutWithMock(time, 'sleep') self.url_map = appinfo.URLMap(url=r'/(get|post).*', script=r'\1.py') self.mox.StubOutWithMock(http_proxy.HttpProxy, 'wait_for_connection') self.mox.StubOutWithMock(portpicker, 'PickUnusedPort') http_proxy.HttpProxy.wait_for_connection(self.process)
def test_expiration_precedence(self): static_files_handler.Now = self.mox.CreateMockAnything() static_files_handler.Now().AndReturn(datetime.datetime(1990, 01, 01)) url_map = appinfo.URLMap(url='/', expiration='1d 2h 3m 4s', static_files='index.html') h = static_files_handler.StaticContentHandler( root_path=None, url_map=url_map, url_pattern='/$', app_info_default_expiration='2d 3h 4m 5s') os.path.getmtime('/home/appdir/index.html').AndReturn(12345.6) static_files_handler.StaticContentHandler._read_file( '/home/appdir/index.html').AndReturn('Hello World!') self.mox.ReplayAll() self.assertResponse( '200 OK', { 'Content-type': 'text/html', 'Content-length': '12', 'ETag': '"NDcyNDU2MzU1"', 'Expires': 'Tue, 02 Jan 1990 10:03:04 GMT', 'Cache-Control': 'public' }, 'Hello World!', h._handle_path, '/home/appdir/index.html', {'REQUEST_METHOD': 'GET'}) self.mox.VerifyAll() self.assertEqual( static_files_handler.StaticContentHandler. _filename_to_mtime_and_etag, {'/home/appdir/index.html': (12345.6, 'NDcyNDU2MzU1')})
def test_invalid_regex(self): url_map = appinfo.URLMap(url='((.*))(', static_files='index.html') self.assertRaises(errors.InvalidAppConfigError, static_files_handler.StaticDirHandler, root_path='/appdir', url_map=url_map)
def test_nonstandard_mimetype(self): url_map = appinfo.URLMap(url='/', static_files='simple.dart') h = static_files_handler.StaticContentHandler( root_path=None, url_map=url_map, url_pattern='/$') os.path.getmtime('/home/appdir/simple.dart').AndReturn(12345.6) static_files_handler.StaticContentHandler._read_file( '/home/appdir/simple.dart').AndReturn('void main() {}') self.mox.ReplayAll() self.assertResponse('200 OK', {'Content-type': 'application/dart', 'Content-length': '14', 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT', 'Cache-Control': 'public', 'ETag': '"LTE2OTA2MzYyMTM="'}, 'void main() {}', h._handle_path, '/home/appdir/simple.dart', {'REQUEST_METHOD': 'GET'}) self.mox.VerifyAll()
def test_cached_if_none_match_with_match(self): static_files_handler.StaticContentHandler._filename_to_mtime_and_etag = { '/home/appdir/index.html': (12345.6, 'match')} url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticContentHandler( root_path=None, url_map=url_map, url_pattern='/$') os.path.getmtime('/home/appdir/index.html').AndReturn(12345.6) self.mox.ReplayAll() self.assertResponse('304 Not Modified', {'ETag': '"match"'}, '', h._handle_path, '/home/appdir/index.html', {'REQUEST_METHOD': 'GET', 'HTTP_IF_NONE_MATCH': '"match"'}) self.mox.VerifyAll() self.assertEqual( static_files_handler.StaticContentHandler._filename_to_mtime_and_etag, {'/home/appdir/index.html': (12345.6, 'match')})
def test_if_match_no_file(self): url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticContentHandler( root_path=None, url_map=url_map, url_pattern='/$') error = IOError() error.errno = errno.ENOENT os.path.getmtime('/home/appdir/index.html').AndRaise(error) self.mox.ReplayAll() self.assertResponse('412 Precondition Failed', {}, '', h._handle_path, '/home/appdir/index.html', {'REQUEST_METHOD': 'GET', 'HTTP_IF_MATCH': '"nomatch"'}) self.mox.VerifyAll() self.assertEqual( static_files_handler.StaticContentHandler._filename_to_mtime_and_etag, {})
def test_if_match_without_match(self): url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticContentHandler( root_path=None, url_map=url_map, url_pattern='/$') os.path.getmtime('/home/appdir/index.html').AndReturn(12345.6) static_files_handler.StaticContentHandler._read_file( '/home/appdir/index.html').AndReturn('Hello World!') self.mox.ReplayAll() self.assertResponse('412 Precondition Failed', {'ETag': '"NDcyNDU2MzU1"'}, '', h._handle_path, '/home/appdir/index.html', {'REQUEST_METHOD': 'GET', 'HTTP_IF_MATCH': '"nomatch"'}) self.mox.VerifyAll() self.assertEqual( static_files_handler.StaticContentHandler._filename_to_mtime_and_etag, {'/home/appdir/index.html': (12345.6, 'NDcyNDU2MzU1')})
def test_cached_no_permission_read(self): static_files_handler.StaticContentHandler._filename_to_mtime_and_etag = { '/home/appdir/index.html': (12345.6, 'NDcyNDU2MzU1')} url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticContentHandler( root_path=None, url_map=url_map, url_pattern='/$') os.path.getmtime('/home/appdir/index.html').AndReturn(12345.6) error = IOError() error.errno = errno.EPERM static_files_handler.StaticContentHandler._read_file( '/home/appdir/index.html').AndRaise(error) self.mox.ReplayAll() self.assertResponse('403 Forbidden', {}, '', h._handle_path, '/home/appdir/index.html', {'REQUEST_METHOD': 'GET', 'PATH_INFO': '/'}) self.mox.VerifyAll()
def test_load_cached_file(self): static_files_handler.StaticContentHandler._filename_to_mtime_and_etag = { '/home/appdir/index.html': (12345.6, 'NDcyNDU2MzU1') } url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticContentHandler(root_path=None, url_map=url_map, url_pattern='/$') os.path.getmtime('/home/appdir/index.html').AndReturn(12345.6) static_files_handler.StaticContentHandler._read_file( '/home/appdir/index.html').AndReturn('Hello World!') self.mox.ReplayAll() self.assertResponse( '200 OK', { 'Content-type': 'text/html', 'Content-length': '12', 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT', 'Cache-Control': 'no-cache', 'ETag': '"NDcyNDU2MzU1"' }, 'Hello World!', h._handle_path, '/home/appdir/index.html', {'REQUEST_METHOD': 'GET'}) self.mox.VerifyAll() self.assertEqual( static_files_handler.StaticContentHandler. _filename_to_mtime_and_etag, {'/home/appdir/index.html': (12345.6, 'NDcyNDU2MzU1')})
def handlers(self): if self._backend_entry.start: return [appinfo.URLMap( url='/_ah/start', script=self._backend_entry.start, login='******')] + self._module_configuration.handlers return self._module_configuration.handlers
def test_check_for_mutable_changes(self): info1 = appinfo.AppInfoExternal( application='app', module='default', version='version', runtime='python27', threadsafe=False, libraries=[appinfo.Library(name='django', version='latest')], skip_files='.*', handlers=[], inbound_services=['warmup'], env_variables=appinfo.EnvironmentVariables(), error_handlers=[appinfo.ErrorHandlers(file='error.html')], ) info2 = appinfo.AppInfoExternal( application='app', module='default', version='version', runtime='python27', threadsafe=False, libraries=[appinfo.Library(name='jinja2', version='latest')], skip_files=r'.*\.py', handlers=[appinfo.URLMap()], inbound_services=[], ) application_configuration.ModuleConfiguration._parse_configuration( '/appdir/app.yaml').AndReturn((info1, [])) os.path.getmtime('/appdir/app.yaml').AndReturn(10) os.path.getmtime('/appdir/app.yaml').AndReturn(11) application_configuration.ModuleConfiguration._parse_configuration( '/appdir/app.yaml').AndReturn((info2, [])) os.path.getmtime('/appdir/app.yaml').AndReturn(11) self.mox.ReplayAll() config = application_configuration.ModuleConfiguration( '/appdir/app.yaml') self.assertSequenceEqual( set([ application_configuration.NORMALIZED_LIBRARIES_CHANGED, application_configuration.SKIP_FILES_CHANGED, application_configuration.HANDLERS_CHANGED, application_configuration.INBOUND_SERVICES_CHANGED, application_configuration.ENV_VARIABLES_CHANGED, application_configuration.ERROR_HANDLERS_CHANGED ]), config.check_for_updates()) self.mox.VerifyAll() self.assertEqual(info2.GetNormalizedLibraries(), config.normalized_libraries) self.assertEqual(info2.skip_files, config.skip_files) self.assertEqual(info2.error_handlers, config.error_handlers) self.assertEqual(info2.handlers, config.handlers) self.assertEqual(info2.inbound_services, config.inbound_services) self.assertEqual(info2.env_variables, config.env_variables)
def initURLMapping(conf, options): """Returns a list with mappings URL to module name and script.""" url_mapping = [] add_handlers = [ appinfo.URLMap(url=url, script=script) for url, script in [ # Configure script with login handler (options.login_url, '$PYTHON_LIB/typhoonae/handlers/login.py'), # Configure script with logout handler (options.logout_url, '$PYTHON_LIB/typhoonae/handlers/login.py'), # Configure script with images handler ('/_ah/img(?:/.*)?', '$PYTHON_LIB/typhoonae/handlers/images.py'), # Configure script with Channel JS API handler ('/_ah/channel/jsapi', '$PYTHON_LIB/typhoonae/channel/jsapi.py'), # Configure obscure dev/null handler ('/_ah/dev/null', '$PYTHON_LIB/typhoonae/handlers/devnull.py') ] if url not in [h.url for h in conf.handlers if h.url] ] # Generate URL mapping for handler in add_handlers + conf.handlers: script = handler.script regexp = handler.url if script != None: if script.startswith('$PYTHON_LIB'): module = script.replace(os.sep, '.')[12:] if module.endswith('.py'): module = module[:-3] try: m = __import__(module) except Exception, err_obj: logging.error( "Could not initialize script '%s'. %s: %s" % (script, err_obj.__class__.__name__, err_obj)) continue p = os.path.dirname(m.__file__).split(os.sep) path = os.path.join(os.sep.join(p[:len(p) - 1]), script[12:]) else: path = os.path.join(os.getcwd(), script) if path.startswith(os.sep) and not os.path.isfile(path): path = path[1:] if not regexp.startswith('^'): regexp = '^' + regexp if not regexp.endswith('$'): regexp += '$' compiled = re.compile(regexp) login_required = handler.login in ('required', 'admin') admin_only = handler.login in ('admin', ) url_mapping.append( (compiled, script, path, login_required, admin_only))
def test_optional(self): """Test page with no login requirement, and no cookie.""" url_map = appinfo.URLMap(url='/') h = url_handler.UserConfiguredURLHandler(url_map, '/$') def start_response(unused_status, unused_response_headers, unused_exc_info=None): # Successful authorization should not call start_response self.fail('start_response was called') r = h.handle_authorization(self.environ, start_response) self.assertEqual(None, r)
def test_good_app_yaml_configuration(self): automatic_scaling = appinfo.AutomaticScaling( min_pending_latency='1.0s', max_pending_latency='2.0s', min_idle_instances=1, max_idle_instances=2) error_handlers = [appinfo.ErrorHandlers(file='error.html')] handlers = [appinfo.URLMap()] env_variables = appinfo.EnvironmentVariables() info = appinfo.AppInfoExternal( application='app', module='module1', version='1', runtime='python27', threadsafe=False, automatic_scaling=automatic_scaling, skip_files=r'\*.gif', error_handlers=error_handlers, handlers=handlers, inbound_services=['warmup'], env_variables=env_variables, ) appinfo_includes.ParseAndReturnIncludePaths(mox.IgnoreArg()).AndReturn( (info, [])) os.path.getmtime('/appdir/app.yaml').AndReturn(10) self.mox.ReplayAll() config = application_configuration.ModuleConfiguration( '/appdir/app.yaml') self.mox.VerifyAll() self.assertEqual(os.path.realpath('/appdir'), config.application_root) self.assertEqual(os.path.realpath('/appdir/app.yaml'), config.config_path) self.assertEqual('dev~app', config.application) self.assertEqual('app', config.application_external_name) self.assertEqual('dev', config.partition) self.assertEqual('module1', config.module_name) self.assertEqual('1', config.major_version) self.assertRegexpMatches(config.version_id, r'module1:1\.\d+') self.assertEqual('python27', config.runtime) self.assertFalse(config.threadsafe) self.assertEqual(automatic_scaling, config.automatic_scaling) self.assertEqual(info.GetNormalizedLibraries(), config.normalized_libraries) self.assertEqual(r'\*.gif', config.skip_files) self.assertEqual(error_handlers, config.error_handlers) self.assertEqual(handlers, config.handlers) self.assertEqual(['warmup'], config.inbound_services) self.assertEqual(env_variables, config.env_variables) self.assertEqual({'/appdir/app.yaml': 10}, config._mtimes)
def test_simple_path(self): url_map = appinfo.URLMap(url='/foo', static_dir='subdir') h = static_files_handler.StaticDirHandler(root_path='/appdir', url_map=url_map) match = h.match('/foo/bar.jpg') self.assertTrue(match) self.assertFalse(h.match('/baz')) static_files_handler.StaticContentHandler._handle_path( os.path.join('/appdir', 'subdir', 'bar.jpg'), {}, mox.IgnoreArg()).AndReturn('<output>') self.mox.ReplayAll() self.assertEqual('<output>', h.handle(match, {}, None)) self.mox.VerifyAll()
def test_simple_path(self): url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticFilesHandler(root_path='/appdir', url_map=url_map) match = h.match('/') self.assertTrue(match) self.assertFalse(h.match('/other')) static_files_handler.StaticContentHandler._handle_path( os.path.join('/appdir', 'index.html'), {}, mox.IgnoreArg()).AndReturn('<output>') self.mox.ReplayAll() self.assertEqual('<output>', h.handle(match, {}, None)) self.mox.VerifyAll()
def test_required_redirect_no_login(self): """Test page with login: required; redirect, and no cookie.""" url_map = appinfo.URLMap(url='/', login='******') h = url_handler.UserConfiguredURLHandler(url_map, '/$') expected_status = '302 Requires login' expected_location = ( 'https://localhost:1443/login?continue=http%3A//localhost%3A8080' '/my/album/of/pictures%3Fwith%3Dsome%26query%3Dparameters') expected_headers = {'Location': expected_location} self.assertResponse(expected_status, expected_headers, '', h.handle_authorization, self.environ)
def test_patterned_path(self): url_map = appinfo.URLMap(url=r'/(.*)/(.*)', static_files=r'static/\1/subdir/\2') h = static_files_handler.StaticFilesHandler(root_path='/appdir', url_map=url_map) match = h.match('/hello/foo.jpg') self.assertTrue(match) self.assertFalse(h.match('/')) static_files_handler.StaticContentHandler._handle_path( os.path.join('/appdir', 'static/hello/subdir/foo.jpg'), {}, mox.IgnoreArg()).AndReturn('<output>') self.mox.ReplayAll() self.assertEqual('<output>', h.handle(match, {}, None)) self.mox.VerifyAll()
def test_required_unauthorized_no_login(self): """Test page with login: required; unauthorized, and no cookie.""" url_map = appinfo.URLMap(url='/', login='******', auth_fail_action='unauthorized') h = url_handler.UserConfiguredURLHandler(url_map, '/$') expected_status = '401 Not authorized' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'} expected_content = 'Login required to view page.' self.assertResponse(expected_status, expected_headers, expected_content, h.handle_authorization, self.environ)
def test_admin_succeed(self): """Test page with login: admin, and a valid admin cookie.""" url_map = appinfo.URLMap(url='/', login='******') h = url_handler.UserConfiguredURLHandler(url_map, '/$') self.environ['HTTP_COOKIE'] = COOKIE_ADMIN def start_response(unused_status, unused_response_headers, unused_exc_info=None): # Successful authorization should not call start_response self.fail('start_response was called') r = h.handle_authorization(self.environ, start_response) self.assertEqual(None, r)
def test_login_required_no_login_fake_logged_in_header(self): """Test page with login: required with fake-login-required.""" url_map = appinfo.URLMap(url='/', login='******') h = url_handler.UserConfiguredURLHandler(url_map, '/$') self.environ[constants.FAKE_LOGGED_IN_HEADER] = '1' def start_response(unused_status, unused_response_headers, unused_exc_info=None): # Successful authorization should not call start_response self.fail('start_response was called') r = h.handle_authorization(self.environ, start_response) self.assertEqual(None, r)
def test_admin_no_login_fake_is_admin_header(self): """Test page with login: admin, and no cookie, with fake-is-admin header.""" url_map = appinfo.URLMap(url='/', login='******') h = url_handler.UserConfiguredURLHandler(url_map, '/$') self.environ[constants.FAKE_IS_ADMIN_HEADER] = '1' def start_response(unused_status, unused_response_headers, unused_exc_info=None): # Successful authorization should not call start_response self.fail('start_response was called') r = h.handle_authorization(self.environ, start_response) self.assertEqual(None, r)
def setUp(self): self.mox = mox.Mox() self.tmpdir = tempfile.mkdtemp() self.proxy = http_proxy.HttpProxy( host='localhost', port=23456, instance_died_unexpectedly=lambda: False, instance_logs_getter=get_instance_logs, error_handler_file=None) self.mox.StubOutWithMock(httplib.HTTPConnection, 'connect') self.mox.StubOutWithMock(httplib.HTTPConnection, 'request') self.mox.StubOutWithMock(httplib.HTTPConnection, 'getresponse') self.mox.StubOutWithMock(httplib.HTTPConnection, 'close') self.mox.StubOutWithMock(login, 'get_user_info') self.url_map = appinfo.URLMap(url=r'/(get|post).*', script=r'\1.py')
def ParseAndReturnIncludePaths(appinfo_file, open_fn=open): """Parse an AppYaml file and merge referenced includes and builtins. Args: appinfo_file: an opened file, for example the result of open('app.yaml'). open_fn: a function to open included files. Returns: A tuple where the first element is the parsed appinfo.AppInfoExternal object and the second element is a list of the absolute paths of the included files, in no particular order. """ try: appinfo_path = appinfo_file.name if not os.path.isfile(appinfo_path): raise Exception( 'Name defined by appinfo_file does not appear to be a ' 'valid file: %s' % appinfo_path) except AttributeError: raise Exception('File object passed to ParseAndMerge does not define ' 'attribute "name" as as full file path.') appyaml = appinfo.LoadSingleAppInfo(appinfo_file) appyaml, include_paths = _MergeBuiltinsIncludes(appinfo_path, appyaml, open_fn) if not appyaml.handlers: if appyaml.vm: appyaml.handlers = [appinfo.URLMap(url='.*', script='PLACEHOLDER')] else: raise appinfo_errors.MissingURLMapping( 'No URLMap entries found in application configuration') if len(appyaml.handlers) > appinfo.MAX_URL_MAPS: raise appinfo_errors.TooManyURLMappings( 'Found more than %d URLMap entries in application configuration' % appinfo.MAX_URL_MAPS) if appyaml.runtime == 'python27' and appyaml.threadsafe: for handler in appyaml.handlers: if (handler.script and (handler.script.endswith('.py') or '/' in handler.script)): raise appinfo_errors.ThreadsafeWithCgiHandler( 'Threadsafe cannot be enabled with CGI handler: %s' % handler.script) return appyaml, include_paths
def test_admin_no_admin(self): """Test page with login: admin, and a non-admin cookie.""" url_map = appinfo.URLMap(url='/', login='******') h = url_handler.UserConfiguredURLHandler(url_map, '/$') self.environ['HTTP_COOKIE'] = COOKIE expected_status = '401 Not authorized' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'} expected_content = ('Current logged in user [email protected] is not ' 'authorized to view this page.') self.assertResponse(expected_status, expected_headers, expected_content, h.handle_authorization, self.environ)
def test_required_no_login_fake_is_admin(self): """Test page with login: required, no cookie, with fake-is-admin header.""" # This should FAIL, because fake-is-admin only applies to login: admin, not # login: required. url_map = appinfo.URLMap(url='/', login='******') h = url_handler.UserConfiguredURLHandler(url_map, '/$') self.environ[constants.FAKE_IS_ADMIN_HEADER] = '1' expected_status = '302 Requires login' expected_location = ( 'https://localhost:1443/login?continue=http%3A//localhost%3A8080' '/my/album/of/pictures%3Fwith%3Dsome%26query%3Dparameters') expected_headers = {'Location': expected_location} self.assertResponse(expected_status, expected_headers, '', h.handle_authorization, self.environ)
def test_file_does_not_exist_stat(self): url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticContentHandler(root_path=None, url_map=url_map, url_pattern='/$') error = IOError() error.errno = errno.ENOENT os.path.getmtime('/home/appdir/index.html').AndRaise(error) self.mox.ReplayAll() self.assertResponse('404 Not Found', {}, '', h._handle_path, '/home/appdir/index.html', { 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/' }) self.mox.VerifyAll()
def test_admin_no_login_fake_logged_in(self): """Tests page with login: admin, no cookie with fake login header.""" # This should FAIL, because a fake login does not imply admin privileges. url_map = appinfo.URLMap(url='/', login='******') h = url_handler.UserConfiguredURLHandler(url_map, '/$') self.environ[constants.FAKE_LOGGED_IN_HEADER] = '1' expected_status = '401 Not authorized' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'} expected_content = ('Current logged in user Fake User is not authorized ' 'to view this page.') self.assertResponse(expected_status, expected_headers, expected_content, h.handle_authorization, self.environ)