def req(self, body, method): req = Request({'wsgi.url_scheme' : URL_SCHEME, 'wsgi.input' : StringIO(body), 'SERVER_NAME' : SERVER_NAME, 'SERVER_PORT' : SERVER_PORT}) req.body = body req.method = method return req
def reqWithQuery(self, body, method, query_params): req = Request({'wsgi.url_scheme' : URL_SCHEME, 'wsgi.input' : StringIO(body), 'SERVER_NAME' : SERVER_NAME, 'SERVER_PORT' : SERVER_PORT, 'QUERY_STRING' : query_params }) req.body = body req.method = method return req
def reqWithPath(self, body, method, path): req = Request({'wsgi.url_scheme' : URL_SCHEME, 'wsgi.input' : StringIO(body), 'SERVER_NAME' : SERVER_NAME, 'SERVER_PORT' : SERVER_PORT, 'PATH_INFO' : path }) req.body = body req.method = method return req
def testInvoke(self): req = Request.blank('http://testrunner.example.com/test_entry/grant') rsp = req.get_response(application) self.assertEqual(rsp.status_int, 200) cap = json.loads(rsp.body)['value']['@'] req2 = Request.blank(cap) rsp2 = req2.get_response(application) self.assertEqual(rsp2.body, \ json.dumps({"value": {"success": True}}))
def get_cache(): if users.is_current_user_admin(): return None env = dict(os.environ) env["wsgi.input"] = sys.stdin env["wsgi.errors"] = sys.stderr env["wsgi.version"] = (1, 0) env["wsgi.run_once"] = True env["wsgi.url_scheme"] = wsgiref.util.guess_scheme(env) env["wsgi.multithread"] = False env["wsgi.multiprocess"] = False req = Request(env) cached_resp = memcache.get(req.path_url.rstrip('/')) if cached_resp: def cache_app(env, start_resp): logging.info('returning cached page (%s)' % req.path_url) #BREAKPOINT() write_handle = start_resp(cached_resp.status, (cached_resp.headers.items())) write_handle(cached_resp.body) return cache_app else: return None
def mock_handler(page, request='/', **response): handler = RequestHandler.with_page(page=page)() handler.initialize(Request.blank(request), Response()) handler.response_dict(**response) handler.logout_url = lambda: None handler.login_url = lambda: None return handler
def test_instructor_can_set_category_to_answer(self): qkey = self.q00_key respond = ResponseHandler() session = { 'account': self.instructor.username, 'accounttypr': ADMIN, 'class': self.classy.classname, 'question_key': qkey.urlsafe(), } secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY) serialized = secure_cookie_serializer.serialize('session', session) headers = {'Cookie': 'session=%s' % serialized} respond.request = Request.blank( '/respond?response=test&cname=test_category') respond.request.method = 'POST' respond.request.headers = headers #ensure that the vars were passed to test properly self.assertTrue(respond.request.get('response') == 'test') self.assertTrue(respond.request.get('cname') == 'test_category') response = respond.request.get_response(main.app) time.sleep(2) question = qkey.get() cate = Category.query(Category.name == 'test_category').fetch() self.assertTrue( len(cate) == 1) #was created/found and is unique, also has the correct name cate = cate[0] self.assertTrue(question.category == cate.key) question.key.delete() cate.key.delete()
def application(environ, start_response): # entry point global _url_map if not _url_map: _init_url_map() request = Request(environ) match_app = '' for regexp, app in _url_map: match_obj = regexp.match(request.path) if match_obj: # path info hack path_prefix = environ['PATH_PREFIX'] = match_obj.group() path_info = environ['ROOT_PATH_INFO'] = environ['PATH_INFO'] new_path_info = path_info[len(path_prefix):] if new_path_info.startswith('/'): environ['PATH_INFO'] = new_path_info else: environ['PATH_INFO'] = '/' + new_path_info match_app = app break else: # no match patterns. raise Http404 # select app from core.loader import get_application real_app = get_application(match_app) # run app return real_app(environ, start_response)
def test_instructor_can_respond_with_faq(self): qkey = self.q00_key respond = ResponseHandler() session = { 'account': self.instructor.username, 'accounttypr': ADMIN, 'class': self.classy.classname, 'question_key': qkey.urlsafe(), } secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY) serialized = secure_cookie_serializer.serialize('session', session) headers = {'Cookie': 'session=%s' % serialized} respond.request = Request.blank('/respond?response=test&infaq=infaq') respond.request.method = 'POST' respond.request.headers = headers self.assertTrue(respond.request.get('response') == 'test') self.assertTrue(respond.request.get('infaq') == 'infaq') response = respond.request.get_response(main.app) time.sleep(2) question = qkey.get() self.assertTrue(question.response == R_INFAQ)
def test_instructor_can_create_new_category(self): qkey = self.q00_key respond = ResponseHandler() session = { 'account': self.instructor.username, 'accounttype': ADMIN, 'class': self.classy.classname, 'question_key': qkey.urlsafe(), } secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY) serialized = secure_cookie_serializer.serialize('session', session) headers = {'Cookie':'session=%s' % serialized} respond.request = Request.blank('/respond?add_to_category=1&response=test&cname=Default&new_cname=test_category') respond.request.method='POST' respond.request.headers=headers #ensure that the vars were passed to test properly self.assertTrue(respond.request.get('response') == 'test') self.assertTrue(respond.request.get('new_cname') == 'test_category') temp = Category.query(Category.name=='test_category').fetch() for c in temp: c.key.delete() del temp response = respond.request.get_response(main.app) time.sleep(2) category = Category.query(Category.name == 'test_category').fetch() self.assertTrue(len(category)==1) #was created and is unique, also has the correct name category = category[0] self.assertTrue(category.key.parent() == self.classy.key) category.key.delete()
def test_instructor_can_respond(self): qkey = self.q00_key respond = ResponseHandler() session = { 'account': self.instructor.username, 'accounttypr': ADMIN, 'class': self.classy.classname, 'question_key': qkey.urlsafe(), } secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY) serialized = secure_cookie_serializer.serialize('session', session) headers = {'Cookie': 'session=%s' % serialized} respond.request = Request.blank('/respond?response=test') respond.request.method = 'POST' #respond.request.body = 'response=test' respond.request.headers = headers #print '\n'+respond.request.get('message')+'\n' self.assertTrue(respond.request.get('response') == 'test') response = respond.request.get_response(main.app) #message = response.get('message') question = qkey.get() self.assertFalse(question == None) self.assertFalse(question.respondentUID == None) self.assertFalse(question.response == None) self.assertFalse(question.response == '') self.assertTrue(question.respondentUID == self.instructor.key) self.assertTrue(question.response == 'test')
def exec_handler(self, body = None): """Used by each test to execute the minimal Testhandler.""" h = self.MyTestHandler() h.request = Request.blank('/test_rpc/') h.response = Response() h.request.body = body h.post() return (h.response._Response__status[0], h.response.out.getvalue())
def test_search_4(self): handler = MyHandler() form = 'searchKeyword=Kony' handler.request = Request({ 'ACTION': '/searchQuery', 'METHOD': 'get', 'wsgi.input': StringIO(form), 'CONTENT_LENGTH': len(form), })
def testGrant(self): req = Request.blank('http://testrunner.example.com/test_entry/grant') rsp = req.get_response(application) self.assertEqual(rsp.status_int, 200) d = json.loads(rsp.body) self.assertIn('value', d) self.assertIn('@', d['value']) cap = d['value']['@'] self.assertRegexpMatches(cap, r'^http://testrunner.example.com/caps/')
def __call__(self, environ, start_response): """Called by WSGI when a request comes in.""" request = Request(environ) response = Response() WSGIApplication.active_instance = self # Match the path against registered routes. kargs = self.mapper.match(request.path) if kargs is None: raise TypeError( 'No routes match. Provide a fallback to avoid this.') # Extract the module and controller names from the route. try: module_name, class_name = kargs['controller'].split(':', 1) except (KeyError, ValueError): module_name = kargs['controller'] class_name = module_name del kargs['controller'] module_name = _CONTROLLERS_MODULE_PREFIX + '.' + module_name # Initialize matched controller from given module. try: __import__(module_name) module = sys.modules[module_name] controller = getattr(module, class_name)() controller.initialize(request, response) except (ImportError, AttributeError): logging.exception('Could not import controller %s:%s', module_name, class_name) raise ImportError( 'Controller %s from module %s could not be initialized.' % (class_name, module_name)) # Use the action set in the route, or the HTTP method. if 'action' in kargs: action = kargs['action'] del kargs['action'] else: action = environ['REQUEST_METHOD'].lower() if action not in [ 'get', 'post', 'head', 'options', 'put', 'delete', 'trace' ]: action = None if controller and action: try: # Execute the requested action, passing the route dictionary as # named parameters. getattr(controller, action)(**kargs) except error.AccessDenied, acl_e: logging.exception(acl_e) response.set_status(404) except Exception, e: # We want to catch any exception thrown by the controller and # pass it on to the controller's own exception handler. controller.handle_exception(e, self.__debug)
def exec_handler(self, body=None): """Used by each test to execute the minimal Testhandler.""" h = self.MyTestHandler() h.request = Request.blank('/test_rpc/') h.response = Response() h.request.method = 'POST' h.request.body = body h.post() return (h.response._Response__status[0], h.response.out.getvalue())
def test_export_3(self): handler = MyHandler() s = "<crises>name </crises>" handler.request = Request({ 'ACTION': '/xmlExport', 'METHOD': 'get', 'wsgi.input': StringIO(s), 'CONTENT_LENGTH': len(s), })
def test_upload_3(self): handler = MyHandler() f = open('nalmanza-WC1.xml') s = "" for line in f: s += line handler.request = Request({ 'ACTION': '/xmlupload', 'METHOD': 'get', 'wsgi.input': StringIO(s), 'CONTENT_LENGTH': len(s), })
def __call__(self, environ, start_response): """Called by WSGI when a request comes in.""" url = URLGenerator(self.mapper, environ) environ['routes.url'] = url request = Request(environ) response = Response() WSGIApplication.active_instance = self # Match the path against registered routes. kargs = self.mapper.match(request.path) if kargs is None: raise TypeError( 'No routes match. Provide a fallback to avoid this.') # Extract the module and controller names from the route. try: module_name, class_name = kargs['controller'].split(':', 1) del kargs['controller'] except: raise TypeError( 'Controller is not set, or not formatted in the form "my.module.name:MyControllerName".' ) # Initialize matched controller from given module. try: __import__(module_name) module = sys.modules[module_name] controller = getattr(module, class_name)() controller.initialize(request, response) except: raise ImportError( 'Controller %s from module %s could not be initialized.' % (class_name, module_name)) # Use the action set in the route, or the HTTP method. if 'action' in kargs: action = kargs['action'] del kargs['action'] else: action = environ['REQUEST_METHOD'].lower() if action not in [ 'get', 'post', 'head', 'options', 'put', 'delete', 'trace' ]: action = None if controller and action: try: # Execute the requested action, passing the route dictionary as # named parameters. getattr(controller, action)(**kargs) except Exception, e: controller.handle_exception(e, self.__debug) response.wsgi_write(start_response) return ['']
def __call__(self, environ, start_response): """Called by WSGI when a request comes in.""" request = Request(environ) response = Response() # BidiX 2008-09-22 : try to setup a firewall at least a nop if banned_ip.is_banned(request.remote_addr): response.set_status(403) response.wsgi_write(start_response) return [''] WSGIApplication.active_instance = self handler = None groups = () for regexp, handler_class in self._url_mapping: match = regexp.match(request.path) if match: handler = handler_class() handler.match = match # BidiX 2008-05-22 handler.initialize(request, response) groups = match.groups() break self.current_request_args = groups if handler: try: method = environ['REQUEST_METHOD'] if method == 'GET': handler.get(*groups) elif method == 'POST': handler.post(*groups) elif method == 'HEAD': handler.head(*groups) elif method == 'OPTIONS': handler.options(*groups) elif method == 'PUT': handler.put(*groups) elif method == 'DELETE': handler.delete(*groups) elif method == 'TRACE': handler.trace(*groups) else: handler.error(501) except Exception, e: #handler.handle_exception(e, self.__debug) # BidiX 2008-05-22 handler.handle_exception(e, True) # BidiX 2008-05-22
def setUp(self): """Set up the test with a simple TestHandler.""" h = self.MyTestHandler() h.request = Request.blank('/rpc/') h.response = Response() self.handler = h
def mock_handler(file='handlers/mock.py', request='/mock', **response): handler = RequestHandler.with_page(mock_page(file))() handler.initialize(Request.blank(request), Response()) handler.response_dict(**response) return handler
def __init__(self): Request.__init__(self, dict())