def test_multiple_file_uploads_with_filename_and_contents(self): uploaded_file1_name = os.path.join(os.path.dirname(__file__), "__init__.py") uploaded_file1_contents = open(uploaded_file1_name).read() if PY3: uploaded_file1_contents = to_bytes(uploaded_file1_contents) uploaded_file2_name = __file__ uploaded_file2_name = os.path.join(os.path.dirname(__file__), 'html', "404.html") uploaded_file2_contents = open(uploaded_file2_name).read() if PY3: uploaded_file2_contents = to_bytes(uploaded_file2_contents) app = webtest.TestApp(MultipleUploadFileApp()) res = app.get('/') self.assertEqual(res.status_int, 200) self.assertEqual(res.headers['content-type'], 'text/html; charset=utf-8') self.assertEqual(res.content_type, 'text/html') single_form = res.forms["file_upload_form"] single_form.set("file-field-1", (uploaded_file1_name, uploaded_file1_contents)) single_form.set("file-field-2", (uploaded_file2_name, uploaded_file2_contents)) display = single_form.submit("button") self.assertFile(uploaded_file1_name, uploaded_file1_contents, display) self.assertFile(uploaded_file1_name, uploaded_file1_contents, display)
def upload_binary_app(environ, start_response): req = Request(environ) status = "200 OK" if req.method == "GET": body = to_bytes(""" <html> <head><title>form page</title></head> <body> <form method="POST" id="binary_upload_form" enctype="multipart/form-data"> <input name="binary-file-field" type="file" /> <input name="button" type="submit" value="binary" /> </form> </body> </html> """) else: uploaded_files = req.POST.getall("binary-file-field") data = [str(n) for n in struct.unpack('255h', uploaded_files[0].value)] body = to_bytes(""" <html> <head><title>display page</title></head> <body> %s </body> </html> """ % join_bytes(',', data)) headers = [('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(body)))] start_response(status, headers) return [body]
def application_exc_info(environ, start_response): body = to_bytes('body stuff') headers = [ ('Content-Type', 'text/plain; charset=utf-8'), ('Content-Length', str(len(body)))] start_response(to_bytes('200 OK'), headers, ('stuff',)) return [body]
def test_writelines(self): fake_error = self.FakeError() error_wrapper = ErrorWrapper(fake_error) data = [to_bytes('a line'), to_bytes('another line')] error_wrapper.writelines(data) self.assertEqual(fake_error.written, data, "ErrorWrapper should call original writer")
def upload_binary_app(environ, start_response): req = Request(environ) status = "200 OK" if req.method == "GET": body = to_bytes(""" <html> <head><title>form page</title></head> <body> <form method="POST" id="binary_upload_form" enctype="multipart/form-data"> <input name="binary-file-field" type="file" /> <input name="button" type="submit" value="binary" /> </form> </body> </html> """) else: uploaded_files = req.POST.getall("binary-file-field") data = [str(n) for n in struct.unpack('255h', uploaded_files[0].value)] body = to_bytes(""" <html> <head><title>display page</title></head> <body> %s </body> </html> """ % join_bytes(',', data)) headers = [ ('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(body)))] start_response(status, headers) return [body]
def test_multiple_file_uploads_with_filename_and_contents(self): uploaded_file1_name = \ os.path.join(os.path.dirname(__file__), "__init__.py") uploaded_file1_contents = open(uploaded_file1_name).read() if PY3: uploaded_file1_contents = to_bytes(uploaded_file1_contents) uploaded_file2_name = __file__ uploaded_file2_contents = open(uploaded_file2_name).read() if PY3: uploaded_file2_contents = to_bytes(uploaded_file2_contents) app = webtest.TestApp(multiple_upload_file_app) res = app.get('/') self.assertEqual(res.status_int, 200) self.assertEqual(res.headers['content-type'], 'text/html; charset=utf-8') self.assertEqual(res.content_type, 'text/html') single_form = res.forms["file_upload_form"] single_form.set("file-field-1", (uploaded_file1_name, uploaded_file1_contents)) single_form.set("file-field-2", (uploaded_file2_name, uploaded_file2_contents)) display = single_form.submit("button") self.assertIn("<p>You selected '%s'</p>" % uploaded_file1_name, display, display) self.assertIn("<p>with contents: '%s'</p>" % to_string(uploaded_file1_contents), display, \ display) self.assertIn("<p>You selected '%s'</p>" % uploaded_file2_name, display, display) self.assertIn("<p>with contents: '%s'</p>" % to_string(uploaded_file2_contents), display, \ display)
def application_exc_info(environ, start_response): body = to_bytes('body stuff') headers = [('Content-Type', 'text/plain; charset=utf-8'), ('Content-Length', str(len(body)))] # PEP 3333 requires native strings: headers = [(str(k), str(v)) for k, v in headers] start_response(to_bytes('200 OK'), headers, ('stuff', )) return [body]
def test_encode_multipart_content_type(self): data = self.app.encode_multipart([], [("file", "data.txt", six.b("data"), "text/x-custom-mime-type")]) self.assertIn(to_bytes("Content-Type: text/x-custom-mime-type"), data[-1]) data = self.app.encode_multipart( [("file", webtest.Upload("data.txt", six.b("data"), "text/x-custom-mime-type"))], [] ) self.assertIn(to_bytes("Content-Type: text/x-custom-mime-type"), data[-1])
def test_encode_multipart_content_type(self): data = self.app.encode_multipart( [], [('file', 'data.txt', six.b('data'), 'text/x-custom-mime-type')]) self.assertIn(to_bytes('Content-Type: text/x-custom-mime-type'), data[-1]) data = self.app.encode_multipart( [('file', webtest.Upload('data.txt', six.b('data'), 'text/x-custom-mime-type'))], []) self.assertIn(to_bytes('Content-Type: text/x-custom-mime-type'), data[-1])
def cookie_app(environ, start_response): req = Request(environ) status = to_bytes("200 OK") body = "Cookie." assert dict(req.cookies) == {"spam": "eggs"} assert environ["HTTP_COOKIE"] == "spam=eggs" headers = [("Content-Type", "text/html"), ("Content-Length", str(len(body)))] start_response(status, headers) return [to_bytes(body)]
def cookie_app3(environ, start_response): status = to_bytes("200 OK") body = 'Cookie: %(HTTP_COOKIE)s' % environ headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ] start_response(status, headers) return [to_bytes(body)]
def cookie_app(environ, start_response): status = to_bytes("200 OK") body = '' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ('Set-Cookie', 'spam=eggs; Expires=Tue, 21-Feb-2013 17:45:00 GMT;'), ] start_response(status, headers) return [to_bytes(body)]
def cookie_app(environ, start_response): status = to_bytes("200 OK") body = "Cookie." headers = [ ("Content-Type", "text/html"), ("Content-Length", str(len(body))), ("Set-Cookie", "spam=eggs; Domain=localhost;"), ] start_response(status, headers) return [to_bytes(body)]
def cookie_app(environ, start_response): status = to_bytes("200 OK") body = "" headers = [ ("Content-Type", "text/html"), ("Content-Length", str(len(body))), ("Set-Cookie", "spam=eggs; Expires=Tue, 21-Feb-2013 17:45:00 GMT;"), ] start_response(status, headers) return [to_bytes(body)]
def cookie_app(environ, start_response): req = Request(environ) self.assertEqual(req.cookies["foo"], "bar") self.assertEqual(req.cookies["fizz"], ";bar=baz") status = to_bytes("200 OK") body = "" headers = [("Content-Type", "text/html"), ("Content-Length", str(len(body)))] start_response(status, headers) return [to_bytes(body)]
def cookie_app(environ, start_response): status = to_bytes("200 OK") body = 'Cookie.' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ('Set-Cookie', 'spam=eggs; Domain=localhost;'), ] start_response(status, headers) return [to_bytes(body)]
def cookie_app(environ, start_response): status = to_bytes("200 OK") body = 'Cookie.' headers = [ ('Content-Type', 'text/plain'), ('Content-Length', str(len(body))), ('Set-Cookie', 'spam=eggs; secure; Domain=.example.org;'), ] start_response(status, headers) return [to_bytes(body)]
def cookie_app2(environ, start_response): status = to_bytes("200 OK") body = '' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ('Set-Cookie', 'spam=eggs'), ('Set-Cookie', 'foo="bar;baz"'), ] start_response(status, headers) return [to_bytes(body)]
def test_encode_multipart(self): data = self.app.encode_multipart([], [('file', 'data.txt', b'data')]) self.assertIn(to_bytes('data.txt'), data[-1]) data = self.app.encode_multipart([], [(b'file', b'data.txt', b'data')]) self.assertIn(to_bytes('data.txt'), data[-1]) data = self.app.encode_multipart([('key', 'value')], []) self.assertIn(to_bytes('name="key"'), data[-1]) data = self.app.encode_multipart([(b'key', b'value')], []) self.assertIn(to_bytes('name="key"'), data[-1])
def test_encode_multipart_content_type(self): data = self.app.encode_multipart( [], [('file', 'data.txt', b'data', 'text/x-custom-mime-type')]) self.assertIn(to_bytes('Content-Type: text/x-custom-mime-type'), data[-1]) data = self.app.encode_multipart( [('file', webtest.Upload('data.txt', b'data', 'text/x-custom-mime-type'))], []) self.assertIn(to_bytes('Content-Type: text/x-custom-mime-type'), data[-1])
def test_encode_multipart(self): data = self.app.encode_multipart([], [("file", "data.txt", six.b("data"))]) self.assertIn(to_bytes("data.txt"), data[-1]) data = self.app.encode_multipart([], [(six.b("file"), six.b("data.txt"), six.b("data"))]) self.assertIn(to_bytes("data.txt"), data[-1]) data = self.app.encode_multipart([("key", "value")], []) self.assertIn(to_bytes('name="key"'), data[-1]) data = self.app.encode_multipart([(six.b("key"), six.b("value"))], []) self.assertIn(to_bytes('name="key"'), data[-1])
def get_files_page(self, req): file_parts = [] uploaded_files = [(k, v) for k, v in req.POST.items() if 'file' in k] uploaded_files = sorted(uploaded_files) for name, uploaded_file in uploaded_files: filename = to_bytes(uploaded_file.filename) value = to_bytes(uploaded_file.value, 'ascii') file_parts.append(b""" <p>You selected '""" + filename + b"""'</p> <p>with contents: '""" + value + b"""'</p> """) return b''.join(file_parts)
def select_app_without_default(environ, start_response): req = Request(environ) status = b"200 OK" if req.method == "GET": body = to_bytes( """ <html> <head><title>form page</title></head> <body> <form method="POST" id="single_select_form"> <select id="single" name="single"> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> </select> <input name="button" type="submit" value="single"> </form> <form method="POST" id="multiple_select_form"> <select id="multiple" name="multiple" multiple="multiple"> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> <option value="11">Eleven</option> </select> <input name="button" type="submit" value="multiple"> </form> </body> </html> """ ) else: select_type = req.POST.get("button") if select_type == "single": selection = req.POST.get("single") elif select_type == "multiple": selection = ", ".join(req.POST.getall("multiple")) body = to_bytes( """ <html> <head><title>display page</title></head> <body> <p>You submitted the %(select_type)s </p> <p>You selected %(selection)s</p> </body> </html> """ % dict(selection=selection, select_type=select_type) ) headers = [("Content-Type", "text/html; charset=utf-8"), ("Content-Length", str(len(body)))] start_response(status, headers) return [body]
def cookie_app(environ, start_response): req = Request(environ) status = to_bytes("200 OK") body = 'Cookie.' assert dict(req.cookies) == {'spam': 'eggs'} assert environ['HTTP_COOKIE'] == 'spam=eggs' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ] start_response(status, headers) return [to_bytes(body)]
def select_app_without_default(environ, start_response): req = Request(environ) status = b"200 OK" if req.method == "GET": body = to_bytes(""" <html> <head><title>form page</title></head> <body> <form method="POST" id="single_select_form"> <select id="single" name="single"> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> </select> <input name="button" type="submit" value="single"> </form> <form method="POST" id="multiple_select_form"> <select id="multiple" name="multiple" multiple="multiple"> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> <option value="11">Eleven</option> </select> <input name="button" type="submit" value="multiple"> </form> </body> </html> """) else: select_type = req.POST.get("button") if select_type == "single": selection = req.POST.get("single") elif select_type == "multiple": selection = ", ".join(req.POST.getall("multiple")) body = to_bytes(""" <html> <head><title>display page</title></head> <body> <p>You submitted the %(select_type)s </p> <p>You selected %(selection)s</p> </body> </html> """ % dict(selection=selection, select_type=select_type)) headers = [ ('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(body)))] # PEP 3333 requires native strings: headers = [(str(k), str(v)) for k, v in headers] start_response(status, headers) return [body]
def cookie_app(environ, start_response): req = Request(environ) self.assertEqual(req.cookies['foo'], 'bar') self.assertEqual(req.cookies['fizz'], ';bar=baz') status = to_bytes("200 OK") body = '' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ] start_response(status, headers) return [to_bytes(body)]
def multiple_upload_file_app(environ, start_response): req = Request(environ) status = "200 OK" if req.method == "GET": body = to_bytes( """ <html> <head><title>form page</title></head> <body> <form method="POST" id="file_upload_form" enctype="multipart/form-data"> <input name="file-field-1" type="file" /> <input name="file-field-2" type="file" /> <input name="button" type="submit" value="single"> </form> </body> </html> """) else: uploaded_file_1 = req.POST.get("file-field-1") uploaded_file_2 = req.POST.get("file-field-2") uploaded_files = [uploaded_file_1, uploaded_file_2] body_head = to_bytes( """ <html> <head><title>display page</title></head> <body> """) file_parts = [] for uploaded_file in uploaded_files: print (to_bytes(uploaded_file.filename), type(uploaded_file.value)) file_parts.append( """ <p>You selected '%(filename)s'</p> <p>with contents: '%(value)s'</p> """ % dict(filename=to_string(uploaded_file.filename), value=to_string(uploaded_file.value))) body_foot = to_bytes( """ </body> </html> """) body = body_head + join_bytes("", file_parts) + body_foot headers = [ ('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(body)))] start_response(status, headers) return [body]
def test_submit_with_file_upload(self): uploaded_file_name = 'test.txt' uploaded_file_contents = 'test content file upload' if PY3: uploaded_file_contents = to_bytes(uploaded_file_contents) deform_upload_file_app = get_submit_app('deform', deform_upload_fields_text) app = webtest.TestApp(deform_upload_file_app) res = app.get('/') self.assertEqual(res.status_int, 200) self.assertEqual( res.headers['content-type'], 'text/html; charset=utf-8') self.assertEqual(res.content_type, 'text/html') self.assertEqual(res.charset, 'utf-8') single_form = res.forms["deform"] single_form.set("title", "testtitle") single_form.set("fileupload", (uploaded_file_name, uploaded_file_contents)) single_form.set("description", "testdescription") display = single_form.submit("Submit") self.assertIn(""" _charset_: __formid__:deform title:testtitle __start__:fileupload:mapping fileupload:test.txt:test content file upload __end__:fileupload:mapping description:testdescription Submit:Submit """.strip(), display, display)
def test_submit_with_file_upload(self): uploaded_file_name = 'test.txt' uploaded_file_contents = to_bytes('test content file upload') deform_upload_file_app = get_submit_app('deform', deform_upload_fields_text) app = webtest.TestApp(deform_upload_file_app) res = app.get('/') self.assertEqual(res.status_int, 200) self.assertEqual(res.headers['content-type'], 'text/html; charset=utf-8') self.assertEqual(res.content_type, 'text/html') self.assertEqual(res.charset, 'utf-8') single_form = res.forms["deform"] single_form.set("title", "testtitle") single_form.set("fileupload", (uploaded_file_name, uploaded_file_contents)) single_form.set("description", "testdescription") display = single_form.submit("Submit") self.assertIn( """ _charset_: __formid__:deform title:testtitle __start__:fileupload:mapping fileupload:test.txt:test content file upload __end__:fileupload:mapping description:testdescription Submit:Submit """.strip(), display, display)
def test_post_with_file_upload(self): uploaded_file_name = 'test.txt' uploaded_file_contents = to_bytes('test content file upload') deform_upload_file_app = get_submit_app('deform', deform_upload_fields_text) app = webtest.TestApp(deform_upload_file_app) display = app.post( "/", OrderedDict([('_charset_', ''), ('__formid__', 'deform'), ('title', 'testtitle'), ('__start__', 'fileupload:mapping'), ('fileupload', webtest.Upload(uploaded_file_name, uploaded_file_contents)), ('__end__', 'fileupload:mapping'), ('description', 'testdescription'), ('Submit', 'Submit')])) self.assertIn( """ _charset_: __formid__:deform title:testtitle __start__:fileupload:mapping fileupload:test.txt:test content file upload __end__:fileupload:mapping description:testdescription Submit:Submit""".strip(), display, display)
def input_app(environ, start_response): req = Request(environ) status = "200 OK" body = to_bytes( """ <html> <head><title>form page</title></head> <body> <form method="POST" id="text_input_form"> <input name="foo" type="text" value="bar"> <input name="button" type="submit" value="text"> </form> <form method="POST" id="radio_input_form"> <input name="foo" type="radio" value="bar"> <input name="foo" type="radio" value="baz" checked> <input name="button" type="submit" value="radio"> </form> <form method="POST" id="checkbox_input_form"> <input name="foo" type="checkbox" value="bar" checked> <input name="button" type="submit" value="text"> </form> <form method="POST" id="textarea_input_form"> <textarea name="textarea">'foo&bar'</textarea> </form> </body> </html> """) headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body)))] start_response(status, headers) return [body]
def test_post_with_file_upload(self): uploaded_file_name = 'test.txt' uploaded_file_contents = 'test content file upload' if PY3: uploaded_file_contents = to_bytes(uploaded_file_contents) deform_upload_file_app = get_submit_app('deform', deform_upload_fields_text) app = webtest.TestApp(deform_upload_file_app) display = app.post("/", OrderedDict([ ('_charset_', ''), ('__formid__', 'deform'), ('title', 'testtitle'), ('__start__', 'fileupload:mapping'), ('fileupload', webtest.Upload(uploaded_file_name, uploaded_file_contents)), ('__end__', 'fileupload:mapping'), ('description', 'testdescription'), ('Submit', 'Submit')])) self.assertIn(""" _charset_: __formid__:deform title:testtitle __start__:fileupload:mapping fileupload:test.txt:test content file upload __end__:fileupload:mapping description:testdescription Submit:Submit""".strip(), display, display)
def set_authorization(self, value): self.authorization_value = value if value is not None: invalid_value = ( "You should use a value like ('Basic', ('user', 'password'))" " OR ('Bearer', 'token') OR ('JWT', 'token')" ) if isinstance(value, (list, tuple)) and len(value) == 2: authtype, val = value if authtype == 'Basic' and val and \ isinstance(val, (list, tuple)): val = ':'.join(list(val)) val = b64encode(to_bytes(val)).strip() val = val.decode('latin1') elif authtype in ('Bearer', 'JWT') and val and \ isinstance(val, (str, text_type)): val = val.strip() else: raise ValueError(invalid_value) value = str('%s %s' % (authtype, val)) else: raise ValueError(invalid_value) self.extra_environ.update({ 'HTTP_AUTHORIZATION': value, }) else: if 'HTTP_AUTHORIZATION' in self.extra_environ: del self.extra_environ['HTTP_AUTHORIZATION']
def set_authorization(self, value): self.authorization_value = value if value is not None: invalid_value = ( "You should use a value like ('Basic', ('user', 'password')) OR ('Bearer', 'token')" ) if isinstance(value, (list, tuple)) and len(value) == 2: authtype, val = value if authtype == 'Basic' and val and \ isinstance(val, (list, tuple)): val = ':'.join(list(val)) val = b64encode(to_bytes(val)).strip() val = val.decode('latin1') elif authtype == 'Bearer' and val and \ isinstance(val, (str, text_type)): val = val.strip() else: raise ValueError(invalid_value) value = str('%s %s' % (authtype, val)) else: raise ValueError(invalid_value) self.extra_environ.update({ 'HTTP_AUTHORIZATION': value, }) else: if 'HTTP_AUTHORIZATION' in self.extra_environ: del self.extra_environ['HTTP_AUTHORIZATION']
def test_encode_multipart(self): data = self.app.encode_multipart( [], [('file', 'data.txt', six.b('data'))]) self.assertIn(to_bytes('data.txt'), data[-1]) data = self.app.encode_multipart( [], [(six.b('file'), six.b('data.txt'), six.b('data'))]) self.assertIn(to_bytes('data.txt'), data[-1]) data = self.app.encode_multipart( [('key', 'value')], []) self.assertIn(to_bytes('name="key"'), data[-1]) data = self.app.encode_multipart( [(six.b('key'), six.b('value'))], []) self.assertIn(to_bytes('name="key"'), data[-1])
def input_app_without_default(environ, start_response): Request(environ) status = b"200 OK" body = to_bytes( """ <html> <head><title>form page</title></head> <body> <form method="POST" id="text_input_form"> <input name="foo" type="text"> <input name="button" type="submit" value="text"> </form> <form method="POST" id="radio_input_form"> <input name="foo" type="radio" value="bar"> <input name="foo" type="radio" value="baz"> <input name="button" type="submit" value="radio"> </form> <form method="POST" id="checkbox_input_form"> <input name="foo" type="checkbox" value="bar"> <input name="button" type="submit" value="text"> </form> </body> </html> """) headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body)))] start_response(status, headers) return [body]
def submit_app(environ, start_response): req = Request(environ) status = "200 OK" if req.method == "GET": body = to_bytes(""" <html> <head><title>form page</title></head> <body> <form id="%s" action="" method="POST" enctype="multipart/form-data" accept-charset="utf-8"> %s </form> </body> </html> """ % (form_id, form_fields_text)) else: body_head = to_bytes(""" <html> <head><title>display page</title></head> <body> """) body_parts = [] for (name, value) in req.POST.items(): if hasattr(value, 'filename'): body_parts.append( "%s:%s:%s\n" % (to_string(name), to_string( value.filename), to_string(value.value))) else: body_parts.append("%s:%s\n" % (to_string(name), to_string(value))) body_foot = to_bytes(""" </body> </html> """) body = body_head + join_bytes("", body_parts) + body_foot headers = [('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(body)))] start_response(status, headers) assert (isinstance(body, binary_type)) return [body]
def links_app(environ, start_response): req = Request(environ) status = "200 OK" responses = { '/': """ <html> <head><title>page with links</title></head> <body> <a href="/foo/">Foo</a> <a href='bar'>Bar</a> <a href='baz/' id='id_baz'>Baz</a> <a href='#' id='fake_baz'>Baz</a> <a href='javascript:alert("123")' id='js_baz'>Baz</a> <script> var link = "<a href='/boo/'>Boo</a>"; </script> <a href='/spam/'>Click me!</a> <a href='/egg/'>Click me!</a> </body> </html> """, '/foo/': '<html><body>This is foo. <a href="bar">Bar</a> </body></html>', '/foo/bar': '<html><body>This is foobar.</body></html>', '/bar': '<html><body>This is bar.</body></html>', '/baz/': '<html><body>This is baz.</body></html>', '/spam/': '<html><body>This is spam.</body></html>', '/egg/': '<html><body>Just eggs.</body></html>', '/utf8/': u(""" <html> <head><title>Тестовая страница</title></head> <body> <a href='/foo/'>Менделеев</a> <a href='/baz/' title='Поэт'>Пушкин</a> <img src='/egg/' title='Поэт'> <script> var link = "<a href='/boo/'>Злодейская ссылка</a>"; </script> </body> </html> """).encode('utf8'), } utf8_paths = ['/utf8/'] body = responses[u(req.path_info)] headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(body)))] if req.path_info in utf8_paths: headers[0] = ('Content-Type', 'text/html; charset=utf-8') start_response(status, headers) return [to_bytes(body)]
def get_files_page(self, req): file_parts = [] uploaded_files = [(k, v) for k, v in req.POST.items() if 'file' in k] uploaded_files = sorted(uploaded_files) for name, uploaded_file in uploaded_files: if isinstance(uploaded_file, cgi.FieldStorage): filename = to_bytes(uploaded_file.filename) value = to_bytes(uploaded_file.value, 'ascii') content_type = to_bytes(uploaded_file.type, 'ascii') else: filename = value = content_type = b'' file_parts.append(b""" <p>You selected '""" + filename + b"""'</p> <p>with contents: '""" + value + b"""'</p> <p>with content type: '""" + content_type + b"""'</p> """) return b''.join(file_parts)
def get_files_page(self, req): uploaded_files = [(k, v) for k, v in req.POST.items() if "file" in k] data = uploaded_files[0][1].value if PY3: data = struct.unpack(b"255h", data[:510]) else: data = struct.unpack(str("255h"), data) return b",".join([to_bytes(str(i)) for i in data])
def get_files_page(self, req): uploaded_files = [(k, v) for k, v in req.POST.items() if 'file' in k] data = uploaded_files[0][1].value if PY3: data = struct.unpack(b'255h', data[:510]) else: data = struct.unpack(str('255h'), data) return b','.join([to_bytes(str(i)) for i in data])
def _gen_request(self, method, url, params=utils.NoDefault, headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None): """ Do a generic request. """ environ = self._make_environ(extra_environ) inline_uploads = [] # this supports OrderedDict if isinstance(params, dict) or hasattr(params, 'items'): params = list(params.items()) if isinstance(params, (list, tuple)): inline_uploads = [ v for (k, v) in params if isinstance(v, (forms.File, forms.Upload)) ] if len(inline_uploads) > 0: content_type, params = self.encode_multipart( params, upload_files or ()) environ['CONTENT_TYPE'] = content_type else: params = utils.encode_params(params, content_type) if upload_files or \ (content_type and to_bytes(content_type).startswith(b'multipart')): params = urlparse.parse_qsl(params, keep_blank_values=True) content_type, params = self.encode_multipart( params, upload_files or ()) environ['CONTENT_TYPE'] = content_type elif params: environ.setdefault('CONTENT_TYPE', str('application/x-www-form-urlencoded')) if content_type is not None: environ['CONTENT_TYPE'] = content_type environ['REQUEST_METHOD'] = str(method) url = str(url) url = self._remove_fragment(url) req = self.RequestClass.blank(url, environ) if isinstance(params, text_type): params = params.encode(req.charset or 'utf8') req.environ['wsgi.input'] = BytesIO(params) req.content_length = len(params) if headers: req.headers.update(headers) return self.do_request(req, status=status, expect_errors=expect_errors)
def multiple_upload_file_app(environ, start_response): req = Request(environ) status = "200 OK" if req.method == "GET": body = to_bytes(""" <html> <head><title>form page</title></head> <body> <form method="POST" id="file_upload_form" enctype="multipart/form-data"> <input name="file-field-1" type="file" /> <input name="file-field-2" type="file" /> <input name="button" type="submit" value="single"> </form> </body> </html> """) else: uploaded_file_1 = req.POST.get("file-field-1") uploaded_file_2 = req.POST.get("file-field-2") uploaded_files = [uploaded_file_1, uploaded_file_2] body_head = to_bytes(""" <html> <head><title>display page</title></head> <body> """) file_parts = [] for uploaded_file in uploaded_files: print(to_bytes(uploaded_file.filename), type(uploaded_file.value)) file_parts.append(""" <p>You selected '%(filename)s'</p> <p>with contents: '%(value)s'</p> """ % dict(filename=to_string(uploaded_file.filename), value=to_string(uploaded_file.value))) body_foot = to_bytes(""" </body> </html> """) body = body_head + join_bytes("", file_parts) + body_foot headers = [('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', str(len(body)))] start_response(status, headers) return [body]
def _gen_request(self, method, url, params=utils.NoDefault, headers=None, extra_environ=None, status=None, upload_files=None, expect_errors=False, content_type=None): """ Do a generic request. """ if method == 'DELETE' and params is not utils.NoDefault: warnings.warn(('You are not supposed to send a body in a ' 'DELETE request. Most web servers will ignore it'), lint.WSGIWarning) environ = self._make_environ(extra_environ) inline_uploads = [] # this supports OrderedDict if isinstance(params, dict) or hasattr(params, 'items'): params = list(params.items()) if isinstance(params, (list, tuple)): inline_uploads = [v for (k, v) in params if isinstance(v, (forms.File, forms.Upload))] if len(inline_uploads) > 0: content_type, params = self.encode_multipart( params, upload_files or ()) environ['CONTENT_TYPE'] = content_type else: params = utils.encode_params(params, content_type) if upload_files or \ (content_type and to_bytes(content_type).startswith(b'multipart')): params = cgi.parse_qsl(params, keep_blank_values=True) content_type, params = self.encode_multipart( params, upload_files or ()) environ['CONTENT_TYPE'] = content_type elif params: environ.setdefault('CONTENT_TYPE', str('application/x-www-form-urlencoded')) if content_type is not None: environ['CONTENT_TYPE'] = content_type environ['REQUEST_METHOD'] = str(method) url = str(url) url = self._remove_fragment(url) req = self.RequestClass.blank(url, environ) if isinstance(params, text_type): params = params.encode(req.charset or 'utf8') req.environ['wsgi.input'] = BytesIO(params) req.content_length = len(params) if headers: req.headers.update(headers) return self.do_request(req, status=status, expect_errors=expect_errors)
def application(environ, start_response): req = Request(environ) if req.path_info == '/redirect': req.path_info = '/path' resp = Response() resp.status = '302 Found' resp.location = req.path else: resp = Response() resp.body = to_bytes( '<html><body><a href="%s">link</a></body></html>' % req.path) return resp(environ, start_response)
def test_testing(self): res = self.app.get('/') self.assertEqual(res.status_int, 200) self.assertEqual(res.headers['content-type'], 'text/plain') self.assertEqual(res.content_type, 'text/plain') res = self.app.request('/', method='GET') self.assertEqual(res.status_int, 200) self.assertEqual(res.headers['content-type'], 'text/plain') self.assertEqual(res.content_type, 'text/plain') res = self.app.head('/') self.assertEqual(res.status_int, 200) self.assertEqual(res.headers['content-type'], 'text/plain') self.assertTrue(res.content_length > 0) self.assertEqual(res.body, to_bytes(''))
def cookie_app(environ, start_response): req = Request(environ) status = "200 OK" body = '<html><body><a href="/go/">go</a></body></html>' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ] if req.path_info != '/go/': headers.extend([ ('Set-Cookie', 'spam=eggs'), ('Set-Cookie', 'foo="bar;baz"'), ]) start_response(status, headers) return [to_bytes(body)]
def run(script, *args): dirname = os.path.dirname(sys._getframe(1).f_code.co_filename) script = os.path.join(dirname, script) if binary: cmd = [binary, 'test'] + list(args) + [script] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() output = p.stdout.read() if to_bytes('FAIL') in output: print(to_string(output)) raise AssertionError('Failure while running %s' % ' '.join(cmd))