def test_jsonOutput(self): testutil.createRequest("/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"] == "text/javascript"
def test_flash_plain(self): "turbogears.flash with strings should work" testutil.createRequest("/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_flash_unicode(self): "turbogears.flash with unicode objects should work" testutil.createRequest("/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_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.createRequest("/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_index_trailing_slash(): "If there is no trailing slash on an index method call, redirect" cherrypy.root = SubApp() cherrypy.root.foo = SubApp() testutil.createRequest("/foo") print cherrypy.response.status assert cherrypy.response.status.startswith("302")
def test_approotsWithPath(self): turbogears.config.update({"server.webpath" : "/coolsite/root"}) turbogears.startup.startTurboGears() testutil.createRequest("/coolsite/root/subthing/") print cherrypy.tree.mount_point() self.failUnlessEqual("/coolsite/root/subthing/foo", url("/foo"))
def test_recursiveErrorHandler(self): """ Recursive error handler. """ testutil.createRequest("/recursiveerror?bar=abc") self.failUnless("Recursive error handler" in cherrypy.response.body[0]) testutil.createRequest("/recursiveerror?bar=1") self.failUnless("Recursive error provider" in cherrypy.response.body[0])
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.createRequest("/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_defaultFormat(self): """The default format can be set via expose""" testutil.createRequest("/returnjson") firstline = cherrypy.response.body[0] assert '"title": "Foobar"' in firstline testutil.createRequest("/returnjson?tg_format=html") firstline = cherrypy.response.body[0] assert '"title": "Foobar"' not in firstline
def test_mochikit_everywhere(): "MochiKit can be included everywhere by setting tg.mochikit_all" root = cherrypy.root turbogears.config.update({"global":{"tg.mochikit_all" : True}}) testutil.createRequest("/") turbogears.config.update({"global":{"tg.mochikit_all" : False}}) print cherrypy.response.body[0] assert "MochiKit.js" in cherrypy.response.body[0]
def test_form_translation_new_style(): "Form input is translated into properly converted parameters" root = MyRoot() cherrypy.root = root testutil.createRequest("/testform_new_style?p_data.name=ed&p_data.age=5") assert root.name == "ed" print root.age assert root.age == 5
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.createRequest("/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.createRequest("/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_include_widgets(): "Any widget Can be included everywhere by setting tg.include_widgets" root = cherrypy.root turbogears.config.update({"global":{"tg.include_widgets" : ["turbogears.mochikit"]}}) testutil.createRequest("/") turbogears.config.update({"global":{"tg.include_widgets" : None}}) print cherrypy.response.body[0] assert "MochiKit.js" in cherrypy.response.body[0]
def test_implicitErrorHandler(self): """ Implicit error handling. """ testutil.createRequest("/impliciterror?bar=abc") self.failUnless("Implicit error handler" in cherrypy.response.body[0]) testutil.createRequest("/impliciterror?bar=1") self.failUnless("Implicit error provider" in cherrypy.response.body[0])
def test_runwithtrans(self): "run_with_transaction is called only on topmost exposed method" oldrwt = database.run_with_transaction database.run_with_transaction = cherrypy.root.rwt testutil.createRequest("/callsanother") database.run_with_transaction = oldrwt assert cherrypy.root.value assert cherrypy.root.rwt_called == 1
def test_form_translation(): "Form input is translated into properly converted parameters" root = MyRoot() cherrypy.root = root testutil.createRequest("/testform?name=ed&date=11/05/2005&age=5") assert root.name == "ed" print root.age assert root.age == 5
def test_set_kid_outputformat_in_config(self): "the outputformat for kid can be set in the config" turbogears.config.update({'kid.outputformat': 'xhtml'}) testutil.createRequest('/test') assert '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ' in cherrypy.response.body[0] turbogears.config.update({'kid.outputformat': 'html'}) testutil.createRequest('/test') assert '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ' in cherrypy.response.body[0]
def test_header_labels(self): #Check that the returned header labels match the the model cherrypy.root.catwalk = CatWalk(browse) testutil.createRequest("/catwalk/browse/?object_name=Artist&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) assert len(values['headers']) == 5 for header in values['headers']: assert header['name'] in ['id','name','albums','genres', 'plays_instruments']
def test_basicurls(self): testutil.createRequest("/") self.failUnlessEqual("/foo", url("/foo")) self.failUnlessEqual("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_list_contents(self): """If we add a record to the model, it should show up in the final page text""" cherrypy.root=Root() Bookmark(name='Compound Thinking', link='http://www.CompoundThinking.com', description="A {not so} random link.") testutil.createRequest("/list") assert '<a href="http://www.CompoundThinking.com">' in cherrypy.response.body[0]
def test_redirect(self): turbogears.config.update({"server.webpath" : "/coolsite/root"}) turbogears.startup.startTurboGears() testutil.createRequest("/coolsite/root/subthing/") try: turbogears.redirect("/foo") assert False, "redirect exception should have been raised" except cherrypy.HTTPRedirect, e: print e.urls assert "http://localhost/coolsite/root/subthing/foo" in e.urls
def test_flash_on_redirect(self): "turbogears.flash must survive a redirect" testutil.createRequest("/flash_redirect?tg_format=json") assert cherrypy.response.status.startswith("302") testutil.createRequest( cherrypy.response.headers["Location"], headers=dict(Cookie=cherrypy.response.simple_cookie.output(header="").strip())) import simplejson values = simplejson.loads(cherrypy.response.body[0]) assert values["tg_flash"]==u"redirect \xfcnicode"
def test_filters(self): cherrypy.root.catwalk = CatWalk(browse) testutil.createRequest("/catwalk/browse/?object_name=Song&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) assert values['total'] == 15 * 15 * 15 #without the filters we get all songs (3375) testutil.createRequest("/catwalk/browse/?object_name=Song&filters=album:1&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) assert values['total'] == 15 #filter by album id (only 15 songs)
def test_rows_joins_count(self): #Control that the count for related and multiple joins match #the number of related instances when accessed as a field cherrypy.root.catwalk = CatWalk(browse) testutil.createRequest("/catwalk/browse/?object_name=Artist&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) artist = browse.Artist.get(1) assert int(values['rows'][0]['genres']) == len(list(artist.genres)) assert int(values['rows'][0]['albums']) == len(list(artist.albums))
def test_rows_limit(self): #Update the limit of rows for the query and control the number of rows returned cherrypy.root.catwalk = CatWalk(browse) testutil.createRequest("/catwalk/browse/?object_name=Artist&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) assert values.has_key('rows') assert len(values['rows']) == 10 testutil.createRequest("/catwalk/browse/?object_name=Artist&page_size=15&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) assert values.has_key('rows') assert len(values['rows']) == 15
def test_allowJsonConfig(self): "JSON output can be enabled via config." turbogears.config.update({'tg.allow_json':True}) testutil.capture_log("tubrogears.controllers") class JSONRoot(controllers.RootController): def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_html="turbogears.tests.simple") allowjsonconfig = turbogears.expose(html="turbogears.tests.simple")(allowjsonconfig) testutil.print_log() cherrypy.root = JSONRoot() testutil.createRequest('/allowjsonconfig?tg_format=json') assert cherrypy.response.headers["Content-Type"]=="text/javascript" turbogears.config.update({'tg.allow_json':False})
def test_double_flash(self): """latest set flash should have precedence""" # Here we are calling method that sets a flash message. However flash # cookie is still there. Turbogears should discard old flash message # from cookie and use new one, set by flash_plain(). testutil.createRequest("/flash_plain?tg_format=json", headers=dict(Cookie='tg_flash="old flash"; Path=/;')) import simplejson values = simplejson.loads(cherrypy.response.body[0]) assert values["tg_flash"]=="plain" assert cherrypy.response.simple_cookie.has_key("tg_flash"), \ "Cookie clearing request should be present" flashcookie = cherrypy.response.simple_cookie['tg_flash'] assert flashcookie['expires'] == 0
def test_response_fields(self): #Check that the response contains the expected keys cherrypy.root.catwalk = CatWalk(browse) testutil.createRequest("/catwalk/browse/?object_name=Artist&start=3&page_size=20&tg_format=json") response = cherrypy.response.body[0] values = simplejson.loads(response) assert values.has_key('headers') assert values.has_key('rows') assert values.has_key('start') assert values.has_key('page_size') assert values.has_key('total') assert values['start'] == 3 assert values['page_size'] == 20 assert values['total'] == 15
def test_allowJsonConfigFalse(self): "Make sure JSON can still be restricted with a global config on." turbogears.config.update({'tg.allow_json':True}) testutil.capture_log("tubrogears.controllers") class JSONRoot(controllers.RootController): def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_html="turbogears.tests.simple") allowjsonconfig = turbogears.expose(html="turbogears.tests.simple")(allowjsonconfig) testutil.print_log() cherrypy.root = JSONRoot() testutil.createRequest('/allowjson?tg_format=json') print cherrypy.response.body[0] assert cherrypy.response.headers["Content-Type"]=="text/html" turbogears.config.update({'tg.allow_json':False})
def test_can_use_internally_defined_arguments(): """Tests that we can use argument names that are internally used by TG in controllers:_execute_func et al.""" class App(controllers.RootController): def index(self, **kw): return "\n".join(["%s:%s" % i for i in kw.iteritems()]) index = turbogears.expose()(index) cherrypy.root = App() testutil.createRequest("/?format=foo&template=bar&fragment=boo") output = cherrypy.response.body[0] print output assert "format:foo" in output assert "template:bar" in output assert "fragment:boo" in output
def test_logintitle(self): "login page should have the right title" testutil.createRequest("/login") response = cherrypy.response.body[0].lower() assert "<title>login</title>" in response
def test_indextitle(self): "The indexpage should have the right title" testutil.createRequest("/") response = cherrypy.response.body[0].lower() assert "<title>welcome to turbogears</title>" in response
def test_logintitle(): "login page should have the right title" testutil.createRequest("/login") assert "<TITLE>Login</TITLE>" in cherrypy.response.body[0]
def test_indextitle(): "The indexpage should have the right title" testutil.createRequest("/") assert "<TITLE>Welcome to TurboGears</TITLE>" in cherrypy.response.body[0]