def test_redirect(self): config.update({"server.webpath": "/coolsite/root"}) response = self.app.get("/redirect") assert response.location == 'http://localhost:80/coolsite/root/foo' self.app.get("/raise_redirect") assert response.location == 'http://localhost:80/coolsite/root/foo' self.app.get("/relative_redirect") assert response.location == 'http://localhost:80/coolsite/root/foo'
def test_throw_out_random(self): """Can append random value to the URL to avoid caching problems.""" response = self.app.get("/test?tg_random=1") assert "Paging all niggles" in response config.update({"tg.strict_parameters": True}) response = self.app.get("/test?tg_random=1", status=200) assert "Paging all niggles" in response response = self.app.get("/test?tg_not_random=1", status=500) assert "unexpected keyword argument" in response
def run(self): import cherrypy from gearshift import toolbox # TODO: remove this check once we convert the whole toolbox to genshi try: import turbokid except ImportError: # we could not import turbokid, the toolbox will crash with # horrible tracebacks... print "Please easy_install turbokid, toolbox cannot run without it" # sys exit with different than zero error code in case someone # is using the error code to know if it worked... sys.exit(2) # Make sure we have full configuration with every option # in it so other plugins or whatever find what they need # when starting even inside the toolblox conf = get_package_name() conf = conf and "%s.config" % conf or None conf = config.config_obj(configfile=self.config, modulename=conf) if 'global' in conf: config.update({'global': conf['global']}) root = SecureObject(toolbox.Toolbox(), from_any_host(self.hostlist), exclude=['noaccess']) cherrypy.tree.mount(root, '/', config=gearshift.config.app) # amend some parameters since we are running from the command # line in order to change port, log methods... config.update({ 'global': { 'server.socket_port': self.port, 'server.webpath': '/', 'server.environment': 'development', 'server.log_to_screen': True, 'autoreload.on': False, 'server.package': 'gearshift.toolbox', 'log_debug_info_filter.on': False, 'tools.identity.failure_url': '/noaccess', 'tools.identity.force_external_redirect': False, 'tg.defaultview': 'kid', 'tg.strict_parameters': False, 'kid.outputformat': 'html default', 'kid.encoding': 'utf-8' } }) gearshift.view.load_engines() if self.noopen: cherrypy.engine.start() else: cherrypy.engine.start_with_callback(self.openbrowser) cherrypy.engine.block()
def start_server(): """Start the server if it's not already.""" if not config.get("cp_started"): cherrypy.engine.start() config.update({"cp_started" : True}) if not config.get("server_started"): startup.startTurboGears() config.update({"server_started" : True})
def test_ignore_parameters(self): config.update({"tg.strict_parameters": True}) response = self.app.get("/test?ignore_me=1", status=500) assert "unexpected keyword argument" in response config.update({"tg.ignore_parameters": ['ignore_me', 'me_too']}) response = self.app.get("/test?ignore_me=1") assert "Paging all niggles" in response response = self.app.get("/test?me_too=1", status=200) assert "Paging all niggles" in response response = self.app.get("/test?me_not=1", status=500) assert "unexpected keyword argument" in response
def setUp(self): testutil.stop_server(tg_only=True) self._visit_on = config.get('tools.visit.on', False) self._visit_source = config.get('tools.visit.source', 'cookie') config.update({'tools.visit.on': True}) self._visit_timeout = config.get('tools.visit.timeout', 20) config.update({'tools.visit.timeout': 50}) self.cookie_name = config.get("tools.visit.cookie.name", 'tg-visit') self._visit_key_param = config.get("tools.visit.form.name", 'tg_visit') self.app = testutil.make_app(VisitRoot) testutil.start_server()
def setUp(self): testutil.stop_server(tg_only = True) self._visit_on = config.get('tools.visit.on', False) self._visit_source = config.get('tools.visit.source', 'cookie') config.update({'tools.visit.on': True}) self._visit_timeout = config.get('tools.visit.timeout', 20) config.update({'tools.visit.timeout': 50}) self.cookie_name = config.get("tools.visit.cookie.name", 'tg-visit') self._visit_key_param = config.get("tools.visit.form.name", 'tg_visit') self.app = testutil.make_app(VisitRoot) testutil.start_server()
def run(self): import cherrypy from gearshift import toolbox # TODO: remove this check once we convert the whole toolbox to genshi try: import turbokid except ImportError: # we could not import turbokid, the toolbox will crash with # horrible tracebacks... print "Please easy_install turbokid, toolbox cannot run without it" # sys exit with different than zero error code in case someone # is using the error code to know if it worked... sys.exit(2) # Make sure we have full configuration with every option # in it so other plugins or whatever find what they need # when starting even inside the toolblox conf = get_package_name() conf = conf and "%s.config" % conf or None conf = config.config_obj(configfile=self.config, modulename=conf) if 'global' in conf: config.update({'global': conf['global']}) root = SecureObject(toolbox.Toolbox(), from_any_host(self.hostlist), exclude=['noaccess']) cherrypy.tree.mount(root, '/', config=gearshift.config.app) # amend some parameters since we are running from the command # line in order to change port, log methods... config.update({'global': { 'server.socket_port': self.port, 'server.webpath': '/', 'server.environment': 'development', 'server.log_to_screen': True, 'autoreload.on': False, 'server.package': 'gearshift.toolbox', 'log_debug_info_filter.on': False, 'tools.identity.failure_url': '/noaccess', 'tools.identity.force_external_redirect': False, 'tg.defaultview': 'kid', 'tg.strict_parameters': False, 'kid.outputformat': 'html default', 'kid.encoding': 'utf-8' }}) gearshift.view.load_engines() if self.noopen: cherrypy.engine.start() else: cherrypy.engine.start_with_callback(self.openbrowser) cherrypy.engine.block()
def setup(m): global tool tool = InternationalizationTool('1.1') os.mkdir(src_dir) tf = open(os.path.join(src_dir, "test.kid"), "w") tf.write(TEMPLATE) tf.close() config.update({ 'i18n.locale_dir': locale_dir, 'i18n.domain': 'testmessages', })
def test_user_password_raw_unicode(self): config.update({"tools.identity.soprovider.encryption_algorithm": "sha1"}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.set_password_raw(u"garçon") u.sync() assert u.password == u"garçon" hub.rollback() hub.end()
def test_allow_json_config(self): """JSON output can be enabled via config.""" config.update({'tg.allow_json':True}) class JSONRoot(controllers.RootController): @expose(template="gearshift.tests.simple") def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="gearshift.tests.simple") app = testutil.make_app(JSONRoot) response = app.get('/allowjsonconfig?tg_format=json') assert response.headers["Content-Type"] == "application/json" config.update({'tg.allow_json': False})
def set_db_uri(dburi, package=None): """Sets the database URI to use either globally or for a specific package. Note that once the database is accessed, calling setDBUri will have no effect. @param dburi: database URI to use @param package: package name this applies to, or None to set the default. """ if package: config.update({"%s.dburi" % package: dburi}) else: config.update({"sqlobject.dburi": dburi})
def set_db_uri(dburi, package=None): """Sets the database URI to use either globally or for a specific package. Note that once the database is accessed, calling setDBUri will have no effect. @param dburi: database URI to use @param package: package name this applies to, or None to set the default. """ if package: config.update({"%s.dburi" % package : dburi}) else: config.update({"sqlobject.dburi" : dburi})
def test_user_password_hashed_md5(self): """Test if a md5 hashed password is stored in the database.""" config.update({"tools.identity.soprovider.encryption_algorithm": "md5"}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.password = "******" u.sync() assert u.password == "5f4dcc3b5aa765d61d8327deb882cf99" hub.rollback() hub.end()
def test_user_password_hashed_sha(self): """Test if a sha hashed password is stored in the database.""" config.update({"tools.identity.soprovider.encryption_algorithm": "sha1"}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.password = "******" u.sync() assert u.password == "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" hub.rollback() hub.end()
def test_user_password_raw_unicode(self): config.update( {'tools.identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.set_password_raw(u'garçon') u.sync() assert u.password == u'garçon' hub.rollback() hub.end()
def setup_module(): basedir = os.path.join(os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))), "tests") locale_dir = os.path.join(basedir, 'locale') config.update({ 'i18n.locale_dir': locale_dir, 'i18n.domain': 'messages', 'i18n.default_locale': 'en', 'i18n.get_locale': lambda: 'en', 'i18n.run_template_filter': False, 'sqlobject.dburi': "sqlite:///:memory:" }) sogettext.create_so_catalog(["en", "fi"], "messages")
def test_strict_parameters(self): config.update({'tg.strict_parameters': True}) try: # check that paginate ordering works with strict parameters as well self.request("/basic1?method=Q&data_tgp_ordering=street", status=200) self.assert_order(16, 2, 3, 4, 5, 6, 7, 8, 9, 10) Spy.assert_ok(self.body, 'ordering', ['street']) # check that old style ordering is not accepted any more self.request("/basic1?method=Q&tg_paginate_ordering=street", status=500) assert ("got an unexpected keyword argument" " 'tg_paginate_ordering'") in self.body finally: config.update({'tg.strict_parameters': False})
def test_templateRetrievalByPath(self): config.update({'server.environment': 'development'}) from turbokid import kidsupport ks = kidsupport.KidSupport() cls = ks.load_template("gearshift.tests.simple") assert cls is not None t = cls() t.someval = "hello" filled = str(t) assert "groovy" in filled assert "html" in filled # the following import should not fail, if everything is working correctly: import gearshift.tests.simple
def test_user_password_hashed_md5(self): """Test if a md5 hashed password is stored in the database.""" config.update( {'tools.identity.soprovider.encryption_algorithm': 'md5'}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.password = '******' u.sync() assert u.password == '5f4dcc3b5aa765d61d8327deb882cf99' hub.rollback() hub.end()
def test_user_password_unicode(self): """Test if we can set a user password which is encoded as unicode (no encryption algorithm).""" config.update({'tools.identity.soprovider.encryption_algorithm': None}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.password = u'garçon' u.sync() assert u.password == u'garçon' hub.rollback() hub.end()
def test_user_password_hashed_sha(self): """Test if a sha hashed password is stored in the database.""" config.update( {'tools.identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.password = '******' u.sync() assert u.password == '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8' hub.rollback() hub.end()
def test_user_password_unicode(self): """Test if we can set a user password which is encoded as unicode (no encryption algorithm).""" config.update({"tools.identity.soprovider.encryption_algorithm": None}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.password = u"garçon" u.sync() assert u.password == u"garçon" hub.rollback() hub.end()
def test_user_password_hashed_sha_unicode(self): """Test if a sha hashed password with unicode characters is stored in the database.""" config.update({"tools.identity.soprovider.encryption_algorithm": "sha1"}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.password = u"garçon" u.sync() assert u.password == "442edb21c491a6e6f502eb79e98614f3c7edf43e" hub.rollback() hub.end()
def test_user_password_raw(self): """Test that we can store raw values in the password field (without being hashed).""" config.update({"tools.identity.soprovider.encryption_algorithm": "sha1"}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.set_password_raw("password") u.sync() assert u.password == "password" hub.rollback() hub.end()
def test_user_password_hashed_md5_unicode(self): """Test if a md5 hashed password with unicode characters is stored in the database.""" config.update({"tools.identity.soprovider.encryption_algorithm": "md5"}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.password = u"garçon" u.sync() assert u.password == "c295c4bb2672ca8c432effc53b40bb1e" hub.rollback() hub.end()
def setup_module(): global users_table, test_table, multi_table, fresh_multi_table config.update({ 'sqlalchemy.dburi': 'sqlite:///:memory:', 'fresh.dburi': 'sqlite:///freshtest.db', }) if os.path.exists('freshtest.db'): os.unlink('freshtest.db') fresh_metadata = get_metadata('fresh') if metadata.is_bound(): metadata.bind = None bind_metadata() metadata.bind.echo = True fresh_metadata.bind.echo = True users_table = Table("users", metadata, Column("user_id", Integer, primary_key=True), Column("user_name", String(40)), Column("password", String(10))) persons_table = Table("persons", metadata, Column("id", Integer, primary_key=True), Column("name", String(40))) addresses_table = Table("addresses", metadata, Column("id", Integer, primary_key=True), Column("address", String(40)), Column("city", String(40)), Column("person_id", Integer, ForeignKey(persons_table.c.id))) multi_table = Table('multi', metadata, Column('id', Integer, primary_key=True)) metadata.create_all() test_table = Table("test", fresh_metadata, Column("id", Integer, primary_key=True), Column("val", String(40))) fresh_multi_table = Table('multi', fresh_metadata, Column('id', Integer, primary_key=True)) fresh_metadata.create_all() mapper(User, users_table) mapper(Person, persons_table) mapper(Address, addresses_table, properties=dict( person=relation(Person, backref='addresses'))) mapper(Test, test_table) start_server()
def test_allow_json_config_false(self): """Make sure JSON can still be restricted with a global config on.""" config.update({'tg.allow_json': False}) class JSONRoot(controllers.RootController): @expose(template="gearshift.tests.simple") def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="gearshift.tests.simple") testutil.stop_server() app = testutil.make_app(JSONRoot) testutil.start_server() response = app.get('/allowjsonconfig') response = app.get('/allowjsonconfig?tg_format=json', status=500) assert response.headers["Content-Type"] == "text/html" config.update({'tg.allow_json': True})
def test_user_password_hashed_sha_unicode(self): """Test if a sha hashed password with unicode characters is stored in the database.""" config.update( {'tools.identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.password = u'garçon' u.sync() assert u.password == '442edb21c491a6e6f502eb79e98614f3c7edf43e' hub.rollback() hub.end()
def test_user_password_hashed_md5_unicode(self): """Test if a md5 hashed password with unicode characters is stored in the database.""" config.update( {'tools.identity.soprovider.encryption_algorithm': 'md5'}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.password = u'garçon' u.sync() assert u.password == 'c295c4bb2672ca8c432effc53b40bb1e' hub.rollback() hub.end()
def test_user_password_raw(self): """Test that we can store raw values in the password field (without being hashed).""" config.update( {'tools.identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.set_password_raw('password') u.sync() assert u.password == 'password' hub.rollback() hub.end()
def test_with_webpath(self): config.update({'server.webpath': '/web/path'}) try: self.request("/basic?data_tgp_no=2") Spy.assert_ok(self.body, 'current_page', 2) Spy.assert_ok(self.body, 'href_first', r"'/web/path/basic?data_tgp_no=1&data_tgp_limit=4'", raw=True) Spy.assert_ok(self.body, 'href_prev', r"'/web/path/basic?data_tgp_no=1&data_tgp_limit=4'", raw=True) Spy.assert_ok(self.body, 'href_next', r"'/web/path/basic?data_tgp_no=3&data_tgp_limit=4'", raw=True) Spy.assert_ok(self.body, 'href_last', r"'/web/path/basic?data_tgp_no=last&data_tgp_limit=4'", raw=True) finally: config.update({'server.webpath': ''})
def setup_module(): basedir = os.path.join( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "tests") locale_dir = os.path.join(basedir, 'locale') config.update({ 'i18n.locale_dir': locale_dir, 'i18n.domain': 'messages', 'i18n.default_locale': 'en', 'i18n.get_locale': lambda: 'en', 'i18n.run_template_filter': False, 'sqlobject.dburi': "sqlite:///:memory:" }) sogettext.create_so_catalog(["en", "fi"], "messages")
def test_get_mime_type_for_format(): assert util.get_mime_type_for_format('plain') == 'text/plain' assert util.get_mime_type_for_format('text') == 'text/plain' assert util.get_mime_type_for_format('html') == 'text/html' assert util.get_mime_type_for_format('xhtml') == 'text/html' assert util.get_mime_type_for_format('xml') == 'text/xml' assert util.get_mime_type_for_format('json') == 'application/json' assert util.get_mime_type_for_format('foo') == 'text/html' config.update({'global': {'tg.format_mime_types': {'xhtml': 'application/xhtml+xml', 'foo': 'text/bar'}}}) assert util.get_mime_type_for_format('xhtml') == 'application/xhtml+xml' assert util.get_mime_type_for_format('json') == 'application/json' assert util.get_mime_type_for_format('foo') == 'text/bar' config.update({'global': {'tg.format_mime_types': {}}}) assert util.get_mime_type_for_format('xhtml') == 'text/html' assert util.get_mime_type_for_format('foo') == 'text/html'
def test_allow_json_config(self): """JSON output can be enabled via config.""" config.update({'tg.allow_json': True}) class JSONRoot(controllers.RootController): @expose(template="gearshift.tests.simple") def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="gearshift.tests.simple") app = testutil.make_app(JSONRoot) response = app.get('/allowjsonconfig?tg_format=json') assert response.headers["Content-Type"] == "application/json" config.update({'tg.allow_json': False})
def test_user_password_hashed_md5_utf8string(self): """Test if a md5 hashed password with unicode characters is stored in the database if the password is entered as str (encoded in UTF-8). This test ensures that the encryption algorithm does handle non-unicode parameters gracefully.""" config.update({"tools.identity.soprovider.encryption_algorithm": "md5"}) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.password = u"garçon".encode("UTF-8") u.sync() assert u.password == "c295c4bb2672ca8c432effc53b40bb1e" hub.rollback() hub.end()
def test_default_output_encoding(self): info = dict(someval="someval") template = "gearshift.tests.simple" headers = {} # default encoding is utf-8 val = view.render(info, template, headers=headers) assert headers.get('Content-Type') == 'text/html; charset=utf-8' # encoding can be changed and will be added to existing content type try: config.update({'kid.encoding': 'iso-8859-1'}) headers['Content-Type'] = 'text/html' view.render(info, template, headers=headers) assert headers.get( 'Content-Type') == 'text/html; charset=iso-8859-1' finally: config.update({'kid.encoding': 'utf-8'})
def test_visit_from_form_with_cookie_fallback(self): """Test if visit key is retrieved from cookie if not found in params.""" _app = self.app try: testutil.stop_server(tg_only = True) config.update({'tools.visit.source': 'form,cookie'}) _app = testutil.make_app(VisitRoot) testutil.start_server() # first visit's cookie print self.app.get("/") first_key = self.app.get("/").raw.get('key') # second request with no params response = self.app.get("/") finally: config.update({'tools.visit.source': self._visit_source}) self.app = _app assert first_key == response.raw['key']
def test_user_password_hashed_md5_utf8string(self): """Test if a md5 hashed password with unicode characters is stored in the database if the password is entered as str (encoded in UTF-8). This test ensures that the encryption algorithm does handle non-unicode parameters gracefully.""" config.update( {'tools.identity.soprovider.encryption_algorithm': 'md5'}) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.password = u'garçon'.encode('UTF-8') u.sync() assert u.password == 'c295c4bb2672ca8c432effc53b40bb1e' hub.rollback() hub.end()
def test_visit_from_form_with_cookie_fallback(self): """Test if visit key is retrieved from cookie if not found in params.""" _app = self.app try: testutil.stop_server(tg_only=True) config.update({'tools.visit.source': 'form,cookie'}) _app = testutil.make_app(VisitRoot) testutil.start_server() # first visit's cookie print self.app.get("/") first_key = self.app.get("/").raw.get('key') # second request with no params response = self.app.get("/") finally: config.update({'tools.visit.source': self._visit_source}) self.app = _app assert first_key == response.raw['key']
def test_user_password_hashed_custom(self): """Test if a custom hashed password is stored in the database.""" config.update({ 'tools.identity.soprovider.encryption_algorithm': 'custom', 'tools.identity.custom_encryption': 'identity.tests.test_identity.mycustomencrypt' }) # force new config values to load startup.startTurboGears() self.app.get('/') hub.begin() u = TG_User.by_user_name('samIam') u.password = '******' u.sync() assert u.password == 'password_custom' hub.rollback() hub.end()
def test_visit_from_form(self): """Test if the visit key is retrieved from the request params.""" _app = self.app try: testutil.stop_server(tg_only=True) config.update({'tools.visit.source': 'cookie,form'}) self.app = testutil.make_app(VisitRoot) testutil.start_server() # first visit's cookie first_key = self.app.get("/").raw.get('key') # second request with no cookies self.app.cookies = {} response = self.app.get("/", params={self._visit_key_param: first_key}) finally: config.update({'tools.visit.source': self._visit_source}) self.app = _app assert first_key == response.raw['key']
def test_visit_from_form(self): """Test if the visit key is retrieved from the request params.""" _app = self.app try: testutil.stop_server(tg_only = True) config.update({'tools.visit.source': 'cookie,form'}) self.app = testutil.make_app(VisitRoot) testutil.start_server() # first visit's cookie first_key = self.app.get("/").raw.get('key') # second request with no cookies self.app.cookies = {} response = self.app.get("/", params={self._visit_key_param: first_key}) finally: config.update({'tools.visit.source': self._visit_source}) self.app = _app assert first_key == response.raw['key']
def test_user_password_hashed_custom(self): """Test if a custom hashed password is stored in the database.""" config.update( { "tools.identity.soprovider.encryption_algorithm": "custom", "tools.identity.custom_encryption": "identity.tests.test_identity.mycustomencrypt", } ) # force new config values to load startup.startTurboGears() self.app.get("/") hub.begin() u = TG_User.by_user_name("samIam") u.password = "******" u.sync() assert u.password == "password_custom" hub.rollback() hub.end()
def setUp(self): # identity requires visit and a failure_url test_config = { 'global': { 'tools.visit.on': True, 'tools.identity.on': True, 'tools.identity.failure_url': '/identity_failed', 'tools.identity.soprovider.encryption_algorithm': None } } original_config = dict() for key in test_config['global']: original_config[key] = config.get(key) self._original_config = original_config #config.configure_loggers(test_config) config.update(test_config['global']) self.root = IdentityRoot testutil.TGTest.setUp(self) self.init_model()
def test_cookie_permanent(self): """Check that the visit cookie can be made permanent.""" permanent = config.get('tools.visit.cookie.permanent', False) try: # set cookie permanent for this test only (needs restart) testutil.stop_server(tg_only = False) config.update({'tools.visit.cookie.permanent': True}) app = testutil.make_app(VisitRoot) testutil.start_server() response = app.get('/') cookies = SimpleCookie(response.headers['Set-Cookie']) morsel = cookies[self.cookie_name] finally: config.update({'tools.visit.cookie.permanent': permanent}) assert morsel['max-age'] == '3000' expires = time.mktime(time.strptime(morsel['expires'], '%a, %d-%b-%Y %H:%M:%S GMT')[:8] + (0,)) should_expire = time.mktime(time.gmtime()) + int(morsel['max-age']) assert abs(should_expire - expires) < 3, (should_expire, expires, should_expire - expires)
def setUp(self): # identity requires visit and a failure_url test_config = { "global": { "tools.visit.on": True, "tools.identity.on": True, "tools.identity.failure_url": "/identity_failed", "tools.identity.soprovider.encryption_algorithm": None, } } original_config = dict() for key in test_config["global"]: original_config[key] = config.get(key) self._original_config = original_config # config.configure_loggers(test_config) config.update(test_config["global"]) self.root = IdentityRoot testutil.TGTest.setUp(self) self.init_model()
def test_cookie_permanent(self): """Check that the visit cookie can be made permanent.""" permanent = config.get('tools.visit.cookie.permanent', False) try: # set cookie permanent for this test only (needs restart) testutil.stop_server(tg_only=False) config.update({'tools.visit.cookie.permanent': True}) app = testutil.make_app(VisitRoot) testutil.start_server() response = app.get('/') cookies = SimpleCookie(response.headers['Set-Cookie']) morsel = cookies[self.cookie_name] finally: config.update({'tools.visit.cookie.permanent': permanent}) assert morsel['max-age'] == '3000' expires = time.mktime( time.strptime(morsel['expires'], '%a, %d-%b-%Y %H:%M:%S GMT')[:8] + (0, )) should_expire = time.mktime(time.gmtime()) + int(morsel['max-age']) assert abs(should_expire - expires) < 3, (should_expire, expires, should_expire - expires)
def test_content_types(self): info = dict(someval="someval") template = "gearshift.tests.simple" headers = {} view.render(info, template, headers=headers) assert headers.get('Content-Type') == 'text/html; charset=utf-8' headers = {} view.render(info, template, headers=headers, format='html') assert headers.get('Content-Type') == 'text/html; charset=utf-8' headers = {} view.render(info, template, headers=headers, format='html-strict') assert headers.get('Content-Type') == 'text/html; charset=utf-8' headers = {} view.render(info, template, headers=headers, format='xhtml') assert headers.get('Content-Type') == 'text/html; charset=utf-8' headers = {} view.render(info, template, headers=headers, format='xhtml-strict') assert headers.get('Content-Type') == 'text/html; charset=utf-8' headers = {} view.render(info, template, headers=headers, format='xml') assert headers.get('Content-Type') == 'text/xml; charset=utf-8' headers = {} view.render(info, template, headers=headers, format='json') assert headers.get('Content-Type') == 'application/json' config.update({ 'global': { 'tg.format_mime_types': { 'xhtml': 'application/xhtml+xml' } } }) headers = {} view.render(info, template, headers=headers, format='xhtml') assert headers.get( 'Content-Type') == 'application/xhtml+xml; charset=utf-8' headers = {} view.render(info, template, headers=headers, format='xhtml-strict') assert headers.get( 'Content-Type') == 'application/xhtml+xml; charset=utf-8' config.update({'global': {'tg.format_mime_types': {}}})
def test_strict_parameters(self): config.update({'tg.strict_parameters': True}) try: # check that paginate works with strict parameters as well self.request("/basic?data_tgp_no=2", status=200) assert '"data": [4, 5, 6, 7]' in self.body Spy.assert_ok(self.body, 'current_page', 2) self.request('/custom_limit?data_tgp_limit=2', status=200) assert '"data": [0, 1]' in self.body Spy.assert_ok(self.body, 'limit', 2) self.request("/default_max_pages?data_tgp_no=5", status=200) assert '"data": [40, 41, 42, ' in self.body Spy.assert_ok(self.body, 'pages', xrange(3, 8)) # check that wrong and old style parameters are not accepted self.request("/basic?data_tgp_rubbish=2", status = 500) assert ("basic() got an unexpected keyword argument" " 'data_tgp_rubbish'") in self.body self.request("/basic?tg_paginate_no=2", status=500) assert ("basic() got an unexpected keyword argument" " 'tg_paginate_no'") in self.body finally: config.update({'tg.strict_parameters': False})
def test_cookie_expires(self): """Test if the visit timeout mechanism works.""" timeout = config.get('tools.visit.timeout', 50) _app = self.app try: # set expiration to one second for this test only testutil.stop_server(tg_only=True) config.update({'tools.visit.timeout': 1.0 / 60}) self.app = testutil.make_app(VisitRoot) testutil.start_server() response = self.app.get("/") morsel = response.cookies_set[self.cookie_name] time.sleep(2) # 2 seconds response = self.app.get("/", headers=cookie_header(response)) finally: config.update({'tools.visit.timeout': timeout}) self.app = _app assert response.cookies_set[ self.cookie_name] != morsel, \ 'cookie values should not match' assert response.raw['new'], \ 'this should be a new visit, as the cookie has expired'
def test_strict_parameters(self): config.update({'tg.strict_parameters': True}) try: # check that paginate works with strict parameters as well self.request("/basic?data_tgp_no=2", status=200) assert '"data": [4, 5, 6, 7]' in self.body Spy.assert_ok(self.body, 'current_page', 2) self.request('/custom_limit?data_tgp_limit=2', status=200) assert '"data": [0, 1]' in self.body Spy.assert_ok(self.body, 'limit', 2) self.request("/default_max_pages?data_tgp_no=5", status=200) assert '"data": [40, 41, 42, ' in self.body Spy.assert_ok(self.body, 'pages', xrange(3, 8)) # check that wrong and old style parameters are not accepted self.request("/basic?data_tgp_rubbish=2", status=500) assert ("basic() got an unexpected keyword argument" " 'data_tgp_rubbish'") in self.body self.request("/basic?tg_paginate_no=2", status=500) assert ("basic() got an unexpected keyword argument" " 'tg_paginate_no'") in self.body finally: config.update({'tg.strict_parameters': False})
def test_cookie_expires(self): """Test if the visit timeout mechanism works.""" timeout = config.get('tools.visit.timeout', 50) _app = self.app try: # set expiration to one second for this test only testutil.stop_server(tg_only = True) config.update({'tools.visit.timeout': 1.0/60}) self.app = testutil.make_app(VisitRoot) testutil.start_server() response = self.app.get("/") morsel = response.cookies_set[self.cookie_name] time.sleep(2) # 2 seconds response = self.app.get("/", headers=cookie_header(response)) finally: config.update({'tools.visit.timeout': timeout}) self.app = _app assert response.cookies_set[ self.cookie_name] != morsel, \ 'cookie values should not match' assert response.raw['new'], \ 'this should be a new visit, as the cookie has expired'