def testSetControllerFromRouter(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.controllers, {}) router = Router([Resource(TestController, root=True)]) app.setControllerFromRouter(router) self.assertNotEqual(app.controllers, {})
def testAttachment(self): app = shimehari.Shimehari(__name__) with catchWarnings() as captured: with app.testRequestContext(): f = open(os.path.join(app.rootPath, 'static/index.html')) rv = shimehari.sendFile(f, asAttachment=True) value, options = parse_options_header( rv.headers['Content-Disposition']) self.assertEqual(value, 'attachment') self.assertEqual(len(captured), 2) with app.testRequestContext(): self.assertEqual(options['filename'], 'index.html') rv = shimehari.sendFile(os.path.join(app.rootPath, 'static/index.html'), asAttachment=True) value, options = parse_options_header( rv.headers['Content-Disposition']) self.assertEqual(value, 'attachment') self.assertEqual(options['filename'], 'index.html') with app.testRequestContext(): rv = shimehari.sendFile(StringIO('Test'), asAttachment=True, attachmentFilename='index.txt', addEtags=True) self.assertEqual(rv.mimetype, 'text/plain') value, options = parse_options_header( rv.headers['Content-Disposition']) self.assertEqual(value, 'attachment') self.assertEqual(options['filename'], 'index.txt')
def testDebugLog(self): app = shimehari.Shimehari(__name__) app.debug = True def index(): app.logger.warning('the standard library is dead') app.logger.debug('this is a debug statement') return '' def exc(): 1 / 0 app.router = shimehari.Router([ Rule('/', endpoint='index', methods=['GET']), Rule('/exc', endpoint='exc', methods=['GET']), ]) app.controllers['index'] = index app.controllers['exc'] = exc with app.testClient() as c: with catchStdErr() as err: c.get('/') out = err.getvalue() self.assert_('WARNING' not in out) self.assert_( os.path.basename(__file__.rsplit('.', 1)[0] + '.py') not in out) self.assert_('the standard library is dead' not in out) self.assert_('this is a debug statement' not in out) with catchStdErr() as err: try: c.get('/exc') except ZeroDivisionError: pass else: self.assert_(False, 'debug log ate the exception')
def testProcessorExceptions(self): app = shimehari.Shimehari(__name__) @app.beforeRequest def beforeReq(): if trigger == 'before': 1 / 0 @app.afterRequest def afterRequest(response): if trigger == 'after': 1 / 0 return response def index(): return 'Foo' app.router = shimehari.Router( [Rule('/', endpoint='index', methods=['GET'])]) app.controllers['index'] = index @app.errorHandler(500) def internalServerError(e): return 'Hello Server Error', 500 for trigger in 'before', 'after': rv = app.testClient().get('/') self.assertEqual(rv.status_code, 500) self.assertEqual(rv.data, 'Hello Server Error')
def testJsoniFy(self): d = dict(a=23, b=42, c=[1, 2, 3]) ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) #hum def returnKwargs(): return shimehari.jsonify(**d) def returnDict(): return shimehari.jsonify(d) app.router = shimehari.Router([ Rule('/kw', endpoint='returnKwargs', methods=['GET']), Rule('/dict', endpoint='returnDict', methods=['GET']) ]) app.controllers['returnKwargs'] = returnKwargs app.controllers['returnDict'] = returnDict c = app.testClient() for url in '/kw', '/dict': rv = c.get(url) print rv.mimetype self.assertEqual(rv.mimetype, 'application/json') self.assertEqual(shimehari.json.loads(rv.data), d)
def testLoggerCache(self): app = shimehari.Shimehari(__name__) logger1 = app.logger self.assert_(app.logger is logger1) self.assertEqual(logger1.name, __name__) app.loggerName = __name__ + 'aaaa' self.assert_(app.logger is not logger1)
def testSendFileRegular(self): app = shimehari.Shimehari(__name__) with app.testRequestContext(): rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) self.assert_(rv.direct_passthrough) self.assertEqual(rv.mimetype, 'text/html') with app.openFile('static/index.html') as f: self.assertEqual(rv.data, f.read())
def testTemplateEscaping(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.setupTemplater() render = shimehari.renderTempalteString with app.testRequestContext(): rv = render('{{"</script>"|tojson|safe }}') self.assertEqual(rv, '"</script>"') rv = render('{{"<\0/script>"|tojson|safe }}') self.assertEqual(rv, '"<\\u0000/script>"')
def testCustomRequestGlobalsClass(self): class CustomRequestGlobals(object): def __init__(self): self.spam = 'sakerin' app = shimehari.Shimehari(__name__) app.setupTemplater() app.sharedRequestClass = CustomRequestGlobals with app.testRequestContext(): self.assertEqual( shimehari.renderTempalteString('{{ shared.spam }}'), 'sakerin')
def testAppTearingDown(self): cleanStuff = [] app = shimehari.Shimehari(__name__) @app.tearDownAppContext def cleanup(exception): cleanStuff.append(exception) with app.appContext(): pass self.assertEqual(cleanStuff, [])
def testSendFileXSendFile(self): app = shimehari.Shimehari(__name__) app.useXSendFile = True with app.testRequestContext(): rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) self.assert_(rv.direct_passthrough) self.assert_('x-sendfile' in rv.headers) self.assertEqual(rv.headers['x-sendfile'], os.path.join(app.rootPath, 'static/index.html')) self.assertEqual(rv.mimetype, 'text/html')
def testGotFirstRequest(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.gotFirstRequest, False) def returnHello(*args, **kwargs): return 'Hello' app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])]) app.controllers['returnHello'] = returnHello c = app.testClient() c.get('/hell', content_type='text/planetext') self.assert_(app.gotFirstRequest)
def testURLForWithAnchro(self): app = shimehari.Shimehari(__name__) def index(): return '42' app.router = shimehari.Router( [Rule('/', endpoint='index', methods=['GET'])]) app.controllers['index'] = index with app.testRequestContext(): self.assertEqual(shimehari.urlFor('index', _anchor='x y'), '/#x%20y')
def testJSONBadRequests(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def returnJSON(*args, **kwargs): return unicode(shimehari.request.json) app.router = shimehari.Router( [Rule('/json', endpoint='returnJSON', methods=['POST'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() rv = c.post('/json', data='malformed', content_type='application/json') self.assertEqual(rv.status_code, 400)
def testSetup(self): # ConfigManager.addConfig(testConfig) ConfigManager.removeConfig('development') ConfigManager.addConfig(Config('development', {'AUTO_SETUP': False, 'SERVER_NAME': 'localhost', 'PREFERRED_URL_SCHEME': 'https'})) app = shimehari.Shimehari(__name__) app.appPath = os.path.join(app.rootPath, 'testApp') app.appFolder = 'shimehari.testsuite.testApp' app.setupTemplater() app.setupBindController() app.setupBindRouter() self.assertNotEqual(app.controllers, {}) self.assertNotEqual(app.router._rules, {}) pass
def testGenerateURL(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def index(*args, **kwargs): return 'index' app.router = shimehari.Router( [Rule('/', endpoint='index', methods=['GET'])]) with app.appContext(): rv = shimehari.urlFor('index') self.assertEqual(rv, 'https://localhost/')
def testAddRoute(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.controllers, {}) self.assertEqual(app.router._rules, []) def index(*args, **kwargs): return 'Sake nomitai.' app.addRoute('/', index) c = app.testClient() rv = c.get('/', content_type='text/html') self.assertEqual(rv.status_code, 200) self.assert_('Sake nomitai.' in rv.data)
def jsonBodyEncoding(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.testing = True def returnJSON(*args, **kwargs): return shimehari.request.json app.router = shimehari.Router( [Rule('/json', endpoint='returnJSON', methods=['GET'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() resp = c.get('/', data=u"はひ".encode('iso-8859-15'), content_type='application/json; charset=iso-8859-15') self.assertEqual(resp.data, u'はひ'.encode('utf-8'))
def testSendFileObject(self): app = shimehari.Shimehari(__name__) with catchWarnings() as captured: with app.testRequestContext(): f = open(os.path.join(app.rootPath, 'static/index.html')) rv = shimehari.sendFile(f) with app.openFile('static/index.html') as f: self.assertEqual(rv.data, f.read()) self.assertEqual(rv.mimetype, 'text/html') self.assertEqual(len(captured), 2) app.useXSendFile = True with catchWarnings() as captured: with app.testRequestContext(): f = open(os.path.join(app.rootPath, 'static/index.html')) rv = shimehari.sendFile(f) self.assertEqual(rv.mimetype, 'text/html') self.assert_('x-sendfile' in rv.headers) self.assertEqual( rv.headers['x-sendfile'], os.path.join(app.rootPath, 'static/index.html')) self.assertEqual(len(captured), 2) app.useXSendFile = False with app.testRequestContext(): with catchWarnings() as captured: f = StringIO('Test') rv = shimehari.sendFile(f) self.assertEqual(rv.data, 'Test') self.assertEqual(rv.mimetype, 'application/octet-stream') self.assertEqual(len(captured), 1) with catchWarnings() as captured: f = StringIO('Test') rv = shimehari.sendFile(f, mimetype='text/plain') self.assertEqual(rv.data, 'Test') self.assertEqual(rv.mimetype, 'text/plain') self.assertEqual(len(captured), 1) app.useXSendFile = True with catchWarnings() as captured: with app.testRequestContext(): f = StringIO('Test') rv = shimehari.sendFile(f) self.assert_('x-sendfile' not in rv.headers) self.assertEqual(len(captured), 1)
def testModifiedURLEncoding(self): class ModifiedRequest(shimehari.Request): url_charset = 'euc-jp' app = shimehari.Shimehari(__name__) app.requestClass = ModifiedRequest app.router.charset = 'euc-jp' def index(): return shimehari.request.args['foo'] app.router = shimehari.Router( [Rule('/', endpoint='index', methods=['GET'])]) app.controllers['index'] = index rv = app.testClient().get(u'/?foo=ほげほげ'.encode('euc-jp')) self.assertEqual(rv.status_code, 200) self.assertEqual(rv.data, u'ほげほげ'.encode('utf-8'))
def testExceptionLogging(self): out = StringIO() app = shimehari.Shimehari(__name__) app.loggerName = 'shimehariaaa' app.logger.addHandler(StreamHandler(out)) def index(): 1 / 0 app.router = shimehari.Router( [Rule('/', endpoint='index', methods=['GET'])]) app.controllers['index'] = index rv = app.testClient().get('/') self.assertEqual(rv.status_code, 500) self.assert_('Internal Server Error' in rv.data) err = out.getvalue() self.assert_('ZeroDivisionError: ' in err)
def testJSONAttr(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def returnJSON(*args, **kwargs): return unicode(shimehari.request.json['a'] + shimehari.request.json['b']) app.router = shimehari.Router( [Rule('/add', endpoint='returnJSON', methods=['POST'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() rv = c.post('/add', data=shimehari.json.dumps({ 'a': 1, 'b': 2 }), content_type='application/json') self.assertEqual(rv.data, '3')
def testHasChild(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) def index(*args, **kwargs): return 'index' def show(*args, **kwargs): return 'show' router = RESTfulRouter([ Resource(IndexController, [Resource(ChildController)]), RESTfulRule('test', index, show), ]) app = shimehari.Shimehari(__name__) app.setupTemplater() app.router = router app.setControllerFromRouter(router) c = app.testClient() rv = c.get('/index/1', content_type='text/planetext') self.assertEqual(rv.data, "response show")
def testStaticFile(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.staticFolder = 'static' with app.testRequestContext(): print app.appFolder print app.staticFolder rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 12 * 60 * 60) rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 12 * 60 * 60) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600 with app.testRequestContext(): rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 3600) rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 3600) class StaticFileApp(shimehari.Shimehari): def getSendFileMaxAge(self, filename): return 10 app = StaticFileApp(__name__) app.staticFolder = 'static' with app.testRequestContext(): rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 10) rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 10)
def testTryTriggerBeforeFirstRequest(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.testCnt = 0 @app.beforeFirstRequest def doFirst(): app.testCnt = app.testCnt + 1 return app.testCnt def returnHello(*args, **kwargs): return 'Hello' app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])]) app.controllers['returnHello'] = returnHello c = app.testClient() self.assertEqual(app.testCnt, 0) c.get('/hell', content_type='text/planetext') self.assertEqual(app.testCnt, 1) c.get('/hell', content_type='text/planetext') self.assertEqual(app.testCnt, 1)
def testAppContextProvidesCurrentApp(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) with app.appContext(): self.assertEqual(shimehari.currentApp._get_current_object(), app) self.assertEqual(shimehari._appContextStack.top, None)
def testRaiseErrorGenerateURLRequireServerName(self): app = shimehari.Shimehari(__name__) app.config['SERVER_NAME'] = None with app.appContext(): with self.assertRaises(RuntimeError): shimehari.urlFor('index')
def testAddController(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.controllers, {}) app.addController(TestController) self.assertNotEqual(app.controllers, {})
def testNameWithImportError(self): try: shimehari.Shimehari('importerror') except NotImplementedError: self.fail('Shimehari(importaaaa')
def testDebugLogOverride(self): app = shimehari.Shimehari(__name__) app.debug = True app.loggerName = 'shimehari_tests/testaaa' app.logger.level = 10 self.assertEqual(app.logger.level, 10)