def test_invalid_createrepo_command_fail(self): update({'beaker.createrepo_command': 'iamnotarealcommand'}) rpm_file = pkg_resources.resource_filename('bkr.server.tests', \ 'tmp-distribution-beaker-task_test-2.0-5.noarch.rpm') copy(rpm_file, self.tasklibrary.rpmspath) with self.assertRaises(OSError): self.tasklibrary.update_repo()
def setUp(self): self.defaultview = config.get('tg.defaultview', 'kid') config.update({ 'toscawidgets.on': True, 'tg.defaultview': 'genshi' }) super(ToscaWidgetsTest, self).setUp()
def test_content_types(self): info = dict(someval="someval") template = "turbogears.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 register_static_directory(modulename, directory): """ Sets up a static directory for JavaScript and css files. You can refer to this static directory in templates as ${tg.widgets}/modulename """ directory = os.path.abspath(directory) config.update({"/tg_widgets/%s" % modulename: {"static_filter.on": True, "static_filter.dir": directory}})
def enable_csrf(): '''A startup function to setup :ref:`CSRF-Protection`. This should be run at application startup. Code like the following in the start-APP script or the method in :file:`commands.py` that starts it:: from turbogears import startup from fedora.tg.util import enable_csrf startup.call_on_startup.append(enable_csrf) If we can get the :ref:`CSRF-Protection` into upstream :term:`TurboGears`, we might be able to remove this in the future. .. versionadded:: 0.3.10 Added to enable :ref:`CSRF-Protection` ''' # Override the turbogears.url function with our own # Note, this also changes turbogears.absolute_url since that calls # turbogears.url turbogears.url = url turbogears.controllers.url = url # Ignore the _csrf_token parameter ignore = config.get('tg.ignore_parameters', []) if '_csrf_token' not in ignore: ignore.append('_csrf_token') config.update({'tg.ignore_parameters': ignore}) # Add a function to the template tg stdvars that looks up a template. turbogears.view.variable_providers.append(add_custom_stdvars)
def test_new_text_format(self): """Verify that our view is able to send new text format to Genshi.""" # make sure we have asked for new format in the config new_syntax = config.get("genshi.new_text_syntax", False) config.update({"genshi.new_text_syntax": True}) # we need to reload the engines for the config changes to take effect view.load_engines() # load our expected result in memory expected_result = 'Dear Florent Aide\nYour items:\n * Apples\n * Bananas\n * Cherries\n\n' info = dict( name=u"Florent Aide", itemlist=[u'Apples', u'Bananas', u'Cherries'] ) template = "genshi-text:turbogears.tests.genshi_new_text_format" headers = {} val = view.render(info, template, headers=headers, format="text") config.update({"genshi.new_text_syntax": new_syntax}) print "Got this:" print "*" * 35 print "%r" % val print "*" * 35 print "Expected that:" print "*" * 35 print "%r" % expected_result print "*" * 35 assert val == expected_result
def test_default_output_encoding(self): info = dict(someval="someval") # default encoding is utf-8 val = view.render(info, template="turbogears.tests.simple") assert 'utf-8' in view.cherrypy.response.headers["Content-Type"] config.update({'tg.defaultview':'kid', 'kid.encoding':'iso-8859-1'}) val = view.render(info, template="turbogears.tests.simple") assert 'iso-8859-1' in view.cherrypy.response.headers["Content-Type"]
def test_authenticate_header(self): """Test that identity returns correct WWW-Authenticate header.""" response = self.app.get('/logged_in_only', status=403) assert 'WWW-Authenticate' not in response.headers config.update({'identity.http_basic_auth': True, 'identity.http_auth_realm': 'test realm'}) response = self.app.get('/logged_in_only', status=401) assert response.headers['WWW-Authenticate'] == 'Basic realm="test realm"'
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 setUp(self): self._visit_on = config.get('visit.on', False) self._visit_source = config.get('visit.source', 'cookie') config.update({'visit.on': True}) self._visit_timeout = config.get('visit.timeout', 20) config.update({'visit.timeout': 50}) self.cookie_name = config.get("visit.cookie.name", 'tg-visit') self._visit_key_param = config.get("visit.form.name", 'tg_visit') cherrypy.root = VisitRoot()
def start_server(): """Start the server if it's not already started.""" if not config.get("cp_started"): cherrypy.server.start(server_class=None, init_only=True) config.update({"cp_started" : True}) if not config.get("server_started"): startup.startTurboGears() config.update({"server_started" : True})
def test_redirect(self): config.update({"server.webpath": "/coolsite/root"}) startup.startTurboGears() testutil.create_request("/coolsite/root/subthing/") try: redirect("/foo") assert False, "redirect exception should have been raised" except cherrypy.HTTPRedirect, e: assert "http://localhost/coolsite/root/subthing/foo" in e.urls
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 setUp(self): self._identity_on = config.get('identity.on', False) config.update({'identity.on': False}) try: self._provider = cherrypy.request.identityProvider except AttributeError: self._provider= None cherrypy.request.identityProvider = None startup.startTurboGears() testutil.DBTest.setUp(self)
def test_suppress_mochikit(): """MochiKit inclusion can be suppressed""" config.update({"global":{"tg.mochikit_suppress" : True}}) suppressed = app.get("/usemochi") # repair the fixture config.update({"global":{"tg.mochikit_suppress" : False}}) included = app.get("/usemochi") assert "MochiKit.js" not in suppressed.body assert "MochiKit.js" in included.body
def test_createrepo_c_command(self): update({'beaker.createrepo_command': 'createrepo_c'}) rpm_file = pkg_resources.resource_filename('bkr.server.tests', \ 'tmp-distribution-beaker-task_test-2.0-5.noarch.rpm') copy(rpm_file, self.tasklibrary.rpmspath) try: self.tasklibrary.update_repo() except OSError, e: if e.errno is errno.ENOENT: raise SkipTest('Could not find createrepo_c')
def _config_update(self, data=None, **kw): self.config_backup = {} if not data: data = {} else: data = data.copy() data.update(kw) for k in data: self.config_backup[k] = config.get(k) config.update(data)
def setUp(self): self._identity_on = config.get('identity.on', False) config.update({'identity.on': False}) try: self._provider = cherrypy.request.identityProvider except AttributeError: self._provider = None cherrypy.request.identityProvider = None startup.startTurboGears() testutil.DBTest.setUp(self)
def test_throw_out_random(self): """Can append random value to the URL to avoid caching problems.""" testutil.create_request("/test?tg_random=1") assert "Paging all niggles" in cherrypy.response.body[0] config.update({"tg.strict_parameters": True}) testutil.create_request("/test?tg_random=1") assert cherrypy.response.status.startswith("200") assert "Paging all niggles" in cherrypy.response.body[0] testutil.create_request("/test?tg_not_random=1") assert cherrypy.response.status.startswith("500") assert not hasattr(cherrypy.root, "errors")
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 test_suppress_mochikit(): """MochiKit inclusion can be suppressed""" config.update({"global": {"tg.mochikit_suppress": True}}) testutil.create_request("/usemochi") suppressed_body = cherrypy.response.body[0] # repair the fixture config.update({"global": {"tg.mochikit_suppress": False}}) testutil.create_request("/usemochi") included_body = cherrypy.response.body[0] assert "MochiKit.js" not in suppressed_body assert "MochiKit.js" in included_body
def setUp(self): global tool tool = InternationalizationTool('1.1') self.work_dir = tempfile.mkdtemp() self.src_dir = os.path.join(self.work_dir, 'src') self.locale_dir = os.path.join(self.work_dir, 'locale') os.mkdir(self.src_dir) config.update({ 'i18n.locale_dir': self.locale_dir, 'i18n.domain': 'testmessages', })
def test_user_password_hashed_md5(self): """Test if a md5 hashed password is stored in the database.""" config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 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_include_widgets(self): """Any widget can be included everywhere by setting tg.include_widgets.""" config.update({'global': {'tg.include_widgets': [ 'turbogears.tests.test_toscawidgets.js_link', 'turbogears.tests.test_toscawidgets.css_src']}}) response = self.app.get('/show_table_form') config.update({'global': {'tg.include_widgets': []}}) assert "foo.js" in response assert "body {font-size: 1.em;}" in response assert "foo.css" not in response assert "alert('head');" not in response
def test_user_password_hashed_md5_unicode(self): """Test if a non-ascii md5 hashed password is stored in the database.""" config.update({'identity.soprovider.encryption_algorithm': 'md5'}) 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_unicode(self): """Test that unicode passwords are encrypted correctly""" config.update({'identity.soprovider.encryption_algorithm':'sha1'}) 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(self): test_config = {'global': { 'visit.on': True, 'identity.on': True, 'identity.source': 'form, http_auth, visit'}} if not self.config: original_config = dict() for key in test_config['global']: original_config[key] = config.get(key) self.config = original_config config.update(test_config['global'])
def test_user_password_hashed_sha(self): """Test if a sha hashed password is stored in the database.""" config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 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_hashed_sha_unicode(self): """Test if a non-ascii sha hashed password is stored in the database.""" config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) 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_unicode(self): """Test if we can set a non-ascii user password (no encryption).""" config.update({'identity.soprovider.encryption_algorithm': None}) 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_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 test_external_redirect_with_funky_params(self): """Test that external redirection properly handles funky parameters.""" config.update({'identity.force_external_redirect': True}) testutil.create_request('/logged_in_only?' 'a-0.x=1&a-0.y=2&a-1.x=3&a-1.y=4') path, params = cherrypy.response.headers['Location'].split('?', 1) assert path.endswith('/identity_failed') params = params.split('&') params.sort() params = '&'.join(params) assert params == ('a-0.x=1&a-0.y=2&a-1.x=3&a-1.y=4' '&forward_url=%2Flogged_in_only')
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({'global': {"%s.dburi" % package: dburi}}) else: config.update({'global': {"sqlobject.dburi": dburi}})
def test_user_password_raw_unicode(self): config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() testutil.create_request('/') 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="turbogears.tests.simple")] def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="turbogears.tests.simple") cherrypy.root = JSONRoot() testutil.create_request('/allowjsonconfig?tg_format=json') assert cherrypy.response.headers["Content-Type"] == "application/json" config.update({'tg.allow_json': False})
def tearDown(self): # implementation copied from turbogears.testutil.stop_server. # The only change is that cherrypy.root is set to None # AFTER stopTurbogears has been called so that wsmeext.tg11 # can correctly uninstall its filter. if config.get("cp_started"): cherrypy.server.stop() config.update({"cp_started": False}) if config.get("server_started"): startup.stopTurboGears() config.update({"server_started": False})
def test_allow_json_config_false(self): """Make sure JSON can still be restricted with a global config on.""" config.update({'tg.allow_json': True}) class JSONRoot(controllers.RootController): [expose(template="turbogears.tests.simple")] def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="turbogears.tests.simple") cherrypy.root = JSONRoot() testutil.create_request('/allowjson?tg_format=json') assert cherrypy.response.headers["Content-Type"] == "text/html" config.update({'tg.allow_json': False})
def test_user_password_unicode(self): """Test if we can set a non-ascii user password (no encryption).""" config.update({'identity.soprovider.encryption_algorithm': None}) # force new config values to load startup.startTurboGears() testutil.create_request('/') 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({'identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() testutil.create_request('/') 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_hashed_md5(self): """Test if a md5 hashed password is stored in the database.""" config.update({'identity.soprovider.encryption_algorithm': 'md5'}) # force new config values to load startup.startTurboGears() testutil.create_request('/') 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_md5_unicode(self): """Test if a non-ascii md5 hashed password is stored in the database.""" config.update({'identity.soprovider.encryption_algorithm': 'md5'}) # force new config values to load startup.startTurboGears() testutil.create_request('/') 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_hashed_sha_unicode(self): """Test if a non-ascii sha hashed password is stored in the database.""" config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() testutil.create_request('/') 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_templateRetrievalByPath(self): config.update({'server.environment' : 'development'}) from turbokid import kidsupport ks = kidsupport.KidSupport() cls = ks.load_template("turbogears.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 turbogears.tests.simple
def test_ignore_parameters(self): config.update({"tg.strict_parameters": True}) testutil.create_request("/test?ignore_me=1") assert cherrypy.response.status.startswith("500") assert not hasattr(cherrypy.root, "errors") config.update({"tg.ignore_parameters": ['ignore_me', 'me_too']}) testutil.create_request("/test?ignore_me=1") assert "Paging all niggles" in cherrypy.response.body[0] testutil.create_request("/test?me_too=1") assert cherrypy.response.status.startswith("200") assert "Paging all niggles" in cherrypy.response.body[0] testutil.create_request("/test?me_not=1") assert cherrypy.response.status.startswith("500") assert not hasattr(cherrypy.root, "errors")
def test_user_password_raw(self): """Test that we can store raw values in the password field (without being hashed).""" config.update({'identity.soprovider.encryption_algorithm': 'sha1'}) # force new config values to load startup.startTurboGears() testutil.create_request('/') 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 register_static_directory(modulename, directory): """Set up a static directory for JavaScript and CSS files. You can refer to this static directory in templates as ${tg.widgets}/modulename """ directory = os.path.abspath(directory) config.update({ '/tg_widgets/%s' % modulename: { 'static_filter.on': True, 'static_filter.dir': directory } })
def test_visit_from_form(self): """Test if the visit key is retrieved from the request params.""" try: config.update({'visit.source': 'cookie,form'}) # first visit's cookie testutil.create_request("/") first_key = cherrypy.response.body[0].strip() # second request with no cookies post_data = StringIO(urlencode({self._visit_key_param: first_key})) testutil.create_request("/", method='POST', rfile=post_data) second_key = cherrypy.response.body[0].strip() finally: config.update({'visit.source': self._visit_source}) assert first_key == second_key
def test_visit_from_form_with_cookie_fallback(self): """Test if visit key is retrieved from cookie if not found in params.""" try: config.update({'visit.source': 'form,cookie'}) # first visit's cookie testutil.create_request("/") first_key = cherrypy.response.body[0].strip() # second request with no cookies morsel = cherrypy.response.simple_cookie[self.cookie_name] testutil.create_request("/", headers=cookie_header(morsel)) second_key = cherrypy.response.body[0].strip() finally: config.update({'visit.source': self._visit_source}) assert first_key == second_key
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_external_redirect(self): """Test that external redirection at identity failures works.""" config.update({ 'identity.failure_url': 'test_login', 'identity.force_external_redirect': True }) testutil.create_request('/logged_in_only?a=1&b=2') firstline = cherrypy.response.body[0] assert 'identity_failed_answer' not in firstline, firstline path, params = cherrypy.response.headers['Location'].split('?', 1) assert path.endswith('/test_login') params = params.split('&') params.sort() params = '&'.join(params) assert params == 'a=1&b=2&forward_url=%2Flogged_in_only'
def test_mochikit_nowhere(): """Setting tg.mochikit_suppress will prevent including it everywhere""" config.update({"global": {"tg.mochikit_all": True}}) config.update({"global": {"tg.mochikit_suppress": True}}) testutil.create_request("/") config.update({"global": {"tg.mochikit_all": False}}) config.update({"global": {"tg.mochikit_suppress": False}}) assert "MochiKit.js" not in cherrypy.response.body[0]