desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests for error when BlobRange start is after the blob end.'
def test_download_range_blob_range_header_start_after_end(self):
blob_key = self.create_blob() environ = {'HTTP_RANGE': 'bytes=2-5'} headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key)), (blobstore.BLOB_RANGE_HEADER, 'bytes=6-20'), ('Content-Type', 'text/x-my-content-type'), ('Content-Range', 'bytes 1-2/6')] application = wsgi_test_utils.constant_app('200 orig...
'Construct and execute a transform request using the images stub. Args: blob_key: A str containing the blob_key of the image to transform. options: A str containing the resize and crop options to apply to the image. Returns: A str containing the tranformed (if necessary) image.'
def _transform_image(self, blob_key, options):
(resize, crop) = self._parse_options(options) image_data = images_service_pb.ImageData() image_data.set_blob_key(blob_key) image = _get_images_stub()._OpenImageData(image_data) original_mime_type = image.format (width, height) = image.size if crop: crop_xform = None if (width...
'Parse an options string into a tuple containing the options. Currently this only supports resize and crop. Args: options: A str containing the url resize and crop options. Returns: A tuple (resize, crop) parsed from the string. Raises: InvalidRequestError: The requested resize is invalid.'
def _parse_options(self, options):
match = _OPTIONS_RE.search(options) resize = None crop = False if match: if match.group(1): resize = int(match.group(1)) if match.group(2): crop = True if (resize and ((resize > _SIZE_LIMIT) or (resize < 0))): logging.error('Invalid resize: %r', ...
'Parse the request path into the blobkey and option string. Args: path: A str containing the path of the request. Returns: A tuple (blob_key, option) parsed out of the path. Raises: InvalidRequestError: The request path is invalid.'
def _parse_path(self, path):
match = _PATH_RE.search(path) if ((not match) or (not match.group(1))): logging.error('Failed to parse image path "%s"', path) raise InvalidRequestError() options = '' blobkey = match.group(1) if match.group(3): if match.group(2): blobkey += match.g...
'Dynamically serve an image from blobstore.'
def serve_image(self, environ, start_response):
(blobkey, options) = self._parse_path(environ['PATH_INFO']) key = datastore.Key.from_path(_BLOB_SERVING_URL_KIND, blobkey, namespace='') try: datastore.Get(key) except datastore_errors.EntityNotFoundError: logging.error('The blobkey %s has not registered for image ...
'Initializer for PythonRuntimeInstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided with request information for use by API stubs. runtime_config_getter: A function that can be called without arguments and returns the runtime_config_pb2.Config containing the configuration for th...
def __init__(self, request_data, runtime_config_getter, module_configuration):
super(PythonRuntimeInstanceFactory, self).__init__(request_data, (8 if runtime_config_getter().threadsafe else 1), 10) self._runtime_config_getter = runtime_config_getter self._module_configuration = module_configuration
'Create and return a new Instance. Args: instance_id: A string or integer representing the unique (per module) id of the instance. expect_ready_request: If True then the instance will be sent a special request (i.e. /_ah/warmup or /_ah/start) before it can handle external requests. Returns: The newly created instance.I...
def new_instance(self, instance_id, expect_ready_request=False):
def instance_config_getter(): runtime_config = self._runtime_config_getter() runtime_config.instance_id = str(instance_id) return runtime_config proxy = http_runtime.HttpRuntimeProxy(_RUNTIME_ARGS, instance_config_getter, self._module_configuration, env=dict(os.environ, PYTHONHASHSEED='r...
'Set up the mocks and output objects for tests.'
def setUp(self):
self._mock_channel_service_stub = MockChannelServiceStub() self._old_get_channel_stub = channel._get_channel_stub channel._get_channel_stub = (lambda : self._mock_channel_service_stub) self._channel_app = channel.application self._output = StringIO.StringIO()
'Test a channel request with no pending messages.'
def test_channel_request_no_messages(self):
environ = _build_poll_environ('id') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0'} self.assertResponse('200 OK', expected_headers, '', channel.application, environ)
'Test a channel request with missing query string parameters.'
def test_channel_request_missing_parameters(self):
environ = _build_environ('/_ah/channel/dev', {'command': 'poll'}) expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0'} self.assertResponse('400 Bad Request', expected_headers, '', channel.application, environ) environ = _build_environ('/_ah/channel/dev', {'channel': 'id'}) s...
'Test a channel request with an invalid command.'
def test_channel_request_bad_command(self):
environ = _build_environ('/_ah/channel/dev', {'command': 'bad', 'channel': 'id'}) expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0'} self.assertResponse('400 Bad Request', expected_headers, '', channel.application, environ)
'Test a channel request with an invalid token.'
def test_channel_request_bad_token(self):
environ = _build_poll_environ('bad') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0'} self.assertResponse('401 Invalid+token.', expected_headers, '', channel.application, environ)
'Test a channel request with an expired token.'
def test_channel_request_expired_token(self):
environ = _build_poll_environ('expired') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0'} self.assertResponse('401 Token+timed+out.', expected_headers, '', channel.application, environ)
'Test a channel request with another channel with messages.'
def test_channel_request_other_channel_has_messages(self):
self._mock_channel_service_stub.set_messages({'a': ['hello']}) environ = _build_poll_environ('b') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0'} self.assertResponse('200 OK', expected_headers, '', channel.application, environ)
'Test a channel request with a channel that has a message.'
def test_channel_request_with_messages(self):
self._mock_channel_service_stub.set_messages({'a': ['hello']}) environ = _build_poll_environ('a') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '5', 'Content-Type': 'application/json'} self.assertResponse('200 OK', expected_headers, 'hello', channel.application, environ)
'Test a channel request with a channel that has a 0-length message.'
def test_channel_request_empty_message(self):
self._mock_channel_service_stub.set_messages({'a': ['']}) environ = _build_poll_environ('a') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0', 'Content-Type': 'application/json'} self.assertResponse('200 OK', expected_headers, '', channel.application, environ)
'Test a channel request with a channel that has multiple messages.'
def test_channel_request_with_multiple_messages(self):
self._mock_channel_service_stub.set_messages({'a': ['hello', 'goodbye']}) environ = _build_poll_environ('a') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '5', 'Content-Type': 'application/json'} self.assertResponse('200 OK', expected_headers, 'hello', channel.application, enviro...
'Test that request a channel\'s messages clears those messages.'
def test_channel_request_clears_messages(self):
self._mock_channel_service_stub.set_messages({'a': ['hello']}) environ = _build_poll_environ('a') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '5', 'Content-Type': 'application/json'} self.assertResponse('200 OK', expected_headers, 'hello', channel.application, environ) expe...
'Test that request a channel\'s messages clears only those messages.'
def test_channel_request_clears_correct_messages(self):
self._mock_channel_service_stub.set_messages({'a': ['hello'], 'b': ['goodbye']}) environ = _build_poll_environ('a') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '5', 'Content-Type': 'application/json'} self.assertResponse('200 OK', expected_headers, 'hello', channel.application,...
'Ensure that a channel request causes the channel to be connected.'
def test_channel_request_connects_channel(self):
mock_stub = self._mock_channel_service_stub mock_stub.set_connected_tokens([]) environ = _build_poll_environ('id') expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': '0'} self.assertResponse('200 OK', expected_headers, '', channel.application, environ) self.assertListEqual(['i...
'Test that requesting the jsapi script returns expected result.'
def test_channel_request_jsapi(self):
environ = _build_environ('/_ah/channel/jsapi') js_text = open(channel._JSAPI_PATH).read() expected_headers = {'Cache-Control': 'no-cache', 'Content-Length': str(len(js_text)), 'Content-Type': 'text/javascript'} self.assertResponse('200 OK', expected_headers, js_text, channel.application, environ)
'Return a sorted list of kind names present in the given namespace.'
@staticmethod def _get_kinds(namespace):
assert (namespace is not None) q = metadata.Kind.all(namespace=namespace) return sorted([x.kind_name for x in q.run()])
'Handle modifying actions and redirect to a GET page.'
def post(self):
if self.request.get('action:flush_memcache'): if memcache.flush_all(): message = 'Cache flushed, all keys dropped.' else: message = 'Flushing the cache failed. Please try again.' self.redirect(self._construct_url(remove=['action:flush_mem...
'Serve out the contents of a file to self.response. Args: asset_name: The name of the static asset to serve. Must be in ASSETS_PATH.'
def get(self, asset_name):
with self._asset_name_to_path_lock: if (self._asset_name_to_path is None): self._initialize_asset_map() if (asset_name in self._asset_name_to_path): asset_path = self._asset_name_to_path[asset_name] try: with open(asset_path, 'rb') as f: data = f.r...
'Handle modifying actions and redirect to a GET page.'
def post(self, queue_name):
task_name = self.request.get('task_name') if self.request.get('action:deletetask'): result = self._delete_task(queue_name, task_name) elif self.request.get('action:runtask'): result = self._run_task(queue_name, task_name) if (result == taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_Q...
'Deletes blobs identified in \'blob_key\' form variables. Multiple keys can be specified e.g. \'...&blob_key=key1&blob_key=key2\'. Redirects the client back to the value specified in the \'return_to\' form variable.'
def post(self):
redirect_url = str(self.request.get('return_to', '/blobstore')) keys = self.request.get_all('blob_key') blobstore.delete(keys) self.redirect(redirect_url)
'Fetch value from memcache and detect its type. Args: key: String Returns: (value, type), value is a Python object or None if the key was not set in the cache, type is a string describing the type of the value.'
def _get_memcache_value_and_type(self, key):
try: value = memcache.get(key) except (pickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError) as e: msg = ('Failed to retrieve value from cache: %s' % e) return (msg, 'error') if (value is None): return (None, self.DEFAULT_TYPESTR_FOR_NEW...
'Convert a string value and store the result in memcache. Args: key: String type_: String, describing what type the value should have in the cache. value: String, will be converted according to type_. Returns: Result of memcache.set(key, converted_value). True if value was set. Raises: ValueError: Value can\'t be conv...
def _set_memcache_value(self, key, type_, value):
for (_, converter, typestr) in self.TYPES: if (typestr == type_): value = converter(value) break else: raise ValueError(('Type %s not supported.' % type_)) return memcache.set(key, value)
'Show template and prepare stats and/or key+value to display/edit.'
def get(self):
values = {'request': self.request, 'message': self.request.get('message')} edit = self.request.get('edit') key = self.request.get('key') if edit: key = edit values['show_stats'] = False values['show_value'] = False values['show_valueform'] = True values['types'] =...
'Encode a dictionary into a URL query string. In contrast to urllib this encodes unicode characters as UTF8. Args: query: Dictionary of key/value pairs. Returns: String.'
def _urlencode(self, query):
return '&'.join((('%s=%s' % (urllib.quote_plus(k.encode('utf8')), urllib.quote_plus(v.encode('utf8')))) for (k, v) in query.iteritems()))
'Handle modifying actions and/or redirect to GET page.'
def post(self):
next_param = {} if self.request.get('action:flush'): if memcache.flush_all(): next_param['message'] = 'Cache flushed, all keys dropped.' else: next_param['message'] = 'Flushing the cache failed. Please try again.' elif self.request.ge...
'Load the XSRF token from the given path.'
@classmethod def init_xsrf(cls, xsrf_path):
if os.path.exists(xsrf_path): with open(xsrf_path, 'r') as token_file: cls.xsrf_token = token_file.read().strip() else: cls.xsrf_token = ''.join((random.choice(string.ascii_letters) for _ in range(10))) with open(xsrf_path, 'w') as token_file: token_file.write(cls...
'Returns a rendered version of the given jinja2 template. Args: template: The file name of the template file to use e.g. "memcache_viewer.html". context: A dict of values to use when rendering the template. Returns: A Unicode object containing the rendered template.'
def render(self, template, context):
template = admin_template_environment.get_template(template) values = {'app_id': self.configuration.app_id, 'request': self.request, 'sdk_version': self._SDK_VERSION, 'xsrf_token': self.xsrf_token} values.update(context) return template.render(values)
'Returns a URL referencing the current resource with the same params. For example, if the request URL is "http://foo/bar?animal=cat&color=redirect" then _construct_url([\'animal\'], {\'vehicle\': \'car\'}) will return "http://foo/bar?vehicle=car&color=redirect" Args: remove: A sequence of query parameters to remove fro...
def _construct_url(self, remove=None, add=None):
remove = (remove or []) add = (add or {}) params = dict(self.request.params) for arg in remove: if (arg in params): del params[arg] params.update(add) return str(('%s?%s' % (self.request.path, urllib.urlencode(sorted(params.iteritems())))))
'Loads the cron.yaml file and parses it. Returns: A croninfo.CronInfoExternal containing cron jobs. Raises: yaml_errors.Error, StandardError: The cron.yaml was invalid.'
def _parse_cron_yaml(self):
for cron_yaml in ('cron.yaml', 'cron.yml'): try: with open(os.path.join(self.configuration.servers[0].application_root, cron_yaml)) as f: cron_info = croninfo.LoadSingleCron(f) return cron_info except IOError: continue return None
'Handle modifying actions and redirect to a GET page.'
def post(self):
queue_name = self.request.get('queue') if self.request.get('action:purgequeue'): self._purge_queue(queue_name) self.redirect(self.request.path_url)
'Initializer for _QueueInfo. Args: name: The name of the queue e.g. "default". mode: A taskqueue_service_pb.TaskQueueMode constant representing the queue type e.g. PULL. rate: The execution rate of the queue as a string e.g. "10/s". May be None for pull queues. bucket_size: An int representing the size of the queues to...
def __init__(self, name, mode, rate, bucket_size, tasks_in_queue, oldest_eta_usec):
self.name = name self.mode = mode self.rate = rate self.bucket_size = bucket_size self.tasks_in_queue = tasks_in_queue if (oldest_eta_usec == (-1)): self.oldest_eta_usec = None else: self.oldest_eta_usec = oldest_eta_usec
'Return a new _QueueInfo given information from the taskqueue service. Args: queue: A taskqueue_service_pb.TaskQueueFetchQueuesResponse_Queue instance containing information about the queue. queue_stats: A taskqueue_service_pb.TaskQueueFetchQueueStatsResponse_QueueStats instance containing information about the queue. ...
@classmethod def _from_queue_and_stats(cls, queue, queue_stats):
return cls(queue.queue_name(), queue.mode(), queue.user_specified_rate(), queue.bucket_capacity(), queue_stats.num_tasks(), queue_stats.oldest_eta_usec())
'Returns a 2-tuple: (list of push _QueueInfo, list of pull _QueueInfo).'
@classmethod def get(cls, queue_names=frozenset()):
fetch_queue_request = taskqueue_service_pb.TaskQueueFetchQueuesRequest() fetch_queue_request.set_max_rows(1000) fetch_queue_response = taskqueue_service_pb.TaskQueueFetchQueuesResponse() apiproxy_stub_map.MakeSyncCall('taskqueue', 'FetchQueues', fetch_queue_request, fetch_queue_response) queue_stats...
'Returns the message boundary and entire content body for the form.'
def get_boundary_and_content(self):
boundary = ('----=' + ''.join((random.choice((string.letters + string.digits)) for _ in range(25)))) s = cStringIO.StringIO() for (name, value, sub_type) in self._data: s.write(('--%s\r\n' % boundary)) s.write(('Content-Type: text/%s; charset="UTF-8"\r\n' % sub_type)) s.write((...
'Initializer for AdminApplication. Args: dispatch: A dispatcher.Dispatcher instance used to route requests and provide state about running servers. configuration: An application_configuration.ApplicationConfiguration instance containing the configuration for the application.'
def __init__(self, dispatch, configuration):
super(AdminApplication, self).__init__([('/datastore', datastore_viewer.DatastoreRequestHandler), ('/datastore/edit/(.*)', datastore_viewer.DatastoreEditRequestHandler), ('/datastore/edit', datastore_viewer.DatastoreEditRequestHandler), ('/datastore-indexes', datastore_indexes_viewer.DatastoreIndexesViewer), ('/dat...
'Initializer for AdminServer. Args: host: A string containing the name of the host that the server should bind to e.g. "localhost". port: An int containing the port that the server should bind to e.g. 80. dispatch: A dispatcher.Dispatcher instance used to route requests and provide state about running servers. configur...
def __init__(self, host, port, dispatch, configuration, xsrf_token_path):
self._host = host self._xsrf_token_path = xsrf_token_path super(AdminServer, self).__init__((host, port), AdminApplication(dispatch, configuration))
'Start the AdminServer.'
def start(self):
admin_request_handler.AdminRequestHandler.init_xsrf(self._xsrf_token_path) super(AdminServer, self).start() logging.info('Starting admin server at: http://%s:%d', self._host, self.port)
'Quits the AdminServer.'
def quit(self):
super(AdminServer, self).quit() console.ConsoleRequestHandler.quit()
'Initializer for WSGIRequestInfo. Args: dispatcher: A request_info.Dispatcher instance to provide to API stubs.'
def __init__(self, dispatcher):
super(WSGIRequestInfo, self).__init__() self._request_wsgi_environ = {} self._request_id_to_module_configuration = {} self._request_id_to_instance = {} self._lock = threading.Lock() self._dispatcher = dispatcher
'A context manager that consumes a WSGI environ and returns a request id. with request_information.request(environ, app_info_external) as request_id: # Stubs will have access to the state associated with request_id only in # this context. send_request_to_runtime(request_id, ...) Args: environ: An environ dict for the r...
@contextlib.contextmanager def request(self, environ, module_configuration):
request_id = self.start_request(environ, module_configuration) (yield request_id) self.end_request(request_id)
'Adds the WSGI to the state of the class and returns a request id. Args: environ: An environ dict for the request as defined in PEP-333. module_configuration: An application_configuration.ModuleConfiguration instance respresenting the current module configuration. Returns: A unique string id that will be associated wit...
def start_request(self, environ, module_configuration):
with self._lock: request_id = _choose_request_id() self._request_wsgi_environ[request_id] = environ self._request_id_to_module_configuration[request_id] = module_configuration return request_id
'Removes the information associated with given request_id.'
def end_request(self, request_id):
with self._lock: del self._request_wsgi_environ[request_id] del self._request_id_to_module_configuration[request_id] if (request_id in self._request_id_to_instance): del self._request_id_to_instance[request_id]
'Returns the URL the request e.g. \'http://localhost:8080/foo?bar=baz\'. Args: request_id: The string id of the request making the API call. scheme: A string, the protocol to be used for this request URL. Returns: The URL of the request as a string.'
def get_request_url(self, request_id, scheme=None):
with self._lock: environ = self._request_wsgi_environ[request_id] url = wsgiref.util.request_uri(environ) if (scheme is not None): url = '{0}{1}'.format(scheme, url[url.find(':'):]) return url
'Returns a dict containing the WSGI environ for the request.'
def get_request_environ(self, request_id):
with self._lock: return self._request_wsgi_environ[request_id]
'Returns the Dispatcher. Returns: The Dispatcher instance.'
def get_dispatcher(self):
return self._dispatcher
'Returns the name of the module serving this request. Args: request_id: The string id of the request making the API call. Returns: A str containing the module name.'
def get_module(self, request_id):
with self._lock: return self._request_id_to_module_configuration[request_id].module_name
'Returns the version of the module serving this request. Args: request_id: The string id of the request making the API call. Returns: A str containing the version.'
def get_version(self, request_id):
with self._lock: return self._request_id_to_module_configuration[request_id].major_version
'Returns the instance serving this request. Args: request_id: The string id of the request making the API call. Returns: The instance.Instance serving this request or None if no instance is serving it.'
def get_instance(self, request_id):
with self._lock: return self._request_id_to_instance.get(request_id, None)
'Returns the scheme for this request. Args: request_id: The string id of the request making the API call. Returns: One of \'http\', \'https\'.'
def get_scheme(self, request_id):
with self._lock: scheme = 'http' environ = self._request_wsgi_environ[request_id] if (environ['HTTP_X_FORWARDED_PROTO'] is not None): scheme = environ['HTTP_X_FORWARDED_PROTO'] return scheme
'Initializes a new ThreadExecutor instance.'
def __init__(self):
self._shutdown = False self._shutdown_lock = threading.Lock()
'Create exactly num_directories subdirectories in path.'
def _create_directory_tree(self, path, num_directories):
assert (num_directories >= 0) if (not num_directories): return self._create_directory(path) num_directories -= 1 for i in range(4, 0, (-1)): sub_dir_size = (num_directories / i) self._create_directory_tree(os.path.join(path, ('dir%d' % i)), sub_dir_size) num_directori...
'Tests that internal _directory_to_subdirs is updated on delete.'
def test_subdirectory_deleted(self):
path = self._create_directory('test') sub_path = self._create_directory('test/test2') self._watcher.start() self.assertEqual(set([sub_path]), self._watcher._directory_to_subdirs[path]) os.rmdir(sub_path) self.assertEqual(set([sub_path]), self._watcher._get_changed_paths()) self.assertEqual(s...
'Returns the address of a module.'
def module_to_address(self, module_name, instance=None):
if (module_name is None): return self._dispatcher.dispatch_address return self._dispatcher.get_hostname(module_name, self._dispatcher.get_default_version(module_name), instance)
'Start devappserver2 servers based on the provided command line arguments. Args: options: An argparse.Namespace containing the command line arguments.'
def start(self, options):
logging.getLogger().setLevel(_LOG_LEVEL_TO_PYTHON_CONSTANT[options.dev_appserver_log_level]) configuration = application_configuration.ApplicationConfiguration(options.yaml_files) if options.skip_sdk_update_check: logging.info('Skipping SDK update check.') else: update_checker.c...
'Stops all running devappserver2 modules.'
def stop(self):
while self._running_modules: self._running_modules.pop().quit()
'Tests the get_user_info function when the admin field is True.'
def test_get_user_info_admin(self):
cookie_value = self.get_cookie_value(EMAIL, NICKNAME, True) http_cookie = ('one=two; %s=%s; three=four' % (COOKIE_NAME, cookie_value)) (email, admin, _) = login.get_user_info(http_cookie, cookie_name=COOKIE_NAME) self.assertEqual(EMAIL, email) self.assertTrue(admin)
'Tests the get_user_info function when the admin field is False.'
def test_get_user_info_not_admin(self):
cookie_value = self.get_cookie_value(EMAIL, NICKNAME, False) http_cookie = ('one=two; %s=%s; three=four' % (COOKIE_NAME, cookie_value)) (email, admin, user_id) = login.get_user_info(http_cookie, cookie_name=COOKIE_NAME) self.assertEqual(EMAIL, email) self.assertFalse(admin)
'Tests the get_user_info function when the admin field is False.'
def test_get_user_info_invalid_email(self):
cookie_value = self.get_cookie_value('foo', NICKNAME, False) cookie_value = ('foo:True:%s' % USER_ID) http_cookie = ('one=two; %s=%s; three=four' % (COOKIE_NAME, cookie_value)) (email, admin, user_id) = login.get_user_info(http_cookie, cookie_name=COOKIE_NAME) self.assertEqual('', email) s...
'Tests the get_user_info function when the cookie is not present.'
def test_get_user_info_does_not_exist(self):
http_cookie = 'one=two; three=four' (email, admin, user_id) = login.get_user_info(http_cookie, cookie_name=COOKIE_NAME) self.assertEqual('', email) self.assertFalse(admin)
'Tests the get_user_info function when the cookie is malformed.'
def test_get_user_info_bad_cookie(self):
cookie_name = 'SinaRot/g/get' cookie_value = 'blah' http_cookie = ('%s=%s' % (cookie_name, cookie_value)) (email, admin, user_id) = login.get_user_info(http_cookie, cookie_name=cookie_name) self.assertEqual('', email) self.assertFalse(admin)
'Tests the get_user_info function when the admin field is True.'
def test_get_user_info_from_dict_admin(self):
cookie_value = self.get_cookie_value(EMAIL, NICKNAME, True) cookie_dict = {'one': 'two', COOKIE_NAME: cookie_value, 'three': 'four'} (email, admin, user_id) = login._get_user_info_from_dict(cookie_dict, cookie_name=COOKIE_NAME) self.assertEqual(EMAIL, email) self.assertTrue(admin)
'Tests the get_user_info function when the admin field is False.'
def test_get_user_info_from_dict_not_admin(self):
cookie_value = self.get_cookie_value(EMAIL, NICKNAME, False) cookie_dict = {'one': 'two', COOKIE_NAME: cookie_value, 'three': 'four'} (email, admin, user_id) = login._get_user_info_from_dict(cookie_dict, cookie_name=COOKIE_NAME) self.assertEqual(EMAIL, email) self.assertFalse(admin)
'Tests the get_user_info function when the cookie is not present.'
def test_get_user_info_from_dict_does_not_exist(self):
cookie_dict = {'one': 'two', 'three': 'four'} (email, admin, user_id) = login._get_user_info_from_dict(cookie_dict, cookie_name=COOKIE_NAME) self.assertEqual('', email) self.assertFalse(admin)
'Tests the set_user_info_cookie function.'
def test_set_user_info_cookie(self):
cookie_value = ('%s:True:%s' % (EMAIL, USER_ID)) expected_result = ('%s="%s"; Path=/' % (COOKIE_NAME, cookie_value)) result = login._set_user_info_cookie(EMAIL, True, cookie_name=COOKIE_NAME) self.assertEqual(expected_result, result)
'Tests the clear_user_info_cookie function.'
def test_clear_user_info_cookie(self):
expected_result = ('%s=; Max-Age=0; Path=/' % COOKIE_NAME) result = login._clear_user_info_cookie(cookie_name=COOKIE_NAME) self.assertEqual(expected_result, result)
'Tests that redirects are written back to the user.'
def test_basic(self):
application_url = 'http://foo.com:1234' continue_url = 'http://foo.com:1234/my/album/of/pictures?with=some&query=parameters' expected_location = 'https://localhost:1443/login?continue=http%3A//foo.com%3A1234/my/album/of/pictures%3Fwith%3Dsome%26query%3Dparameters' def start_response(status, headers, exc...
'Tests just accessing the login URL with no params.'
def test_no_params(self):
host = 'foo.com:1234' path_info = '/_ah/login' cookie_dict = {} action = '' set_email = '' set_admin = False continue_url = '' (status, location, set_cookie, content_type) = self._run_test(host, path_info, cookie_dict, action, set_email, set_admin, continue_url) self.assertEqual(302,...
'Tests when setting the user info with and without continue URL.'
def test_login(self):
host = 'foo.com:1234' path_info = '/_ah/login' cookie_dict = {} action = 'Login' set_email = EMAIL set_admin = False continue_url = '' expected_set = login._set_user_info_cookie(set_email, set_admin).strip() (status, location, set_cookie, _) = self._run_test(host, path_info, cookie_d...
'Tests when logging out with and without continue URL.'
def test_logout(self):
host = 'foo.com:1234' path_info = '/_ah/login' cookie_dict = {'dev_appserver_login': ('%s:False:%s' % (EMAIL, USER_ID))} action = 'Logout' set_email = '' set_admin = False continue_url = '' expected_set = login._clear_user_info_cookie().strip() (status, location, set_cookie, _) = sel...
'Tests when the user is already logged in.'
def test_passive(self):
host = 'foo.com:1234' path_info = '/_ah/login' cookie_dict = {'dev_appserver_login': ('%s:False:%s' % (EMAIL, USER_ID))} action = '' set_email = '' set_admin = False continue_url = '/my/fancy/url' continue_url = 'http://foo.com/blah' (status, location, set_cookie, content_type) = sel...
'Runs the login HTTP handler, returning information about the response. Args: host: The value of the HTTP Host header. path_info: The absolute path of the request. cookie_dict: A cookie dictionary with the existing cookies. action: Value of the \'action\' query argument. set_email: Value of the \'email\' query argument...
def _run_test(self, host, path_info='/', cookie_dict=None, action=None, set_email=None, set_admin=None, continue_url=None, method='GET'):
environ = {} wsgiref.util.setup_testing_defaults(environ) environ['SERVER_NAME'] = 'do_not_use' environ['SERVER_PORT'] = '666' environ['SERVER_PROTOCOL'] = 'HTTP/1.1' environ['HTTP_HOST'] = host environ['PATH_INFO'] = path_info environ['REQUEST_METHOD'] = method if cookie_dict: ...
'Initializer for ModuleConfiguration. Args: yaml_path: A string containing the full path of the yaml file containing the configuration for this module.'
def __init__(self, yaml_path):
self._yaml_path = yaml_path self._app_info_external = None self._application_root = os.path.realpath(os.path.dirname(yaml_path)) self._last_failure_message = None (self._app_info_external, files_to_check) = self._parse_configuration(self._yaml_path) self._mtimes = self._get_mtimes(([self._yaml_p...
'The directory containing the application e.g. "/home/user/myapp".'
@property def application_root(self):
return self._application_root
'Return any configuration changes since the last check_for_updates call. Returns: A set containing the changes that occured. See the *_CHANGED module constants.'
def check_for_updates(self):
new_mtimes = self._get_mtimes(self._mtimes.keys()) if (new_mtimes == self._mtimes): return set() try: (app_info_external, files_to_check) = self._parse_configuration(self._yaml_path) except Exception as e: failure_message = str(e) if (failure_message != self._last_failure...
'Initializer for BackendsConfiguration. Args: app_yaml_path: A string containing the full path of the yaml file containing the configuration for this module. backend_yaml_path: A string containing the full path of the backends.yaml file containing the configuration for backends.'
def __init__(self, app_yaml_path, backend_yaml_path):
self._update_lock = threading.RLock() self._base_module_configuration = ModuleConfiguration(app_yaml_path) backend_info_external = self._parse_configuration(backend_yaml_path) self._backends_name_to_backend_entry = {} for backend in (backend_info_external.backends or []): self._backends_name...
'Return any configuration changes since the last check_for_updates call. Args: backend_name: A str containing the name of the backend to be checked for updates. Returns: A set containing the changes that occured. See the *_CHANGED module constants.'
def check_for_updates(self, backend_name):
with self._update_lock: module_changes = self._base_module_configuration.check_for_updates() if module_changes: for backend_changes in self._changes.values(): backend_changes.update(module_changes) changes = self._changes[backend_name] self._changes[backen...
'Initializer for BackendConfiguration. Args: module_configuration: A ModuleConfiguration to use. backends_configuration: The BackendsConfiguration that tracks updates for this BackendConfiguration. backend_entry: A backendinfo.BackendEntry containing the backend configuration.'
def __init__(self, module_configuration, backends_configuration, backend_entry):
self._module_configuration = module_configuration self._backends_configuration = backends_configuration self._backend_entry = backend_entry if backend_entry.dynamic: self._basic_scaling = appinfo.BasicScaling(max_instances=(backend_entry.instances or 1)) self._manual_scaling = None e...
'The directory containing the application e.g. "/home/user/myapp".'
@property def application_root(self):
return self._module_configuration.application_root
'Return any configuration changes since the last check_for_updates call. Returns: A set containing the changes that occured. See the *_CHANGED module constants.'
def check_for_updates(self):
changes = self._backends_configuration.check_for_updates(self._backend_entry.name) if changes: self._minor_version_id = ''.join((random.choice(string.digits) for _ in range(18))) return changes
'Initializer for ApplicationConfiguration. Args: yaml_paths: A list of strings containing the paths to yaml files.'
def __init__(self, yaml_paths):
self.modules = [] self.dispatch = None if ((len(yaml_paths) == 1) and os.path.isdir(yaml_paths[0])): directory_path = yaml_paths[0] for app_yaml_path in [os.path.join(directory_path, 'app.yaml'), os.path.join(directory_path, 'app.yml')]: if os.path.exists(app_yaml_path): ...
'Initializer for HttpRuntimeProxy. Args: args: Arguments to use to start the runtime subprocess. runtime_config_getter: A function that can be called without arguments and returns the runtime_config_pb2.Config containing the configuration for the runtime. module_configuration: An application_configuration.ModuleConfigu...
def __init__(self, args, runtime_config_getter, module_configuration, env=None):
super(HttpRuntimeProxy, self).__init__() self._host = 'localhost' self._port = None self._process = None self._process_lock = threading.Lock() self._runtime_config_getter = runtime_config_getter self._args = args self._module_configuration = module_configuration self._env = env
'Serves this request by forwarding it to the runtime process. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. url_map: An appinfo.URLMap instance containing the configuration for the handler matching this request. match: A re.MatchObjec...
def handle(self, environ, start_response, url_map, match, request_id, request_type):
environ[http_runtime_constants.SCRIPT_HEADER] = match.expand(url_map.script) if (request_type == instance.BACKGROUND_REQUEST): environ[http_runtime_constants.REQUEST_TYPE_HEADER] = 'background' elif (request_type == instance.SHUTDOWN_REQUEST): environ[http_runtime_constants.REQUEST_TYPE_HEAD...
'Starts the runtime process and waits until it is ready to serve.'
def start(self):
runtime_config = self._runtime_config_getter() serialized_config = base64.b64encode(runtime_config.SerializeToString()) with self._process_lock: assert (not self._process), 'start() can only be called once' self._process = safe_subprocess.start_process(self._args, serialized_c...
'Checks if the runtime can serve requests. Quits the development server if the runtime cannot serve.'
def _check_serving(self):
if (not self._can_connect()): logging.error('cannot connect to runtime running on port %r; exiting the development server', self._port) shutdown.async_quit()
'Causes the runtime process to exit.'
def quit(self):
with self._process_lock: assert self._process, 'module was not running' try: self._process.kill() except OSError: pass self._process = None
'Initializer for WSGIHandler. Args: wsgi_app: A WSGI application function as defined in PEP-333. url_pattern: A regular expression string containing the pattern for URLs handled by this handler. Unlike user-provided patterns in app.yaml, the pattern is not required to match the whole URL, only the start. (End the patte...
def __init__(self, wsgi_app, url_pattern):
super(WSGIHandler, self).__init__(re.compile(url_pattern)) self._wsgi_app = wsgi_app
'Serves the content associated with this handler. Args: unused_match: Unused. environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over strings containing the body of the HTTP response.'
def handle(self, unused_match, environ, start_response):
return self._wsgi_app(environ, start_response)
'Construct form from keywords.'
def __init__(self, subforms=None, headers=None, **kwds):
super(FakeForm, self).__init__() self.update((subforms or {})) self.headers = (headers or email.Message.Message()) for (key, value) in kwds.iteritems(): setattr(self, key, value)
'Configure test harness.'
def setUp(self):
self.original_environ = dict(os.environ) os.environ.update({'APPLICATION_ID': 'app', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080', 'AUTH_DOMAIN': 'abcxyz.com', 'USER_EMAIL': 'user@abcxyz.com'}) self.mox = mox.Mox() self.tmpdir = tempfile.mkdtemp() self.datastore_file = os.path.join(self.tmpdir,...
'Restore original environment.'
def tearDown(self):
os.environ = self.original_environ shutil.rmtree(self.tmpdir)
'Assert two strings representing messages are equal (equivalent). This normalizes the headers in both arguments and then compares them using assertMultiLineEqual().'
def assertMessageEqual(self, expected, actual):
expected = self.normalize_header_lines(expected) actual = self.normalize_header_lines(actual) return self.assertMultiLineEqual(expected, actual)
'Normalize blocks of header lines in a message. This sorts blocks of consecutive header lines and then for certain headers (Content-Type and -Disposition) sorts the parameter values.'
def normalize_header_lines(self, message):
lines = message.splitlines(True) output = [] headers = [] for line in lines: if re.match('^\\S+: ', line): line = self.normalize_header(line) headers.append(line) else: if headers: headers.sort() output.extend(headers...
'Normalize parameter values of Content-Type and -Disposition lines. This changes e.g. Content-Type: foo/bar; name="a"; file="b" into Content-Type: foo/bar; file="b"; name="a" It leaves other headers alone.'
def normalize_header(self, line):
match = re.match('^(Content-(?:Type|Disposition): )(\\S+; .*\\S)(\\s*)\\Z', line, re.IGNORECASE) if (not match): return line value = match.group(2) value = self.normalize_parameter_order(value) return ((match.group(1) + value) + match.group(3))
'Normalize the parameter values of a header. This changes e.g. foo/bar; name="a"; file="b" into foo/bar; file="b"; name="a" Note that the text before the first \';\' is unaffected.'
def normalize_parameter_order(self, value):
parts = value.split('; ') if (len(parts) > 2): value = ((parts[0] + '; ') + '; '.join(sorted(parts[1:]))) return value