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 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 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 testStaticFile(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.setStaticFolder('static') with app.testRequestContext(): 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.setStaticFolder('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 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 testTemplateEscaping(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.setupTemplater() render = shimehari.renderTemplateString with app.testRequestContext(): rv = render('{{"</script>"|tojson|safe }}') self.assertEqual(rv, '"</script>"') rv = render('{{"<\0/script>"|tojson|safe }}') self.assertEqual(rv, '"<\\u0000/script>"')
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 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 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 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 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 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 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 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 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 getConfig(self): u"""現在アプリケーションに適用されているコンフィグを返します。""" configs = ConfigManager.getConfigs() try: # from .config import config configs = ConfigManager.getConfigs() except ImportError: pass if not configs: cfg = Config(self.currentEnv, self.defaultConfig) ConfigManager.addConfig(cfg) return cfg else: return configs[self.currentEnv]
def getConfig(self): u"""現在アプリケーションに適用されているコンフィグを返します。""" configs = ConfigManager.getConfigs() try: # from .config import config configs = ConfigManager.getConfigs() except ImportError: pass if not configs: cfg = Config(self.currentEnv, self.defaultConfig) ConfigManager.addConfig(cfg) return cfg else: return configs[self.currentEnv]
def testJSONBadRequestsContentType(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) @csrfExempt 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) self.assertEqual(rv.mimetype, 'application/json') self.assert_('description' in shimehari.json.loads(rv.data)) self.assert_('<p>' not in shimehari.json.loads(rv.data)['description'])
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 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 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 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 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 testLogger(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assert_(type(app.logger))
def testAddConfig(self): config = Config() self.assertNotEqual(ConfigManager.addConfig(config), TypeError)
def testAddController(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.controllers, {}) app.addController(TestController) self.assertNotEqual(app.controllers, {})
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 testHasConfig(self): config = Config() ConfigManager.addConfig(config) rv = ConfigManager.hasConfig() self.assertEqual(rv, True)
import shimehari import unittest from StringIO import StringIO from logging import StreamHandler from shimehari.testsuite import ShimehariTestCase from werkzeug.routing import Rule from shimehari.configuration import ConfigManager, Config testConfig = Config( 'development', { 'AUTO_SETUP': False, 'SERVER_NAME': 'localhost', 'PREFERRED_URL_SCHEME': 'https' }) ConfigManager.addConfig(testConfig) class ShimehariSubclassingTestCase(ShimehariTestCase): def testSuperessedExceptionLogging(self): class SupressedShimehari(shimehari.Shimehari): def logException(self, exc_info): pass out = StringIO() app = SupressedShimehari(__name__) app.loggerName = 'shimehariTests/test' app.logger.addHandler(StreamHandler(out)) def index(): 1 / 0
def testGetConfig(self): config = Config() ConfigManager.configrations = {} ConfigManager.addConfig(config) self.assertEqual(ConfigManager.getConfig('development'), config)
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)
#!/usr/bin/env python # -*- coding: utf-8 -*- import shimehari import unittest from StringIO import StringIO from logging import StreamHandler from shimehari.testsuite import ShimehariTestCase from werkzeug.routing import Rule from shimehari.configuration import ConfigManager, Config testConfig = Config('development', {'AUTO_SETUP': False, 'SERVER_NAME': 'localhost', 'PREFERRED_URL_SCHEME': 'https'}) ConfigManager.addConfig(testConfig) class ShimehariSubclassingTestCase(ShimehariTestCase): def testSuperessedExceptionLogging(self): class SupressedShimehari(shimehari.Shimehari): def logException(self, exc_info): pass out = StringIO() app = SupressedShimehari(__name__) app.loggerName = 'shimehariTests/test' app.logger.addHandler(StreamHandler(out)) def index(): 1 / 0 app.router = shimehari.Router([Rule('/', endpoint='index', methods=['GET'])])
def testHasConfig(self): config = Config() ConfigManager.addConfig(config) rv = ConfigManager.hasConfig() self.assertEqual(rv, True)
def testGetConfig(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.getConfig(), testConfig)
def testGetConfig(self): config = Config() ConfigManager.configrations = {} ConfigManager.addConfig(config) self.assertEqual(ConfigManager.getConfig('development'), config)
#!/usr/bin/env python # -*- coding: utf-8 -*- u""" =============================== [[Shimehari Config]] config ~~~~~~ =============================== """ from shimehari.configuration import Config, ConfigManager from werkzeug.utils import import_string from shimehari.helpers import getEnviron currentEnv = getEnviron() obj = import_string('config.%s' % currentEnv) config = {} for key in dir(obj): if key.isupper(): config[key] = getattr(obj, key) ConfigManager.addConfig(Config(currentEnv, config))
def testAddConfig(self): config = Config() self.assertNotEqual(ConfigManager.addConfig(config), TypeError)