def test_old_visit(self): """Test if we can track a visitor over time.""" testutil.create_request("/") # first visit's cookie morsel = cherrypy.response.simple_cookie[self.cookie_name] testutil.create_request("/", headers=cookie_header(morsel)) assert not visit.current().is_new
def test_json_output(self): testutil.create_request("/test?tg_format=json") import simplejson values = simplejson.loads(cherrypy.response.body[0]) assert values == dict(title="Foobar", mybool=False, someval="niggles", tg_flash=None) assert cherrypy.response.headers["Content-Type"] == "application/json"
def test_validation_nested(self): """Validation is not repeated in nested method call""" cherrypy.root.value = None testutil.create_request("/nestedcall?value=true") assert cherrypy.root.value == 'True' testutil.create_request("/nestedcall?value=false") assert cherrypy.root.value == 'False'
def test_explicit_json(self): testutil.create_request("/explicitjson") assert '"title": "Blub"' in cherrypy.response.body[0] assert cherrypy.response.headers["Content-Type"] == "application/json" testutil.create_request("/explicitjson?tg_format=json") assert '"title": "Blub"' in cherrypy.response.body[0] assert cherrypy.response.headers["Content-Type"] == "application/json"
def test_gettingjsonviaaccept(): create_request("/with_json_via_accept", headers=dict(Accept="text/javascript")) print "\n".join(logged) body = cherrypy.response.body[0] print body assert '"title": "Foobar"' in body
def test_flash_unicode(self): """flash with unicode objects should work""" testutil.create_request("/flash_unicode?tg_format=json") import simplejson values = simplejson.loads(cherrypy.response.body[0]) assert values["tg_flash"] == u"\xfcnicode" assert not cherrypy.response.simple_cookie.has_key("tg_flash")
def test_recursiveErrorHandler(self): """Recursive error handler.""" testutil.create_request("/recursiveerror?bar=abc") self.failUnless("Recursive error handler" in cherrypy.response.body[0]) testutil.create_request("/recursiveerror?bar=1") self.failUnless("Recursive error provider" in cherrypy.response.body[0])
def test_required_fields(): """ Required field are automatically discovered from the form validator and marked with the "requiredfield" css class. """ class MyFields(widgets.WidgetsList): name = widgets.TextField(validator=validators.String()) comment = widgets.TextArea(validator=validators.String(not_empty=True)) form = widgets.TableForm(fields=MyFields()) class MyRoot(turbogears.controllers.RootController): def test(self): return dict(form=form) test = turbogears.expose(template=".form")(test) cherrypy.root = MyRoot() testutil.create_request("/test") output = cherrypy.response.body[0].lower() print output name_p = 'name="comment"' class_p = 'class="textarea requiredfield"' assert (re.compile('.*'.join([class_p, name_p])).search(output) or re.compile('.*'.join([name_p, class_p])).search(output) ) name_p = 'name="name"' class_p = 'class="textfield"' assert (re.compile('.*'.join([class_p, name_p])).search(output) or re.compile('.*'.join([name_p, class_p])).search(output) )
def test_validation_chained(self): """Validation is not repeated if it already happened""" cherrypy.root.value = None testutil.create_request("/errorchain?value=true") assert cherrypy.root.value is None testutil.create_request("/errorchain?value=notbool") assert cherrypy.root.value == "notbool"
def test_explicit_checks_in_restricted_subdirectory(self): """Test that explicit permission checks in a protected directory is handled as expected""" testutil.create_request('/peon_area/in_other_group_explicit_check?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'in_other_group' in firstline, firstline
def test_session_freshness(): """Check for session freshness. Changes made to the data in thread B should be reflected in thread A. """ fresh_metadata.bind.execute(test_table.insert(), dict(id=1, val='a')) cherrypy.root = FreshRoot() create_request("/test1") assert cherrypy.response.status.startswith("200") assert 'AssertionError' not in cherrypy.response.body[0] # Call test2 in a different thread class ThreadB(threading.Thread): def run(self): create_request("/test2") assert cherrypy.response.status.startswith("200") assert 'AssertionError' not in cherrypy.response.body[0] thrdb = ThreadB() thrdb.start() thrdb.join() create_request("/test3") assert cherrypy.response.status.startswith("200") assert 'AssertionError' not in cherrypy.response.body[0]
def test_redirect_to_path(self): for path_type in ("str", "list", "tuple"): for path in ("subthing", "/subthing"): url = "/redirect_to_path_%s?path=%s" % (path_type, path) testutil.create_request(url) assert cherrypy.response.status.startswith("302"), url assert cherrypy.response.headers["Location"] == "http://localhost/subthing/index", url
def test_decoratator_in_restricted_subdirectory(self): """Test that we can require a different permission in a protected subdirectory.""" testutil.create_request('/peon_area/in_other_group?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'in_other_group' in firstline, firstline
def test_user_lacks_permission(self): """Test that a user is denied acces if they don't have the proper permission.""" testutil.create_request('/has_boss_permission?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'identity_failed_answer' in firstline, firstline assert cherrypy.response.status == "401 Unauthorized"
def test_bad_login(self): """Test that we are denied access if we provide a bad login.""" testutil.create_request('/logged_in_only?' 'user_name=samIam&password=wrong&login=Login') firstline = cherrypy.response.body[0] assert 'identity_failed_answer' in firstline, firstline assert cherrypy.response.status == "401 Unauthorized"
def test_require_group_viewable(self): """Test that a user with proper group membership can see a restricted url.""" testutil.create_request('/in_peon_group?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'in_peon_group' in firstline, firstline user = TG_User.by_user_name("samIam")
def test_user_not_in_right_group(self): """Test that a user is denied access if they aren't in the right group.""" testutil.create_request('/in_admin_group?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'identity_failed_answer' in firstline, firstline assert cherrypy.response.status == "401 Unauthorized"
def test_require_group(self): """Test that an anonymous user can not access resource protected by require(in_group(...))""" testutil.create_request('/in_peon_group') firstline = cherrypy.response.body[0] assert 'identity_failed_answer' in firstline, firstline assert cherrypy.response.status == "401 Unauthorized"
def test_deny_anonymous_viewable(self): """Test that a logged in user can see an resource blocked from anonymous users.""" testutil.create_request('/logged_in_only?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'logged_in_only' in firstline, firstline
def test_old_visit(self): "Test if we can track a visitor over time." testutil.create_request("/") morsel = cherrypy.response.simple_cookie[self.cookie_name] #first visit's cookie testutil.create_request("/", headers=cookie_header(morsel)) assert not turbogears.visit.current().is_new turbogears.startup.stopTurboGears()
def test_validation_nested(self): """Validation is not repeated in nested method call""" cherrypy.root.value = None testutil.create_request("/nestedcall?value=true") assert cherrypy.root.value == "True" testutil.create_request("/nestedcall?value=false") assert cherrypy.root.value == "False"
def test_restricted_subdirectory_viewable(self): """Test that we can access a restricted subdirectory if we have proper credentials.""" testutil.create_request('/peon_area/index?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'restricted_index' in firstline, firstline
def test_basic_urls(self): testutil.create_request("/") assert "/foo" == url("/foo") assert "foo/bar" == url(["foo", "bar"]) assert url("/foo", bar=1, baz=2) in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"] assert url("/foo", dict(bar=1, baz=2)) in ["/foo?bar=1&baz=2", "/foo?baz=2&bar=1"] assert url("/foo", dict(bar=1, baz=None)) == "/foo?bar=1"
def test_flash_plain(self): """flash with strings should work""" testutil.create_request("/flash_plain?tg_format=json") import simplejson values = simplejson.loads(cherrypy.response.body[0]) assert values["tg_flash"] == "plain" assert not cherrypy.response.simple_cookie.has_key("tg_flash")
def test_rows_column_number(self): #Control that the number of columns match the number of fields in the model cherrypy.root.catwalk = CatWalk(browse) testutil.create_request("/catwalk/browse/?object_name=Artist&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) assert len(values['rows'][0]) == 4
def test_validation_chained(self): """Validation is not repeated if it already happened""" cherrypy.root.value = None testutil.create_request("/errorchain?value=true") assert cherrypy.root.value is None testutil.create_request("/errorchain?value=notbool") assert cherrypy.root.value == 'notbool'
def test_required_fields(): """ Required field are automatically discovered from the form validator and marked with the "requiredfield" css class. """ class MyFields(widgets.WidgetsList): name = widgets.TextField(validator=validators.String()) comment = widgets.TextArea(validator=validators.String(not_empty=True)) form = widgets.TableForm(fields=MyFields()) class MyRoot(turbogears.controllers.RootController): def test(self): return dict(form=form) test = turbogears.expose(template=".form")(test) cherrypy.root = MyRoot() testutil.create_request("/test") output = cherrypy.response.body[0].lower() print output name_p = 'name="comment"' class_p = 'class="textarea requiredfield"' assert (re.compile('.*'.join([class_p, name_p])).search(output) or re.compile('.*'.join([name_p, class_p])).search(output)) name_p = 'name="name"' class_p = 'class="textfield"' assert (re.compile('.*'.join([class_p, name_p])).search(output) or re.compile('.*'.join([name_p, class_p])).search(output))
def test_table_widget_js(): """ The TableForm Widget can require JavaScript and CSS resources. Addresses ticket #425. Should be applicable to any widget. """ class MyTableWithJS(widgets.TableForm): javascript = [ widgets.JSLink(mod=widgets.static, name="foo.js"), widgets.JSSource("alert('hello');") ] css = [widgets.CSSLink(mod=widgets.static, name="foo.css")] form = MyTableWithJS(fields=[widgets.TextField(name='title')]) class MyRoot(turbogears.controllers.RootController): def test(self): return dict(form=form) test = turbogears.expose(template=".form")(test) cherrypy.root = MyRoot() testutil.create_request("/test") output = cherrypy.response.body[0] assert 'foo.js' in output assert "alert('hello');" in output assert 'foo.css' in output
def test_form_translation_new_style(): """Form input is translated into properly converted parameters""" root = MyRoot() cherrypy.root = root testutil.create_request("/testform_new_style?name=ed&date=11/05/2005&age=5&") assert root.name == "ed" assert root.age == 5
def request(self, url): create_request(url) self.body = cherrypy.response.body[0] self.status = cherrypy.response.status if "fail: " in self.body: print self.body assert False, "Spy alert! Check body output for details..."
def test_form_translation(): """Form input is translated into properly converted parameters""" root = MyRoot() cherrypy.root = root testutil.create_request("/testform?name=ed&date=11/05/2005&age=5") assert root.name == "ed" assert root.age == 5
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]
def test_throwing_identity_exception_in_restricted_subdirectory(self): """Test that throwing an IdentityException in a protected directory is handled as expected""" testutil.create_request('/peon_area/in_admin_group_explicit_check?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'identity_failed' in firstline, firstline assert cherrypy.response.status == "401 Unauthorized"
def test_decoratator_failure_in_restricted_subdirectory(self): """Test that we can get an identity failure from a decorator in a restricted subdirectory""" testutil.create_request('/peon_area/in_admin_group?' 'user_name=samIam&password=secret&login=Login') firstline = cherrypy.response.body[0] assert 'identity_failed_answer' in firstline, firstline assert cherrypy.response.status == "401 Unauthorized"
def test_addremove_related_joins(self): # check the update_join function when nondefault add/remove are used artist = self.model.Artist.get(1) assert len(artist.plays_instruments) == 0 testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1%2C2&tg_format=json") assert len(artist.plays_instruments) == 2 testutil.create_request("/catwalk/updateJoins?objectName=Artist&id=1&join=plays_instruments&joinType=&joinObjectName=Instrument&joins=1&tg_format=json") assert len(artist.plays_instruments) == 1, str(artist.plays_instruments)
def test_gettinghtml(): global logged capture_log("turbogears.controllers") create_request("/with_json") logged = get_log() body = cherrypy.response.body[0] print body assert "Paging all foo" in body
def test_implicitErrorHandler(self): """Implicit error handling.""" testutil.create_request("/impliciterror?bar=abc") self.failUnless("Implicit error handler" in cherrypy.response.body[0]) testutil.create_request("/impliciterror?bar=1") self.failUnless("Implicit error provider" in cherrypy.response.body[0])
def test_getting_json_with_accept_but_using_tg_format(): capture_log("turbogears.controllers") create_request("/with_json_via_accept?tg_format=json") print_log() print "\n".join(logged) body = cherrypy.response.body[0] print body assert '"title": "Foobar"' in body
def test_run_with_trans(self): """run_with_transaction is called only on topmost exposed method""" oldrwt = database.run_with_transaction database.run_with_transaction = cherrypy.root.rwt testutil.create_request("/nestedcall?value=true") database.run_with_transaction = oldrwt assert cherrypy.root.value assert cherrypy.root.rwt_called == 1
def test_redirect_to_path(self): for path_type in ('str', 'list', 'tuple'): for path in ('subthing', '/subthing'): url = "/redirect_to_path_%s?path=%s" % (path_type, path) testutil.create_request(url) assert cherrypy.response.status.startswith("302"), url assert (cherrypy.response.headers['Location'] == 'http://localhost/subthing/index'), url
def test_require_expose_required_permission(self): ''' Test that the decorator exposes the correct permissions via _require attribute on the actual method. ''' testutil.create_request('/test_exposed_require') firstline= cherrypy.response.body[0] assert 'require is exposed' in firstline, firstline
def test_default_format(self): """The default format can be set via expose""" testutil.create_request("/returnjson") firstline = cherrypy.response.body[0] assert '"title": "Foobar"' in firstline testutil.create_request("/returnjson?tg_format=html") firstline = cherrypy.response.body[0] assert '"title": "Foobar"' not in firstline