def check_content_type(status, headers): code = int(status.split(None, 1)[0]) # @@: need one more person to verify this interpretation of RFC 2616 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html NO_MESSAGE_BODY = (201, 204, 304) NO_MESSAGE_TYPE = (204, 304) length = None for name, value in headers: str_name = to_string(name) if str_name.lower() == 'content-length' and value.isdigit(): length = int(value) for name, value in headers: str_name = to_string(name) if str_name.lower() == 'content-type': if code not in NO_MESSAGE_TYPE: return elif length == 0: warnings.warn(("Content-Type header found in a %s response, " "which not return content.") % code, WSGIWarning) return else: assert 0, (("Content-Type header found in a %s response, " "which must not return content.") % code) if code not in NO_MESSAGE_BODY and length is not None and length > 0: assert 0, "No Content-Type header found in headers (%s)" % headers
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 _update_environ(self, environ, user): if user: environ = environ or {} if isinstance(user, User): environ['WEBTEST_USER'] = to_string(user.username) else: environ['WEBTEST_USER'] = to_string(user) return environ
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 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 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 check_headers(headers): assert type(headers) is list, ( "Headers (%r) must be of type list: %r" % (headers, type(headers))) for item in headers: assert type(item) is tuple, ( "Individual headers (%r) must be of type tuple: %r" % (item, type(item))) assert len(item) == 2 name, value = item if type(name) is str: try: name.encode('latin1') except UnicodeEncodeError: raise AssertionError(( "Headers name must be latin1 string or bytes." "%r is not a valid latin1 string" % (name,))) str_name = to_string(name) assert str_name.lower() != 'status', ( "The Status header cannot be used; it conflicts with CGI " "script, and HTTP status is not given through headers " "(value: %r)." % value) assert '\n' not in str_name and ':' not in str_name, ( "Header names may not contain ':' or '\\n': %r" % name) assert header_re.search(str_name), "Bad header name: %r" % name assert not str_name.endswith('-') and not str_name.endswith('_'), ( "Names may not end in '-' or '_': %r" % name) if type(value) is str: try: value.encode('latin1') except UnicodeEncodeError: raise AssertionError(( "Headers values must be latin1 string or bytes." "%r is not a valid latin1 string" % (value,))) str_value = to_string(value) assert not bad_header_value_re.search(str_value), ( "Bad header value: %r (bad char: %r)" % (str_value, bad_header_value_re.search(str_value).group(0)))
def do_request(self, req, status, expect_errors): req.environ.setdefault('REMOTE_ADDR', '127.0.0.1') # is this a workaround for https://code.djangoproject.com/ticket/11111 ? req.environ['REMOTE_ADDR'] = to_string(req.environ['REMOTE_ADDR']) req.environ['PATH_INFO'] = to_string(req.environ['PATH_INFO']) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = curry(store_rendered_templates, data) template_rendered.connect(on_template_render) response = super(DjangoTestApp, self).do_request(req, status, expect_errors) # Add any rendered template detail to the response. # If there was only one template rendered (the most likely case), # flatten the list to a single element. def flattend(detail): if len(data[detail]) == 1: return data[detail][0] return data[detail] response.context = None response.template = None response.templates = data.get('templates', None) if data.get('context'): response.context = flattend('context') if data.get('template'): response.template = flattend('template') elif data.get('templates'): response.template = flattend('templates') response.__class__ = DjangoWebtestResponse return response
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))
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))
def response_to_string(self): try: simple_body = '\n'.join([l for l in self.testbody.splitlines() if l.strip()]) except: simple_body = '\n'.join([l.encode('string_escape') for l in self.normal_body.splitlines() if l.strip()]) headers = [(n, v) for n, v in self.headerlist if n.lower() != 'content-length'] headers.sort() output = 'HTTP/1.0 %s\n%s\n\n%s' % ( to_string(self.status), '\n'.join(['%s: %s' % (n, v) for n, v in headers]), simple_body) if isinstance(output, text_type): output = output.encode(self.charset or 'utf-8', 'replace') return output