def test_required_fields(): """Test required fields. Required fields 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): @expose(template="kid:turbogears.widgets.tests.form") def test(self): return dict(form=form) app = testutil.make_app(MyRoot) response = app.get("/test") output = response.body.lower() assert 'content="kid"' in output and 'content="genshi"' not in 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_display(self): """ Checks if names fo the widgets are set correctly depending on their path. """ app = testutil.make_app(self.MyRoot) response = app.get('/?test_id=sub2') output = response.body value_p = 'value="22"' name_p = 'name="sub.sub2.age"' assert (re.compile('.*'.join([value_p, name_p])).search(output) or re.compile('.*'.join([name_p, value_p])).search(output)) response = app.get('/?test_id=sub') output = response.body value_p = 'value="22"' name_p = 'name="sub.age"' id_p = 'id="myform_sub_age"' assert (re.compile('.*'.join([value_p, name_p])).search(output) or re.compile('.*'.join([name_p, value_p])).search(output)) assert (re.compile('.*'.join([value_p, id_p])).search(output) or re.compile('.*'.join([id_p, value_p])).search(output)) response = app.get('/?test_id=age') output = response.body value_p = 'value="22"' name_p = 'name="age"' assert (re.compile('.*'.join([value_p, name_p])).search(output) or re.compile('.*'.join([name_p, value_p])).search(output))
def test_exc_done_rollback(): """No problems with error handler if controller manually rollbacks.""" app = make_app(RbRoot) response = app.get('/doerr?id=28&dorb=1') assert 'KARL27' in response, 'Exception handler should have answered' assert session.query(User).get(28) is None assert session.query(User).get(29) is not None
def test_validation(self): """Data can be converted and validated""" response = self.app.get("/istrue?value=true") assert response.body == 'True' response = self.app.get("/istrue?value=false") assert response.body == 'False' app = testutil.make_app(MyRoot) response = app.get("/istrue?value=foo") assert response.raw['msg'] == 'Error Message' response = app.get("/save?submit=send&firstname=John&lastname=Doe") assert response.raw['fullname'] == "John Doe" assert response.raw['submit'] == "send" response = app.get("/save?submit=send&firstname=Arthur") assert response.raw['fullname'] == "Arthur Miller" response = app.get("/save?submit=send&firstname=Arthur&lastname=") assert response.raw['fullname'] == "Arthur " response = app.get("/save?submit=send&firstname=D&lastname=") assert len(response.raw['errors'].keys()) == 1 assert "firstname" in response.raw['errors'] assert "characters" in response.raw['errors']["firstname"].lower() response = app.get("/save?submit=send&firstname=&lastname=") assert len(response.raw['errors'].keys()) == 1 assert "firstname" in response.raw['errors']
def test_textfield(): """Test form rendering inside a request.""" #form name is prepended to element ids only when running inside a request. class MyField(widgets.WidgetsList): blonk = widgets.TextField() tf = widgets.ListForm(fields=MyField()) class MyFieldOverrideName(widgets.WidgetsList): blonk = widgets.TextField(name="blink") tf2 = widgets.ListForm(fields=MyFieldOverrideName()) class MyRoot(controllers.RootController): @expose() def fields(self): return tf.render(format='xhtml') @expose() def override(self): return tf2.render(format='xhtml') testutil.mount(MyRoot(), '/') app = testutil.make_app() r = app.get('/fields') assert 'name="blonk"' in r assert 'id="form_blonk"' in r r = app.get('/override') assert 'name="blink"' in r assert 'id="form_blink"' in r
def test_cntrl_commit(): """It's safe to commit a transaction in the controller.""" app = make_app(MyRoot) response = app.get("/create_person?id=23&docom=1") assert 'InvalidRequestError' not in response assert session.query(Person).get(23) is not None, \ 'The Person 23 should have been saved during commit inside controller'
def test_cntrl_commit2(): """A commit inside the controller is not rolled back by the exception.""" app = make_app(MyRoot) response = app.get("/create_person?id=24&docom=1&doerr=1") assert 'InvalidRequestError' not in response assert session.query(Person).get(24) is not None, \ 'The Person 24 should have been saved during commit' \ ' inside controller and not rolled back'
def test_user_exception(): """If a controller raises an exception, transactions are rolled back.""" app = make_app(MyRoot) response = app.get("/create_person?id=19&docom=0&doerr=1&name=Martin%20GAL") assert 'KARL25' in response, \ 'The exception handler should have answered us' p = session.query(Person).get(19) assert p is None, \ 'This Person should have been rolled back: %s' % p
def test_implicit_trans_no_error(): """If a controller runs sucessfully, the transaction is commited.""" app = make_app(MyRoot) response = app.get("/no_error?name=A.%20Dent") arthur = session.query(Person).filter_by(name="A. Dent").first() assert 'someconfirmhandler' in response, \ 'The no error should have redirected to someconfirmhandler' assert arthur is not None, 'Person arthur should have been saved!' assert arthur.name == "A. Dent", 'Person arthur should be named "A. Dent"'
def test_nested_variables(): url = u"/checkform?foo.name=Kevin&foo.age=some%20Numero".encode("utf-8") testutil.stop_server(tg_only = True) app = testutil.make_app(NestedController) testutil.start_server() request = app.get(url) assert config.get("decoding_filter.encoding", path='/') == "utf8" assert request.raw["name"] == "Kevin" assert request.raw["age"] == u"some Numero"
def test_raise_sa_exception(): """If a controller causes an SA exception, it is raised properly.""" app = make_app(MyRoot) response = app.get("/create_person?id=20") assert 'No exceptions occurred' in response response = app.get("/create_person?id=20", status=500) assert 'KARL25' not in response, \ 'Exception should NOT have been handled by our handler' assert 'IntegrityError' in response, \ 'The page should have displayed a database integrity error'
def test_exc_rollback2(): """An exception within a controller method causes a rollback. Try to create a user that should rollback because of an exception so user XX should not exist. """ app = make_app(RbRoot) response = app.get('/doerr?id=XX') assert 'KARL27' in response, 'Exception handler should have answered' assert session.query(User).get('XX') is None
def test_field_for(): app = make_app(NestedController) response = app.get('/field_for') assert "form_foo_appears" in response assert "form_foo_foo_appears" in response assert "foo.appears" in response assert "foo.foo.appears" in response assert "error_appears" in response assert "textfield" in response assert "HiYo!" in response assert "size=\"100\"" in response
def test_cntrl_flush(): """It's safe to flush in the controller.""" app = make_app(MyRoot) response = app.get("/create_person?id=25&doflush=1") print response assert 'No exceptions occurred' in response response = app.get("/create_person?id=25&doflush=0", status=500) assert 'IntegrityError' in response response = app.get("/create_person?id=25&doflush=1") assert 'IntegrityError' in response response = app.get("/create_person?id=25&doflush=2") assert 'No exceptions occurred' in response
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="kid:turbogears.tests.simple") def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="kid:turbogears.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_nested_login(self): """Check that we can login using a nested form.""" config.update({ 'identity.form.user_name': 'credentials.user', 'identity.form.password': '******', 'identity.form.submit': 'log.me.in'}) testutil.stop_server(tg_only=False) self.app = testutil.make_app(self.root) testutil.start_server() response = self.app.get('/logged_in_only?' 'credentials.user=samIam&credentials.pass=secret&log.me.in=Enter') assert 'logged_in_only' in response, response
def test_exc_rollback(): """An exception within a controller method causes a rollback. Try to create a user that should rollback because of an exception so user 25 should not exist, but user 26 should be present since it is created by the exception handler. """ app = make_app(RbRoot) response = app.get('/doerr?id=26') assert 'KARL27' in response, 'Exception handler should have answered' assert session.query(User).get(26) is None assert session.query(User).get(27) is not None
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="kid:turbogears.tests.simple") def allowjsonconfig(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="kid:turbogears.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=404) assert response.headers["Content-Type"] == "text/html" config.update({'tg.allow_json': True})
def test_expose_pass_options(): """Test that expose correctly passes kwargs as options to template engine.""" app = make_app(ExposeRoot) response = app.get("/with_testplugin") info, options = loads(response.body) assert info['fruit'] == 'apple' and info['tree'] == 'Rowan', \ "Data dict returned from exposed method not included in output." assert options['cache'] is True, \ "Options passed to template engine constructor not used." assert options['renderer'] == 'fast', \ "Options passed as kwargs to expose() not passed to render()." assert options['strict'] is not True, \ "Options passed to expose() do not override options passed to __init__()." response = app.get("/with_testplugin_using_mapping") info, options = loads(response.body) assert options['mapping'] == dict(deprecated=True), \ "Options passed in mapping arg to expose() not passed to render()."
def test_allow_json(): class NewRoot(controllers.RootController): @expose(template="turbogears.tests.doesnotexist", allow_json=True) def test(self): return dict(title="Foobar", mybool=False, someval="niggles") app = make_app(NewRoot) response = app.get("/test", headers= dict(accept="application/json")) values = loads(response.body) assert values == dict(title="Foobar", mybool=False, someval="niggles", tg_flash=None) assert response.headers["Content-Type"] == "application/json" response = app.get("/test?tg_format=json") values = loads(response.body) assert values == dict(title="Foobar", mybool=False, someval="niggles", tg_flash=None) assert response.headers["Content-Type"] == "application/json"
def test_session_freshness(): """Check for session freshness. Changes made to the data in thread B should be reflected in thread A. """ test_table.insert().execute(dict(id=1, val='a')) app = make_app(FreshRoot) response = app.get("/test1", status = 200) assert 'AssertionError' not in response # Call test2 in a different thread class ThreadB(threading.Thread): def run(self): response = app.get("/test2", status=200) assert 'AssertionError' not in response thrdb = ThreadB() thrdb.start() thrdb.join() response = app.get("/test3", status=200) assert 'AssertionError' not in response
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="kid:turbogears.widgets.tests.form")(test) app = testutil.make_app(MyRoot) response = app.get("/test") assert 'foo.js' in response.body assert "alert('hello');" in response.body assert 'foo.css' in response.body
def setup_module(): global app app = testutil.make_app(MyRoot) testutil.start_server()
def setUp(self): "Tests the output of the index method" self.app = testutil.make_app(self.root) testutil.start_server()
def setUp(self): testutil.mount(MyRoot(), '/') testutil.mount(SubApp(), '/subthing') testutil.mount(SubApp(), '/subthing/subsubthing') self.app = testutil.make_app() super(TestURLs, self).setUp()
def test_gettingjson(): app = make_app(ExposeRoot) response = app.get("/with_json?tg_format=json") assert '"title": "Foobar"' in response
def test_gettingjsonviaaccept(): app = make_app(ExposeRoot) response = app.get("/with_json_via_accept", headers=dict(Accept="application/json")) assert '"title": "Foobar"' in response
def test_calendardatepicker_js(): class MyRoot(turbogears.controllers.RootController): def test(self, lang=None): return dict(widget=widgets.CalendarDatePicker(calendar_lang=lang)) test = turbogears.expose(template="kid:turbogears.widgets.tests.widget")(test) app = testutil.make_app(MyRoot) # testing default language (en) response = app.get("/test") assert 'calendar/calendar.js' in response.body assert 'calendar/calendar-setup.js' in response.body assert 'calendar/lang/calendar-en.js' in response.body # testing non-existing language response = app.get("/test", headers={"Accept-Language": "x"}) assert 'calendar/lang/calendar-x.js' not in response.body assert 'calendar/lang/calendar-en.js' in response.body # testing French language response = app.get("/test", headers={"Accept-Language": "fr"}) assert 'calendar/lang/calendar-fr.js' in response.body assert 'calendar/lang/calendar-en.js' not in response.body assert 'charset="utf-8"' in response.body # testing German language with any charset response = app.get("/test", headers={"Accept-Language": "de", "Accept-Charset": "*"}) assert 'calendar/lang/calendar-de.js' in response.body assert 'calendar/lang/calendar-en.js' not in response.body assert 'charset="*"' not in response.body # testing Turkish language with non-existing charset response = app.get("/test", headers={"Accept-Language": "tr", "Accept-Charset": "big5"}) assert 'calendar/lang/calendar-tr.js' in response.body assert 'calendar/lang/calendar-en.js' not in response.body assert 'charset="big5"' not in response.body win1254 = 'windows-1254' from codecs import lookup try: assert lookup(win1254).name == 'cp1254' except AttributeError: # Py < 2.5 win1254 = 'cp1254' # cannot test name normalization here # testing Turkish language with existing, not normalized charset response = app.get("/test", headers={"Accept-Language": "tr", "Accept-Charset": win1254}) assert 'calendar/lang/calendar-tr-cp1254.js' in response.body assert 'calendar/lang/calendar-en.js' not in response.body assert 'charset="cp1254"' in response.body # testing more than one language and charset response = app.get("/test", headers={"Accept-Language": "x,tr,de,fr", "Accept-Charset": "big5,%s,latin-1" % win1254}) assert 'calendar/lang/calendar-tr-cp1254.js' in response.body assert 'calendar/lang/calendar-x.js' not in response.body assert 'calendar/lang/calendar-en.js' not in response.body assert 'charset="cp1254"' in response.body assert 'charset="big5"' not in response.body # testing predetermined language (fr) response = app.get("/test?lang=fr", headers={"Accept-Language": "de,en,tr"}) assert 'calendar/lang/calendar-fr.js' in response.body assert 'calendar/lang/calendar-en.js' not in response.body # testing predetermined non-existing language response = app.get("/test?lang=x", headers={"Accept-Language": "de,en,fr,tr"}) assert 'calendar/lang/calendar-de.js' in response.body assert 'calendar/lang/calendar-x.js' not in response.body assert 'calendar/lang/calendar-en.js' not in response.body
def test_getting_json_with_accept_but_using_tg_format(): app = make_app(ExposeRoot) response = app.get("/with_json_via_accept?tg_format=json") assert '"title": "Foobar"' in response
def test_getting_plaintext(): app = make_app(ExposeRoot) response = app.get("/with_json_via_accept", headers=dict(Accept="text/plain")) assert response.body == "This is a plain text for foo."