def simple_app(environ, start_response): setup_testing_defaults(environ) if environ['REQUEST_METHOD'] == 'POST': leng = environ['CONTENT_LENGTH'] mpt_file = open("Multipart-form.txt","wb") mpt_file.write(environ['wsgi.input'].read(int(leng))) mpt_file.close() status = '200 OK' headers = [('Content-type', 'text/html')] start_response(status, headers) keys = environ.keys() keys.sort() ret = list() ret.append("<html><body>") ret.append('<a href=".">This page</a>') ret.append('<form method="POST" action="." enctype="multipart/form-data">') ret.append('<input type="file" name="my_file">') ret.append('<input type="text" name="age">') ret.append('<input type="text" name="age">') ret.append('<input type="text" name="age">') ret.append('<input type="submit" value="Submit">') ret.append('</form>') ret.extend(["%s: %s<br>" % (key, environ[key]) for key in keys]) ret.append("</body></html>") return ret
def wsgi_app(environ, start_response): setup_testing_defaults(environ) if environ['REQUEST_METHOD'] == 'OPTIONS': # This is to hanle the preflight request for CORS. # See https://developer.mozilla.org/en/http_access_control response = Response() response.status = "200 OK" else: params = extract_params(environ) log('------') path = environ['PATH_INFO'].split(environ['HTTP_HOST'])[-1] if BASE_PATH: path = path.split(BASE_PATH)[1] log(path) try: if '/pico/' in path: path = path.replace('/pico/', '/') try: response = handle_api_v1(path, params) except APIError: try: response = handle_pico_js(path, params) except APIError: try: response = handle_api_v2(path, params) except APIError: response = not_found_error(path) else: try: response = static_file_handler(path) except OSError, e: response = not_found_error(path) except Exception, e: response = generate_exception_report(e, path, params)
def application(environ, start_response): setup_testing_defaults(environ) if environ['REQUEST_METHOD'] == 'POST': length = int(environ['CONTENT_LENGTH']) data_string = environ['wsgi.input'].read(length) data = urlparse.parse_qs(data_string) print "Recieved data:", data # Check for required parameters: for x in ('year', 'month', 'day', 'rrule', 'format'): assert x in data result = calculate_occurrences(data) response_body = json.dumps(result) status = '200 OK' headers = [('Content-type', 'application/json'), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body] else: filename = os.path.join(*environ['PATH_INFO'].split('/')[1:]) response_body = open(filename, 'rb').read() status = '200 OK' headers = [('Content-type', guess_type(filename)[0]), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body]
def create_event(self, **kwargs): router = Router({"home": {"path": "/"}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) event = Event("TestEvent", params={"router": router, "request": create_request_from_environ(environ)}) return event
def testGetWsdl(self): """Simple test for serving of WSDL by spyne through pyramid route""" application = PyramidApplication( Application([self.HelloWorldService], tns='spyne.examples.hello', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())) config = Configurator(settings={'debug_all': True}) config.add_route('home', '/') config.add_view(application, route_name='home') wsgi_app = validator(config.make_wsgi_app()) env = { 'SCRIPT_NAME': '', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', 'QUERY_STRING': 'wsdl', } setup_testing_defaults(env) request = Request(env) resp = request.get_response(wsgi_app) self.assert_(resp.status.startswith("200 ")) node = etree.XML(resp.body) # will throw exception if non well formed
def _makeEnviron(self, kw=None): from wsgiref.util import setup_testing_defaults environ = {} setup_testing_defaults(environ) if kw is not None: environ.update(kw) return environ
def test_stats_w_logging_client(self): # In the case where a statsd server has not been configured, # stats info is sent to a log using a custom class that provides # the same interface as the statsd.StatsClient. metric_data = { 'type': 'timing', 'label': 'i.haz.thunkd.cheezburgr', 'value': 300, } environ = { 'PATH_INFO': '/metric', 'REQUEST_METHOD': 'POST', } setup_testing_defaults(environ) # Assign the posted message. environ['wsgi.input'].write(json.dumps(metric_data)) environ['wsgi.input'].seek(0) resp_body = self.app(environ, self.start_response) # Check response, smoke test. self.assertEqual(resp_body, []) self.assertEqual(self.resp_args[0].upper(), '200 OK') self.assertEqual(self.resp_args[1], []) # Check the metric was accepted. self.assertEqual([x.msg for x in self.logged], ['i.haz.thunkd.cheezburgr:300|ms'])
def setup_environ(**kwargs): """ setup basic wsgi environ""" environ = {} from wsgiref.util import setup_testing_defaults setup_testing_defaults(environ) environ.update(kwargs) return environ
def simple_app(environ, start_response): global counter setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) firstname, lastname = get_random_name() joke_str = get_random_joke("plain_first_name", "plain_last_name") print joke_str #Replace plain_first_name with actual firstname, and plain_last_name with actual lastname joke_str_mod = replace_pattern(joke_str, "plain_first_name", "FIRST_NAME") joke_str_mod = replace_pattern(joke_str_mod, "plain_last_name", "LAST_NAME") ret = [("%s: %s\n" % (key, value)).encode("utf-8") for key, value in environ.items()] ret = "{0} Hello, cruel world!\n".format(threading.current_thread().ident) ret = joke_str_mod + "\n" print "Will be sleeping now" if counter < 5: counter += 1 sleep(50) return ret
def checkShift(self, sn_in, pi_in, part, sn_out, pi_out): env = {"SCRIPT_NAME": sn_in, "PATH_INFO": pi_in} util.setup_testing_defaults(env) self.assertEqual(util.shift_path_info(env), part) self.assertEqual(env["PATH_INFO"], pi_out) self.assertEqual(env["SCRIPT_NAME"], sn_out) return env
def checkShift(self,sn_in,pi_in,part,sn_out,pi_out): env = {'SCRIPT_NAME':sn_in,'PATH_INFO':pi_in} util.setup_testing_defaults(env) self.assertEqual(util.shift_path_info(env),part) self.assertEqual(env['PATH_INFO'],pi_out) self.assertEqual(env['SCRIPT_NAME'],sn_out) return env
def dummy_request(env, uname=None): environ = {} setup_testing_defaults(environ) environ.update({ 'REQUEST_METHOD' : 'GET', 'SCRIPT_NAME' : urlparse(str(env._abs_href())).path, 'trac.base_url' : str(env._abs_href()), }) req = Request(environ, lambda *args, **kwds: None) # Intercept redirection req.redirect = lambda *args, **kwds: None # Setup user information if uname is not None : environ['REMOTE_USER'] = req.authname = uname rd = RequestDispatcher(env) chrome = Chrome(env) req.callbacks.update({ 'authname': rd.authenticate, 'chrome': chrome.prepare_request, 'hdf': getattr(rd, '_get_hdf', None), 'lc_time': rd._get_lc_time, 'locale' : getattr(rd, '_get_locale', None), 'perm': rd._get_perm, 'session': rd._get_session, 'tz': rd._get_timezone, 'form_token': rd._get_form_token }) return req
def request(self, application, url, query_string="", post_data=b""): """Hand a request to the application as if sent by a client. @param application: The callable wsgi application to test. @param url: The URL to make the request against. @param query_string: Url parameters. @param post_data: bytes to post.""" self.response_started = False method = 'POST' if post_data else 'GET' temp = io.BytesIO(post_data) environ = { 'PATH_INFO': url, 'REQUEST_METHOD': method, 'CONTENT_LENGTH': len(post_data), 'QUERY_STRING': query_string, 'wsgi.input': temp, } if method == "POST": environ["CONTENT_TYPE"] = "application/x-www-form-urlencoded" setup_testing_defaults(environ) if self.cookies: environ['HTTP_COOKIE'] = ';'.join(self.cookies) response = b'' for ret in application(environ, self._start_response): assert self.response_started response += ret temp.close() return response
def serve(environ, start_response): setup_testing_defaults(environ) web_path = environ['PATH_INFO'] local_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) path = local_path + '/www' + web_path #sys.stderr.write(web_path + "\n") #sys.stderr.write(local_path + "\n") sys.stderr.write(path + "\n") # if path is a directory add index.html to the end of it if not os.path.exists(path): return not_found(start_response) # if no index.html, shall we provide directory listing? if os.path.isdir(path): path += '/index.html' if not os.path.exists(path): return not_found(start_response) fh = open(path, 'r') status = '200 OK' headers = [('Content-type', 'text/html')] start_response(status, headers) return fh
def __call__(self, environ, start_response): # parse the request setup_testing_defaults(environ) path = environ['PATH_INFO'] querystring = environ['QUERY_STRING'] multiargs = urlparse.parse_qs(querystring) # get the route and the associated Python method, then execute # that method with the given querystring parameters as Python kwargs if path[1:]: path_method = 'get_%s' % path[1:] else: path_method = 'get_index' if hasattr(self.__routable_object, path_method): # call the routed method single_value_args = {} for key in multiargs: single_value_args[key] = multiargs[key][0] status, content_type, content = getattr(self.__routable_object, path_method)(**single_value_args) else: # route doesn't exist content_type = 'text/html' content = status = '404 NOT FOUND' # write out the HTTP response status = '200 OK' headers = [('Content-type', content_type)] start_response(status, headers) return [content]
def execute(self): try: router = self.container.get('router') if not router.routes: raise ConsoleError('There are no routes associated with the application.') if self.parsed_args.url: environ = {} util.setup_testing_defaults(environ) environ.update({ 'REQUEST_METHOD': self.parsed_args.method or 'GET', 'HTTP_ACCEPT': self.parsed_args.format or 'text/html', 'PATH_INFO': self.parsed_args.url, 'SERVER_NAME': self.parsed_args.server or '127.0.0.1' }) request = create_request_from_environ(environ) matches = router.matches(request) if matches: sys.stdout.write(colors.header('Displaying {0} matching routes for the application:\n'.format(len(matches)))) for match in matches: sys.stdout.write('{0}\t\t\{1}\t\t{2}\n'.format(colors.ok_green(match.route.name), match.route.path, match.route.regex.pattern)) else: raise ConsoleError('There are no matching routes.') else: sys.stdout.write(colors.header('Displaying {0} routes for the application:\n'.format(len(router)))) for name, route in router: sys.stdout.write('{0}\t\t{1}\n'.format(name, route.path)) except ConsoleError: raise except: _no_application_error()
def simple_app(environ, start_response): # FIXME: remove use of setup_testing_defaults setup_testing_defaults(environ) environ["fsgs"] = fsgs for mapping in url_map: kwargs = mapping.match(environ) if kwargs is not None: request = Request(environ) try: result = mapping.run_handler(request, kwargs) status = "200 OK" if isinstance(result, dict): headers = [("Content-type", "application/json")] if "list_hack" in result: result = result["list_hack"] data = json.dumps(result, indent=4).encode("UTF-8") else: raise Exception("unknown result data type") # headers = [("Content-type", "application/octet-stream")] # data = json.dumps(result).encode("UTF-8") except Exception as e: traceback.print_exc() status = "500 Internal Server Error" headers = [("Content-type", "text/plain")] data = repr(e).encode("UTF-8") start_response(status, headers) return [data] start_response("404 Not Found", [("Content-type", "text/plain")]) return [b"The resource was not found"]
def webapp(environ, start_response): """Serve simple pages, based on whether the URL requests users, rooms or bookings. For now, just serve the Home page """ setup_testing_defaults(environ) # # Assume we're going to serve a valid HTML page # status = '200 OK' headers = [('Content-type', 'text/html; charset=utf-8')] # # Pick up the first segment on the path and pass # the rest along. # # ie if we're looking for /users/1/bookings, # param1 will be "users", and the remaining path will # be "/1/bookings". # param1 = shift_path_info(environ) if param1 == "": data = index_page(environ) elif param1 == "users": data = users_page(environ) elif param1 == "rooms": data = rooms_page(environ) else: status = '404 Not Found' data = "Not Found: %s" % param1 start_response(status, headers) return [data.encode("utf-8")]
def _makeEnv(self, **kw): from wsgiref.util import setup_testing_defaults env = {} setup_testing_defaults(env) env.update(kw) env['QUERY_STRING'] = '' return env
def test_full_conversion(self): def _track(environ): return [environ['cleaver']( 'Coin', ('Heads', 'Heads'), ('Tails', 'Tails') )] def _score(environ): environ['cleaver'].score('Coin') return [] # Simulate an HTTP GET to track, and an HTTP POST later to convert handler = cycle((_track, _track, _score)) def app(environ, start_response): response_headers = [('Content-type', 'text/plain')] start_response('200 OK', response_headers) return next(handler)(environ) environ = {} setup_testing_defaults(environ) app = SplitMiddleware( app, lambda environ: 'ryan', self.b ) # The first request returns a variant and stores it variant = app(environ, lambda *args: None)[0] assert variant in ('Heads', 'Tails') assert len(self.b.all_experiments()) == 1 assert self.b.all_experiments()[0].name == 'Coin' started_on = self.b.all_experiments()[0].started_on assert isinstance(started_on, datetime) experiment = self.b.get_experiment('Coin', ['Heads', 'Tails']) assert experiment.participants == 1 assert self.b.participants('Coin', variant) == 1 # The second request returns the same cleaver variant assert app(environ, lambda *args: None)[0] == variant assert len(self.b.all_experiments()) == 1 assert self.b.all_experiments()[0].name == 'Coin' assert self.b.all_experiments()[0].started_on == started_on experiment = self.b.get_experiment('Coin', ['Heads', 'Tails']) assert experiment.participants == 1 assert self.b.participants('Coin', variant) == 1 # The third request marks a conversion assert app(environ, lambda *args: None) == [] assert experiment.conversions == 1 assert self.b.conversions('Coin', variant) == 1
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/html')] start_response(status, headers) ret = environ['PATH_INFO'][1:] weight = float(ret) return str(cooking_time(weight))
def simple_app(environ, start_response): print 'start' setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) print 'end' return ['empty']
def setUp(self): self.cgi = tempfile.NamedTemporaryFile(delete=False) os.chmod(self.cgi.name, 0700) self.env = dict() setup_testing_defaults(self.env) self.extra_env = None
def simple_request_response(environ, start_response): setup_testing_defaults(environ) request = create_request_from_environ(environ) response = Response(200, body="Hello World!") start_response(*response.start()) return [response()]
def create_event(self, **kwargs): router = DictRouter({"home": {"path": "/"}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) context = {"request": Request.from_environ(environ)} event = Event("TestEvent", params={"router": router, "context": context}) return event
def _makeEnv(self, path_info, script_name): from wsgiref.util import setup_testing_defaults environ = { "PATH_INFO": path_info, "SCRIPT_NAME": script_name, } setup_testing_defaults(environ) return environ
def setup_environ(**kwargs): """ Create a default wsgi environment, for testing purposes. """ env = {} setup_testing_defaults(env) env.update(kwargs) return env
def simple_app(environ, start_response): setup_testing_defaults(environ) status = str('200 OK') headers = [(str('Content-type'), str('text/html'))] start_response(status, headers) return [str(ServiceManagement.dispatch(Request(environ)))]
def checkOSEnviron(self,handler): empty = {}; setup_testing_defaults(empty) env = handler.environ from os import environ for k,v in environ.items(): if k not in empty: self.assertEqual(env[k],v) for k,v in empty.items(): self.assertIn(k, env)
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/html')] start_response(status, headers) return TMPL % create_table(util.get_hosts())
def hello_world(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return "Hello World " + str(time.time())
def _get_request_obj(self): environ = {} setup_testing_defaults(environ) def start_response(status, headers): return lambda body: None req = Request(environ, start_response) return req
def simple_app(env, start_response): setup_testing_defaults(env) if env["PATH_INFO"] == "/hello": start_response("200 OK", [("Content-Type", "application/json")]) return ["Hello from upstream server"] else: start_response("404 Not Found", [("Content-Type", "text/plain")]) return []
def _makeEnviron(self, kw=None): from wsgiref.util import setup_testing_defaults environ = {} setup_testing_defaults(environ) if kw is not None: environ.update(kw) environ['REMOTE_ADDR'] = '1.1.1.1' environ['HTTP_HOST'] = 'localhost' return environ
def __init__(self, **kw): setup_testing_defaults(kw) BaseCGIHandler.__init__(self, BytesIO(), BytesIO(), StringIO(), kw, multithread=True, multiprocess=True)
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) return [ "Hello World".encode("utf-8"), ]
def checkOSEnviron(self,handler): empty = {}; setup_testing_defaults(empty) env = handler.environ from os import environ for k,v in environ.items(): if not empty.has_key(k): self.assertEqual(env[k],v) for k,v in empty.items(): self.failUnless(env.has_key(k))
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret
def checkOSEnviron(self, handler): empty = {} setup_testing_defaults(empty) env = handler.environ from os import environ for k, v in environ.items(): if not empty.has_key(k): self.assertEqual(env[k], v) for k, v in empty.items(): self.failUnless(env.has_key(k))
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/html')] start_response(status, headers) page = ['<html><head><head><body><h1>Hello World</h1></body></html>'] return page
def app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/html; charset=utf8')] start_response(status, headers) form = StudentForm() return [template.render(form=form).encode("utf-8")]
def hello_world(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) res = f"Hello World {time.time()}".encode('utf-8') return [res]
def application(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) ret = [("%s: %s\n" % (key, value)).encode("utf-8") for key, value in environ.items() if key.find("wsgi") != -1] return ret
def simple_app(environ, start_response): """ Respond to a GET with a 200 and the known agent_response string. """ setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return CONST.agent_response
def app(env, start_response): setup_testing_defaults(env) start_response(self.status, self.headers) if self.interpolate: return self.content % { "SCHEME": "http", "HOST": self.host, "PORT": self.port, } return self.content
def getquota(env, start_response): setup_testing_defaults(env) try: request_body_size = int(env.get('CONTENT_LENGTH', 0)) except ValueError: request_body_size = 0 request_body = env['QUERY_STRING'] d = parse_qs(request_body) username = escape(d.get('username', [''])[0]) pagecount, pagequota = ('', '') current_time = datetime.datetime.now() first_of_next_month = datetime.datetime( current_time.year + current_time.month // 12, (current_time.month + 1) if current_time.month < 12 else 1, 1, 0, 0, 0, 0) lastupdate, = db_cursor.execute( 'SELECT value FROM config WHERE key="lastupdate";').fetchone() if len(username) > 0: try: pagecount, pagequota, lastjob = db_cursor.execute( 'SELECT pagecount, pagequota, lastjob FROM users WHERE username = ?;', [username]).fetchone() no_such_user = False except: no_such_user = True else: no_such_user = True status = '200 OK' headers = [('Content-type', 'application/json'), ('Access-Control-Allow-Origin', '*')] start_response(status, headers) res = {} if (pagecount != '' and pagequota != ''): res["pagequota"] = pagequota res["pagecount"] = pagecount res["lastjob"] = datetime.datetime.fromtimestamp( int(lastjob)).strftime("%Y-%m-%d") res["increasecount"] = monthly_pagenumber_decrease if int( pagecount) - monthly_pagenumber_decrease > 0 else pagecount res["nextincrease"] = first_of_next_month.strftime('%Y-%m-%d') elif (no_such_user and len(username) > 0): res["error"] = "USER_NOT_FOUND" else: res["error"] = "OTHER" return json.dumps(res) + '\n'
def get(self, app, path): environ = {'PATH_INFO': path, 'REQUEST_METHOD': 'GET'} setup_testing_defaults(environ) _code = [] _headers = [] def start_response(code, headers): _code.append(code) _headers.extend(headers) contents = b''.join(app(environ, start_response)) return _code[0], _headers, contents
def create_event(self, **kwargs): router = DictRouter({'home': {'path': '/'}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) context = {'request': Request.from_environ(environ)} event = Event( 'TestEvent', params={'router': router, 'context': context}) return event
def test_monitor_decorator(self): pynba = LocalProxy(enabled=False) # noqa @monitor(('127.0.0.1', 30002)) def foo(environ, start_response): return environ = {} setup_testing_defaults(environ) start_response = None foo(environ, start_response)
def setUp(self): self.patcher = mock.patch('core.BanRot.from_csv') self.from_csv_mock = self.patcher.start() self.ban_rot_mock = mock.MagicMock() self.from_csv_mock.return_value = self.ban_rot_mock import banrot banrot.banrot = self.ban_rot_mock self.banrot_mod = banrot self.environ = {} setup_testing_defaults(self.environ) self.start_response = mock.MagicMock()
def create_event(self, **kwargs): router = Router({'home': {'path': '/'}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) event = Event('TestEvent', params={ 'router': router, 'request': create_request_from_environ(environ) }) return event
def test_request(self): environ = {"QUERY_STRING": "foo=bar&hoge=piyo"} setup_testing_defaults(environ) req = Request(environ) self.assertEqual(req.scheme, "http") self.assertEqual(req.host, environ["HTTP_HOST"]) self.assertEqual(req.method, environ["REQUEST_METHOD"]) self.assertEqual(req.raw_path, "/?foo=bar&hoge=piyo") self.assertEqual(req.path, "/") self.assertEqual(req.query, {"foo": ["bar"], "hoge": ["piyo"]}) self.assertEqual(req.version, environ["SERVER_PROTOCOL"]) self.assertEqual(req.url, request_uri(environ))
def __init__(self,environ,start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-Type', 'text/html')] start_response(status, headers) for k, v in environ.items(): print(k, v) ret = [("%s:%s\n" % (key, value)).encode('utf-8') for key, value in environ.items()] print(ret) self.ret = ret
def app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain; charset=utf-8')] start_response(status, headers) n = 30 fib_n = fib(n) res = "fib(%d) = %d" % (n, fib_n) return [res.encode("utf-8")]
def test_router(self): environ = {} setup_testing_defaults(environ) request = Request(environ) class TestController(Controller): def handle(self, request): return "dadada" router = Router([view("/", TestController)]) request_, handle, method = router.match(request) self.assertTrue(callable(handle))
def run(): env = { 'HTTP_COOKIE': '', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'PATH_INFO': '/tests1/test_get' } setup_testing_defaults(env) pprint(env) app = Application() body = app.__call__(env, start_resp) print(body)
def setUp(self): super().setUp() self.write_buffer = io.BytesIO() self.write = self.write_buffer.write self.environ = {} wsgiref_util.setup_testing_defaults(self.environ) self.status = None self.response_headers = None self.exc_info = None
def mkcalendar(self, app, path): environ = {'PATH_INFO': path, 'REQUEST_METHOD': 'MKCALENDAR', 'SCRIPT_NAME': ''} setup_testing_defaults(environ) _code = [] _headers = [] def start_response(code, headers): _code.append(code) _headers.extend(headers) contents = b''.join(app(environ, start_response)) return _code[0], _headers, contents
def testEnviron(self): os_environ = { # very basic environment 'HOME': '/my/home', 'PATH': '/my/path', 'LANG': 'fr_FR.UTF-8', # set some WSGI variables 'SCRIPT_NAME': 'test_script_name', 'SERVER_NAME': 'test_server_name', } with support.swap_attr(TestHandler, 'os_environ', os_environ): # override X and HOME variables handler = TestHandler(X="Y", HOME="/override/home") handler.setup_environ() # Check that wsgi_xxx attributes are copied to wsgi.xxx variables # of handler.environ for attr in ('version', 'multithread', 'multiprocess', 'run_once', 'file_wrapper'): self.assertEqual(getattr(handler, 'wsgi_' + attr), handler.environ['wsgi.' + attr]) # Test handler.environ as a dict expected = {} setup_testing_defaults(expected) # Handler inherits os_environ variables which are not overriden # by SimpleHandler.add_cgi_vars() (SimpleHandler.base_env) for key, value in os_environ.items(): if key not in expected: expected[key] = value expected.update({ # X doesn't exist in os_environ "X": "Y", # HOME is overriden by TestHandler 'HOME': "/override/home", # overriden by setup_testing_defaults() "SCRIPT_NAME": "", "SERVER_NAME": "127.0.0.1", # set by BaseHandler.setup_environ() 'wsgi.input': handler.get_stdin(), 'wsgi.errors': handler.get_stderr(), 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.multithread': True, 'wsgi.multiprocess': True, 'wsgi.file_wrapper': util.FileWrapper, }) self.assertDictEqual(handler.environ, expected)