desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Check that blob_key decodes to expected value. Args: blob_key: Blob key that was actually generated. expected_time: Time stamp that is expected to be in the md5 digest. expected_random: Random number that is expected to be in the md5 digest.'
def check_key(self, blob_key, expected_time, expected_random):
if (blob_key is None): self.fail('Generated blob-key is None.') digester = hashlib.md5() digester.update(str(expected_time)) digester.update(str(expected_random)) actual_digest = base64.urlsafe_b64decode(blob_key) self.assertEquals(digester.digest(), actual_digest)
'Basic test of key generation.'
def test_generate_key(self):
time_func = self.mox.CreateMockAnything() random_func = self.mox.CreateMockAnything() time_func().AndReturn(10) random_func().AndReturn(20) self.mox.ReplayAll() key = blob_upload._generate_blob_key(time_func, random_func) self.check_key(key, 10, 20) self.mox.VerifyAll()
'Test what happens when there is conflict in key generation.'
def test_generate_key_with_conflict(self):
time_func = self.mox.CreateMockAnything() random_func = self.mox.CreateMockAnything() time_func().AndReturn(10) random_func().AndReturn(20) time_func().AndReturn(10) random_func().AndReturn(30) time_func().AndReturn(10) random_func().AndReturn(20) random_func().AndReturn(30) rand...
'Test what happens when there are too many conflicts in key generation.'
def test_too_many_conflicts(self):
time_func = self.mox.CreateMockAnything() random_func = self.mox.CreateMockAnything() for i in range(10): time_func().AndReturn(10) random_func().AndReturn((10 + i)) time_func().AndReturn(10) for i in range(10): random_func().AndReturn((10 + i)) self.mox.ReplayAll() f...
'Setup for namespaces test.'
def setUp(self):
super(GenerateBlobKeyTestNamespace, self).setUp() namespace_manager.set_namespace('abc')
'Set up additional parts of the test framework.'
def setUp(self):
UploadTestBase.setUp(self) self.generate_blob_key = self.mox.CreateMockAnything() self.now = self.mox.CreateMockAnything() self.blob_storage_path = os.path.join(self.tmpdir, 'blobstore') self.storage = file_blob_storage.FileBlobStorage(self.blob_storage_path, os.environ['APPLICATION_ID']) def fo...
'Execute a basic blob insertion.'
def execute_blob_test(self, blob_content, expected_result, base64_encoding=False):
expected_key = blobstore.BlobKey('expectedkey') expected_creation = datetime.datetime(2008, 11, 12) self.generate_blob_key().AndReturn(expected_key) self.mox.ReplayAll() (content_type, blob_file, filename) = self.handler._preprocess_data('image/png; a="b"; m="n"', StringIO.StringIO(blob_conten...
'Test blob creation.'
def test_store_blob(self):
self.execute_blob_test('blob content', 'blob content')
'Test the high-level method to store a blob and build a MIME message.'
def test_store_and_build_forward_message(self):
self.generate_blob_key().AndReturn(blobstore.BlobKey('item1')) self.generate_blob_key().AndReturn(blobstore.BlobKey('item2')) self.generate_blob_key().AndReturn(blobstore.BlobKey('item3')) self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() form = FakeForm({'field1...
'Test the high-level method to store a blob and build a MIME message.'
def test_store_and_build_forward_message_with_gs_bucket(self):
self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) expected_key = blobstore.BlobKey('expectedkey') self.generate_blob_key().AndReturn(expected_key) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('file1'), type='image/png', type_options={'a':...
'Test store and build message method with UTF-8 values.'
def test_store_and_build_forward_message_utf8_values(self):
self.generate_blob_key().AndReturn(blobstore.BlobKey('item1')) self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('file1'), type='text/plain', type_options={'a': 'b', 'x': 'y'}, filename='chinese_ch...
'Test store and build message method with Latin-1 values.'
def test_store_and_build_forward_message_latin1_values(self):
self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('file1'), type='text/plain', type_options={'a': 'b', 'x': 'y'}, filename='german_char_name_f\xfc\xdfe.txt', headers={'h1': 'v1', 'h2': 'v2'})}) sel...
'Test default header generation when no headers are provided.'
def test_store_and_build_forward_message_no_headers(self):
self.generate_blob_key().AndReturn(blobstore.BlobKey('item1')) self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40, 0, 100)) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('file1'), type=None, type_options={}, filename='file1', headers={}), 'field2...
'Test upload with a zero length blob.'
def test_store_and_build_forward_message_zero_length_blob(self):
self.generate_blob_key().AndReturn(blobstore.BlobKey('item1')) self.generate_blob_key().AndReturn(blobstore.BlobKey('item2')) self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('file1'), type='i...
'Test upload with no filename in content disposition.'
def test_store_and_build_forward_message_no_filename(self):
self.generate_blob_key().AndReturn(blobstore.BlobKey('item1')) self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('file1'), type='image/png', type_options={'a': 'b', 'x': 'y'}, filename='stuff.png',...
'Test upload with no headers provided.'
def test_store_and_build_forward_message_bad_mimes(self):
for unused_mime in range(len(BAD_MIMES)): self.now() self.mox.ReplayAll() for mime_type in BAD_MIMES: form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('file1'), type=mime_type, type_options={}, filename='file', headers={})}) self.assertRaisesRegexp(webob.exc....
'Test upload with a blob larger than the maximum blob size.'
def test_store_and_build_forward_message_max_blob_size_exceeded(self):
self.generate_blob_key().AndReturn(blobstore.BlobKey('item1')) self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('a'), type='image/png', type_options={'a': 'b', 'x': 'y'}, filename='stuff.png', hea...
'Test upload with all blobs larger than the total allowed size.'
def test_store_and_build_forward_message_total_size_exceeded(self):
self.generate_blob_key().AndReturn(blobstore.BlobKey('item1')) self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('a'), type='image/png', type_options={'a': 'b', 'x': 'y'}, filename='stuff.png', hea...
'Test blob creation with a base-64-encoded body.'
def test_store_blob_base64(self):
expected_result = 'This is the blob content.' self.execute_blob_test(base64.urlsafe_b64encode(expected_result), expected_result, base64_encoding=True)
'Test that exception is raised if the filename is too large.'
def test_filename_too_large(self):
self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() filename = (('a' * blob_upload._MAX_STRING_NAME_LENGTH) + '.txt') form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('a'), type='image/png', type_options={'a': 'b', 'x': 'y'}, filename=filename, hea...
'Test that exception is raised if the content-type is too large.'
def test_content_type_too_large(self):
self.now().AndReturn(datetime.datetime(2008, 11, 12, 10, 40)) self.mox.ReplayAll() content_type = ('text/' + ('a' * blob_upload._MAX_STRING_NAME_LENGTH)) form = FakeForm({'field1': FakeForm(name='field1', file=StringIO.StringIO('a'), type=content_type, type_options={'a': 'b', 'x': 'y'}, filename='foobar...
'Setup for namespaces test.'
def setUp(self):
super(UploadHandlerUnitTestNamespace, self).setUp() namespace_manager.set_namespace('abc')
'Set up test framework.'
def setUp(self):
self.original_environ = dict(os.environ) os.environ.update({'APPLICATION_ID': 'app', 'USER_EMAIL': 'nobody@nowhere.com', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080'}) self.environ = {} wsgiref.util.setup_testing_defaults(self.environ) self.environ['REQUEST_METHOD'] = 'POST' self.user_stub ...
'Runs self.dispatcher and returns the response. self.environ should already be initialised with the WSGI environment, including the HTTP_* headers. Args: request_body: String containing the body of the request. Returns: (status, headers, response_body, forward_environ, forward_body), where: status is the response statu...
def run_dispatcher(self, request_body=''):
response_dict = {} state_dict = {'start_response_already_called': False, 'headers_already_sent': False} self.environ['wsgi.input'] = cStringIO.StringIO(request_body) body = cStringIO.StringIO() def write_body(text): if (not text): return assert state_dict['start_response_...
'Basic dispatcher request flow.'
def _run_test_success(self, upload_data, upload_url):
request_path = urlparse.urlparse(upload_url)[2] session_key = upload_url.split('/')[(-1)] self.environ['PATH_INFO'] = request_path self.environ['CONTENT_TYPE'] = 'multipart/form-data; boundary="================1234=="' (status, _, response_body, forward_environ, forward_body) = self.run_dispatche...
'Basic dispatcher request flow.'
def test_success(self):
upload_data = '--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nvalue\n--================1234==--' upload_url = blobstore.create_upload_url('/success?foo=bar') (upload, forward_environ, _) = self._run...
'Basic dispatcher request flow.'
def test_success_with_bucket(self):
upload_data = '--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nvalue\n--================1234==--' upload_url = blobstore.create_upload_url('/success?foo=bar', gs_bucket_name='my_test_bucket') (upload...
'Request flow with a success url containing protocol, host and port.'
def test_success_full_success_url(self):
upload_data = '--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nvalue\n--================1234==--' upload_url = blobstore.create_upload_url('https://example.com:1234/success?foo=bar') (upload, forward...
'Test automatic decoding of a base-64-encoded message.'
def test_base64(self):
upload_data = ('--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\nContent-Transfer-Encoding: base64\n\n%s\n--================1234==--' % base64.urlsafe_b64encode('value')) upload_url = blobstore.create_up...
'Using the wrong HTTP method on upload dispatcher causes an error.'
def test_wrong_method(self):
self.environ['REQUEST_METHOD'] = 'GET' (status, _, _, forward_environ, forward_body) = self.run_dispatcher() self.assertEquals('405 Method Not Allowed', status) self.assertEquals(None, forward_environ) self.assertEquals(None, forward_body)
'Using a non-existant upload session causes an error.'
def test_bad_session(self):
upload_url = blobstore.create_upload_url('/success') session_key = upload_url.split('/')[(-1)] datastore.Delete(session_key) request_path = urlparse.urlparse(upload_url)[2] self.environ['PATH_INFO'] = request_path (status, _, response_body, forward_environ, forward_body) = self.run_dispatcher() ...
'Using a bad mime type format causes an error.'
def test_bad_mime_format(self):
upload_data = '--================1234==\nContent-Type: text/plain/error\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nvalue\n--================1234==--' upload_url = blobstore.create_upload_url('/success') request_path = urlparse.urlparse(upload_ur...
'Ensure the upload message uses correct RFC-2821 line terminators.'
def test_check_line_endings(self):
upload_data = '--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nvalue\n--================1234==--' upload_url = blobstore.create_upload_url('/success') request_path = urlparse.urlparse(upload_url)[2] ...
'Tests that headers are copied, except for ones that should not be.'
def test_copy_headers(self):
upload_data = '--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nvalue\n--================1234==--' upload_url = blobstore.create_upload_url('/success') request_path = urlparse.urlparse(upload_url)[2] ...
'Ensure a 413 response is generated when upload size limit exceeded.'
def test_entity_too_large(self):
upload_data = '--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nLots and Lots of Stuff\n--================1234==--' upload_url = blobstore.create_upload_url('/success1', max_bytes_per_blob=1) ...
'Ensure a 400 response is generated when filename size limit exceeded.'
def test_filename_too_long(self):
filename = (('a' * 500) + '.txt') upload_data = ('Content-Type: multipart/form-data; boundary="================1234=="\n\n--================1234==\nContent-Type: text/plain\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="%s"\n\nLots and Lots of Stuff...
'Ensure a 400 response when content-type size limit exceeded.'
def test_content_type_too_long(self):
content_type = ('text/' + ('a' * 500)) upload_data = ('Content-Type: multipart/form-data; boundary="================1234=="\n\n--================1234==\nContent-Type: %s\nMIME-Version: 1.0\nContent-Disposition: form-data; name="field1"; filename="stuff.txt"\n\nLots and Lots of S...
'Ensure that an uncaught HTTPError is not inadvertently caught.'
def test_raise_uncaught_http_error(self):
def forward_app(unused_environ, unused_start_response): raise webob.exc.HTTPLengthRequired() self.dispatcher = blob_upload.Application(forward_app) upload_url = blobstore.create_upload_url('/success') request_path = urlparse.urlparse(upload_url)[2] self.environ['PATH_INFO'] = request_path ...
'Initializer for InotifyFileWatcher. Args: directory: A string representing the path to a directory that should be monitored for changes i.e. files and directories added, renamed, deleted or changed.'
def __init__(self, directory):
self._directory = os.path.abspath(directory) self._find_change_handle = None
'Start watching the directory for changes.'
def start(self):
self._find_change_handle = ctypes.windll.kernel32.FindFirstChangeNotificationA(self._directory, True, _INTERESTING_NOTIFICATIONS) if (self._find_change_handle == INVALID_HANDLE_VALUE): raise ctypes.WinError() if (not ctypes.windll.kernel32.FindNextChangeNotification(self._find_change_handle)): ...
'Stop watching the directory for changes.'
def quit(self):
ctypes.windll.kernel32.FindCloseChangeNotification(self._find_change_handle)
'Returns True if the watched directory has changed since the last call. start() must be called before this method. Returns: Returns True if the watched directory has changed since the last call to has_changes or, if has_changes has never been called, since start was called.'
def has_changes(self):
found_change = False while True: wait_result = ctypes.windll.kernel32.WaitForSingleObject(self._find_change_handle, 0) if (wait_result == WAIT_OBJECT_0): if (not ctypes.windll.kernel32.FindNextChangeNotification(self._find_change_handle)): raise ctypes.WinError() ...
'Handles an HTTP request for the runtime using a PHP executable. Args: environ: An environ dict for the 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 __call__(self, environ, start_response):
user_environ = self.environ_template.copy() self.copy_headers(environ, user_environ) user_environ['REQUEST_METHOD'] = environ.get('REQUEST_METHOD', 'GET') user_environ['PATH_INFO'] = environ['PATH_INFO'] user_environ['QUERY_STRING'] = environ['QUERY_STRING'] user_environ['REAL_SCRIPT_FILENAME'] ...
'Copy headers from source_environ to dest_environ. This extracts headers that represent environ values and propagates all other headers which are not used for internal implementation details or headers that are stripped. Args: source_environ: The source environ dict. dest_environ: The environ dict to populate.'
def copy_headers(self, source_environ, dest_environ):
for env in http_runtime_constants.ENVIRONS_TO_PROPAGATE: value = source_environ.get((http_runtime_constants.INTERNAL_ENVIRON_PREFIX + env), None) if (value is not None): dest_environ[env] = value for (name, value) in source_environ.items(): if (name.startswith('HTTP_') and (n...
'Replace the rewriter chain with a series of dummy rewriters.'
def setUp(self):
self.initial_calls = 0 self.chain_calls = 0 self.modify_calls = 0 self.test_status = True self.test_body = True def check_initial_response(state): self.assertEquals('Environ value', state.environ['ENVIRON_KEY']) if self.test_status: self.assertEquals('200 Good ...
'Tests that rewriter_middleware correctly chains rewriters.'
def test_rewrite_response_chain(self):
environ = {'ENVIRON_KEY': 'Environ value'} application = wsgi_test_utils.constant_app('200 Good to go', [('SomeHeader', 'Some value')], 'Original content') expected_status = '400 Not so good' expected_headers = {'AnotherHeader': 'Another value', 'SomeHeader': 'Some value...
'Tests an application that yields 0 body blocks.'
def test_body_no_yields(self):
def application(unused_environ, start_response): start_response('200 Good to go', [('SomeHeader', 'Some value')]) return [] environ = {'ENVIRON_KEY': 'Environ value'} expected_status = '400 Not so good' expected_headers = {'AnotherHeader': 'Another value', 'Som...
'Tests an application that yields several body blocks.'
def test_body_multiple_yields(self):
def application(unused_environ, start_response): start_response('200 Good to go', [('SomeHeader', 'Some value')]) (yield 'Origin') (yield 'al content') environ = {'ENVIRON_KEY': 'Environ value'} expected_status = '400 Not so good' expected_headers = {'A...
'Tests an application that calls write() and returns an iterable.'
def test_body_write_and_iterable(self):
def application(unused_environ, start_response): write = start_response('200 Good to go', [('SomeHeader', 'Some value')]) write('Origin') return ['al content'] environ = {'ENVIRON_KEY': 'Environ value'} expected_status = '400 Not so good' expected_heade...
'Tests an application that raises an exception before yielding.'
def test_body_exception_before_yield(self):
def application(unused_environ, start_response): start_response('200 Good to go', [('SomeHeader', 'Some value')]) (yield '') (yield '') try: raise ValueError('A problem happened') except ValueError as e: exc_info = sys.exc_info() ...
'Tests an application that raises an exception before yielding.'
def test_body_exception_after_yield(self):
def application(unused_environ, start_response): start_response('200 Good to go', [('SomeHeader', 'Some value')]) (yield 'Origin') try: raise ValueError('A problem happened') except ValueError as e: exc_info = sys.exc_info() start...
'Tests that the invalid request headers are stripped out.'
def test_request_header_sanitation(self):
input_environ = {'HTTP_ACCEPT_ENCODING': 'gzip', 'HTTP_CONNECTION': 'close', 'HTTP_CONTENT_TYPE': 'text/html', 'HTTP_KEEP_ALIVE': 'foo', 'HTTP_PROXY_AUTHORIZATION': 'me', 'HTTP_TE': 'deflate', 'HTTP_TRAILER': 'X-Bar', 'HTTP_TRANSFER_ENCODING': 'chunked', 'HTTP_X_FOO': 'bar'} expected_environ = {'HTTP_CONTENT_TY...
'Tests when the \'Content-Length\' header needs to be updated.'
def test_content_length_rewrite(self):
application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html'), ('Cache-Control', 'no-cache'), ('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'), ('Content-Length', '1234')], 'this is my data') expected_status = '200 OK' expected_headers = {'Content-Type': 'text...
'Tests that a response that is too big is rejected.'
def test_too_big_rewrite(self):
application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/plain'), ('Cache-Control', 'no-cache'), ('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'), ('Content-Length', '1234')], ('x' * 33554433)) expected_status = '500 Internal Server Error' expected_headers = {'Cont...
'Tests that a HEAD request does not delete or alter the Content-Length.'
def test_head_method_preserves_content_length(self):
environ = {'REQUEST_METHOD': 'HEAD'} application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html'), ('Cache-Control', 'no-cache'), ('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'), ('Content-Length', '1234')], 'this is my data') expected_status = '200 OK' ...
'Tests that the default Content-Type header is applied.'
def test_default_content_type(self):
application = wsgi_test_utils.constant_app('200 OK', [('Cache-Control', 'no-cache'), ('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT')], 'this is my data') expected_status = '200 OK' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache', 'Expires': 'Fri, 01...
'Tests when the \'cache-control\' header needs to be updated.'
def test_cache_control_rewrite(self):
application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html')], 'this is my data') expected_status = '200 OK' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache', 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT', 'Content-Length': '15'} ...
'Tests that the user is able to manually set Cache-Control and Expires.'
def test_manual_cache_control(self):
application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html'), ('Cache-Control', 'max-age'), ('Expires', 'Mon, 25 Jul 9999 14:47:05 GMT')], 'this is my data') expected_status = '200 OK' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'max...
'Tests that the user is able to set Cache-Control without Expires.'
def test_manual_cache_control_not_expires(self):
application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html'), ('Cache-Control', 'max-age')], 'this is my data') expected_status = '200 OK' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'max-age', 'Content-Length': '15'} expected_body = 'this i...
'Tests that the user is able to set Expires without Cache-Control.'
def test_manual_expires(self):
application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html'), ('Expires', 'Wed, 25 Jul 2012 14:47:05 GMT')], 'this is my data') expected_status = '200 OK' expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache', 'Expires': 'Wed, 25...
'Tests that the Set-Cookie header prevents caching from taking place.'
def test_set_cookie_prevents_caching(self):
m = mox.Mox() m.StubOutWithMock(time, 'time') time.time().AndReturn(788918400) m.ReplayAll() application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html'), ('Set-Cookie', 'UserID=john; Max-Age=3600; Version=1')], 'this is my data') expected_status = '200 ...
'Tests rewriting when the status is not allowed to have a body.'
def _run_no_body_status_test(self, status):
application = wsgi_test_utils.constant_app(status, [('Content-Type', 'text/html'), ('Content-Length', '1234')], 'this is my data') expected_status = status expected_headers = {'Content-Type': 'text/html'} expected_body = '' self.assert_rewritten_response(expected_status, expected_headers, e...
'Tests rewriting when the status is 100.'
def test_no_body_100(self):
self._run_no_body_status_test('100 Continue')
'Tests rewriting when the status is 101.'
def test_no_body_101(self):
self._run_no_body_status_test('101 Switching Protocols')
'Tests rewriting when the status is 204.'
def test_no_body_204(self):
self._run_no_body_status_test('204 No Content')
'Tests rewriting when the status is 304.'
def test_no_body_304(self):
self._run_no_body_status_test('304 Not Modified')
'Tests when nothing gets rewritten.'
def test_no_rewrite(self):
application = wsgi_test_utils.constant_app('200 OK', [('Content-Type', 'text/html'), ('Cache-Control', 'no-cache'), ('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'), ('Content-Length', '15')], 'this is my data') expected_status = '200 OK' expected_headers = {'Content-Type': 'text/h...
'Tests that unsafe headers are deleted.'
def test_header_sanitation(self):
application = wsgi_test_utils.constant_app('200 OK', [('Server', 'iis'), ('Date', 'sometime in the summer'), ('Content-Type', 'text/html'), ('Cache-Control', 'no-cache'), ('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'), ('Content-Length', '1500'), ('Content-Encoding', 'gzip'), ('Accept-Encod...
'Tests the _get_module method with no modules.'
def test_get_module_no_modules(self):
self.dispatcher._module_name_to_module = {} self.assertRaises(request_info.ModuleDoesNotExistError, self.dispatcher._get_module, None, None)
'Tests the _get_module method with a default module.'
def test_get_module_default_module(self):
self.dispatcher._module_name_to_module = {'default': self.module1} self.assertEqual(self.dispatcher._get_module(None, None), self.module1) self.dispatcher._module_name_to_module['nondefault'] = self.module2 self.assertEqual(self.dispatcher._get_module(None, None), self.module1) self.dispatcher._modu...
'Tests the _get_module method with a non-default module.'
def test_get_module_non_default(self):
self.dispatcher._module_name_to_module = {'default': self.module1, 'nondefault': self.module2} self.assertEqual(self.dispatcher._get_module('nondefault', None), self.module2)
'Tests the _get_module method with no default module.'
def test_get_module_no_default(self):
self.dispatcher._module_name_to_module = {'nondefault': self.module1} self.assertEqual(self.dispatcher._get_module('nondefault', None), self.module1) self.assertEqual(self.dispatcher._get_module(None, None), self.module1)
'Initializer for URLHandler. Args: url_pattern: A re.RegexObject that matches URLs that should be handled by this handler. It may also optionally bind groups.'
def __init__(self, url_pattern):
self._url_pattern = url_pattern
'Tests whether a given URL string matches this handler. Args: url: A URL string to match. Returns: A re.MatchObject containing the result of the match, if the URL string matches this handler. None, otherwise.'
def match(self, url):
return self._url_pattern.match(url)
'Handles the response if the user is not authorized to access this URL. If the user is authorized, this method returns None without side effects. The default behaviour is to always authorize the user. If the user is not authorized, this method acts as a WSGI handler, calling the start_response function and returning th...
def handle_authorization(self, environ, start_response):
return None
'Serves the content associated with this handler. Args: match: The re.MatchObject containing the result of matching the URL against this handler\'s URL pattern. 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...
def handle(self, match, environ, start_response):
raise NotImplementedError()
'Initializer for UserConfiguredURLHandler. Args: url_map: An appinfo.URLMap instance containing the configuration for this handler. url_pattern: A re.RegexObject that matches URLs that should be handled by this handler. It may also optionally bind groups.'
def __init__(self, url_map, url_pattern):
super(UserConfiguredURLHandler, self).__init__(url_pattern) self._url_map = url_map
'Handles the response if the user is not authorized to access this URL. The authorization check is based on the \'login\' setting for this handler, configured by the supplied url_map. Args: environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-3...
def handle_authorization(self, environ, start_response):
admin_only = (self._url_map.login == appinfo.LOGIN_ADMIN) requires_login = ((self._url_map.login == appinfo.LOGIN_REQUIRED) or admin_only) auth_fail_action = self._url_map.auth_fail_action cookies = environ.get('HTTP_COOKIE') (email_addr, admin, _) = login.get_user_info(cookies) if (constants.FA...
'Setup a mox expectation to images_stub._OpenImageData.'
def expect_open_image(self, blob_key, dimensions=None, throw_exception=None, mime_type='JPEG'):
image_data = images_service_pb.ImageData() image_data.set_blob_key(blob_key) self._image.format = mime_type if throw_exception: self._images_stub._OpenImageData(image_data).AndRaise(throw_exception) else: self._images_stub._OpenImageData(image_data).AndReturn(self._image) sel...
'Setup a mox expectation to images_stub._Crop.'
def expect_crop(self, left_x=None, right_x=None, top_y=None, bottom_y=None):
crop_xform = images_service_pb.Transform() if (left_x is not None): if (not isinstance(left_x, float)): raise self.failureException('Crop argument must be a float.') crop_xform.set_crop_left_x(left_x) if (right_x is not None): if (not isinstance(right_x, fl...
'Setup a mox expectation to images_stub._Resize.'
def expect_resize(self, resize):
resize_xform = images_service_pb.Transform() resize_xform.set_width(resize) resize_xform.set_height(resize) self._images_stub._Resize(mox.IsA(Image.Image), resize_xform).AndReturn(self._image)
'Setup a mox expectation to images_stub._EncodeImage.'
def expect_encode_image(self, data, mime_type=images_service_pb.OutputSettings.JPEG):
output_settings = images_service_pb.OutputSettings() output_settings.set_mime_type(mime_type) self._images_stub._EncodeImage(mox.IsA(Image.Image), output_settings).AndReturn(data)
'Setup a mox expectation to datastore.Get.'
def expect_datatore_lookup(self, blob_key, expected_result):
self.mox.StubOutWithMock(datastore, 'Get') blob_url = datastore.Entity('__BlobServingUrl__', name=blob_key) if expected_result: datastore.Get(blob_url.key()).AndReturn(True) else: datastore.Get(blob_url.key()).AndRaise(datastore_errors.EntityNotFoundError)
'Tests URL parsing.'
def test_parse_path(self):
self.assertEquals(('SomeBlobKey', ''), self.app._parse_path('http://test.com/_ah/img/SomeBlobKey')) self.assertEquals(('SomeBlobKey', ''), self.app._parse_path('/_ah/img/SomeBlobKey')) self.assertEquals(('SomeBlobKey', 's32'), self.app._parse_path('/_ah/img/SomeBlobKey=s32')) self.assertEquals(('SomeBlo...
'Tests Option parsing.'
def test_parse_options(self):
self.assertEquals((32, False), self.app._parse_options('s32')) self.assertEquals((32, True), self.app._parse_options('s32-c')) self.assertEquals((None, False), self.app._parse_options('')) self.assertEquals((None, False), self.app._parse_options('c-s32')) self.assertEquals((None, False), self.app._p...
'Tests OpenImage raises an exception.'
def test_open_image_throws(self):
self.expect_open_image('SomeBlobKey', throw_exception=apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.INVALID_BLOB_KEY)) self.mox.ReplayAll() try: self.app._transform_image('SomeBlobKey', '') raise self.failureException('Should have thrown ApplicationError') ...
'Tests no resizing.'
def test_transform_image_no_resize(self):
self.expect_open_image('SomeBlobKey', (1600, 1200)) self.expect_resize(blob_image._DEFAULT_SERVING_SIZE) self.expect_encode_image('SomeImageInJpeg') self.mox.ReplayAll() self.assertEquals(('SomeImageInJpeg', 'image/jpeg'), self.app._transform_image('SomeBlobKey', '')) self.mox.VerifyAll()
'Tests that an image smaller than default serving size is not upsized.'
def test_transform_image_not_upscaled(self):
self.expect_open_image('SomeBlobKey', (400, 300)) self.expect_encode_image('SomeImageInJpeg') self.mox.ReplayAll() self.assertEquals(('SomeImageInJpeg', 'image/jpeg'), self.app._transform_image('SomeBlobKey', '')) self.mox.VerifyAll()
'Tests no resizing in PNG.'
def test_transform_image_no_resize_png(self):
self.expect_open_image('SomeBlobKey', (1600, 1200), mime_type='PNG') self.expect_resize(blob_image._DEFAULT_SERVING_SIZE) self.expect_encode_image('SomeImageInPng', images_service_pb.OutputSettings.PNG) self.mox.ReplayAll() self.assertEquals(('SomeImageInPng', 'image/png'), self.app._transform_image...
'Tests no resizing in TIFF.'
def test_transform_image_no_resize_tiff(self):
self.expect_open_image('SomeBlobKey', (1600, 1200), mime_type='TIFF') self.expect_resize(blob_image._DEFAULT_SERVING_SIZE) self.expect_encode_image('SomeImageInJpeg') self.mox.ReplayAll() self.assertEquals(('SomeImageInJpeg', 'image/jpeg'), self.app._transform_image('SomeBlobKey', '')) self.mox....
'Tests no resizing in GIF.'
def test_transform_image_no_resize_gif(self):
self.expect_open_image('SomeBlobKey', (1600, 1200), mime_type='GIF') self.expect_resize(blob_image._DEFAULT_SERVING_SIZE) self.expect_encode_image('SomeImageInPng', images_service_pb.OutputSettings.PNG) self.mox.ReplayAll() self.assertEquals(('SomeImageInPng', 'image/png'), self.app._transform_image...
'Tests resizing.'
def test_transform_image_resize(self):
self.expect_open_image('SomeBlobKey', (1600, 1200)) self.expect_resize(32) self.expect_encode_image('SomeImageSize32') self.mox.ReplayAll() self.assertEquals(('SomeImageSize32', 'image/jpeg'), self.app._transform_image('SomeBlobKey', 's32')) self.mox.VerifyAll()
'Tests that s0 parameter serves image at the original size.'
def test_transform_image_original_size(self):
self.expect_open_image('SomeBlobKey', (1600, 1200)) self.expect_encode_image('SomeImageInJpeg') self.mox.ReplayAll() self.assertEquals(('SomeImageInJpeg', 'image/jpeg'), self.app._transform_image('SomeBlobKey', 's0')) self.mox.VerifyAll()
'Tests resizing.'
def test_transform_image_resize_png(self):
self.expect_open_image('SomeBlobKey', (1600, 1200), mime_type='PNG') self.expect_resize(32) self.expect_encode_image('SomeImageSize32', images_service_pb.OutputSettings.PNG) self.mox.ReplayAll() self.assertEquals(('SomeImageSize32', 'image/png'), self.app._transform_image('SomeBlobKey', 's32')) ...
'Tests resizing and cropping on a portrait image.'
def test_transform_image_resize_and_crop_portrait(self):
self.expect_open_image('SomeBlobKey', (148, 215)) self.expect_crop(top_y=0.0, bottom_y=0.6883720930232557) self.expect_resize(32) self.expect_encode_image('SomeImageSize32-c') self.mox.ReplayAll() self.assertEquals(('SomeImageSize32-c', 'image/jpeg'), self.app._transform_image('SomeBlobKey', 's3...
'Tests resizing and cropping on a portrait PNG image.'
def test_transform_image_resize_and_crop_portrait_png(self):
self.expect_open_image('SomeBlobKey', (1600, 1200), mime_type='PNG') self.expect_crop(left_x=0.125, right_x=0.875) self.expect_resize(32) self.expect_encode_image('SomeImageSize32-c', images_service_pb.OutputSettings.PNG) self.mox.ReplayAll() self.assertEquals(('SomeImageSize32-c', 'image/png'),...
'Tests resizing and cropping on a landscape image.'
def test_transform_image_resize_and_crop_landscape(self):
self.expect_open_image('SomeBlobKey', (1200, 1600)) self.expect_crop(top_y=0.0, bottom_y=0.75) self.expect_resize(32) self.expect_encode_image('SomeImageSize32-c') self.mox.ReplayAll() self.assertEquals(('SomeImageSize32-c', 'image/jpeg'), self.app._transform_image('SomeBlobKey', 's32-c')) s...
'Tests an image request.'
def test_basic_run(self):
self.expect_datatore_lookup('SomeBlobKey', True) self.expect_open_image('SomeBlobKey', (1600, 1200)) self.expect_resize(blob_image._DEFAULT_SERVING_SIZE) self.expect_encode_image('SomeImageInJpeg') self.run_request('image/jpeg', 'SomeImageInJpeg')
'Tests an image request for a PNG image.'
def test_basic_run_png(self):
self.expect_datatore_lookup('SomeBlobKey', True) self.expect_open_image('SomeBlobKey', (1600, 1200), mime_type='PNG') self.expect_resize(blob_image._DEFAULT_SERVING_SIZE) self.expect_encode_image('SomeImageInPng', images_service_pb.OutputSettings.PNG) self.run_request('image/png', 'SomeImageInPng')
'Tests an image request with a padded blobkey.'
def test_basic_run_with_padded_blobkey(self):
padded_blobkey = 'SomeBlobKey=====================' self.expect_datatore_lookup(padded_blobkey, True) self.expect_open_image(padded_blobkey, (1600, 1200)) self.expect_resize(blob_image._DEFAULT_SERVING_SIZE) self.expect_encode_image('SomeImageInJpeg') self.mox.ReplayAll() self._environ['PATH...