def testUpdatesApp(self): # root = app.RequestProcessor(a='testUpdatesApp.py',model_uri = 'test:') app = vesper.app.createApp(baseapp='testUpdatesApp.py', model_uri='test:') app.load() root = app._server dataStore = root.defaultStore #print 'model', dataStore.model.managedModel.model #set timestamp to 0 so tests are reproducible: dataStore.model.createTxnTimestamp = lambda *args: 0 expectedChangeSet = makeChangeset('0A', '0A00001') #set a notifyChangeset hook to test if its called properly self.notifyChangeset = None def testNotifyChangeset(changeset): self.notifyChangeset = changeset def x(d): return ['%s=%s' % (k,v) for k,v in sorted(d.items()) if k != 'statements'] diff = utils.pprintdiff(x(changeset), x(expectedChangeSet)) self.assertEquals(changeset, expectedChangeSet, diff) dataStore.model.notifyChangeset = testNotifyChangeset self.failUnless(root.loadModelHookCalled) self.failUnless(not dataStore.model._currentTxn) self.assertEquals(dataStore.model.currentVersion, '0') #the "foo" request handler defined in testUpdatesApp.py adds content to the store: result = root.runActions('http-request', dict(_name='foo')) response = "<html><body>page content.</body></html>" self.assertEquals(response, result) self.assertEquals(dataStore.model.currentVersion, '0A00001') self.assertEquals(root.updateResults['_added']['data'], [{'comment': u'page content.', 'id': '@a_resource', 'label': 'foo'}]) self.assertEquals(root.updateResults['_addedStatements'], [('a_resource', 'comment', 'page content.', 'L', ''), ('a_resource', 'label', 'foo', 'L', '')]) self.assertEquals(root.updateResults['_removedStatements'], []) self.assertEquals(root.updateResults['_removed']['data'], []) self.failUnless(self.notifyChangeset) #this request doesn't update the store so updateResults should be empty root.updateResults = {} result = root.runActions('http-request', dict(_name='jj')) self.assertEquals('<html><body>not found!</body></html>', result) self.assertEquals(dataStore.model.currentVersion, '0A00001') self.failUnless('_addedStatements' not in root.updateResults, root.updateResults) self.failUnless('_added' not in root.updateResults) self.failUnless('_removedStatements' not in root.updateResults) self.failUnless('_removed' not in root.updateResults) try: #merging our own changeset in again should throw an error: dataStore.merge(self.notifyChangeset) except RuntimeError, e: self.assertEquals(str(e), 'merge received changeset from itself: 0A')
def testMinimalApp(self): app = vesper.app.createApp(baseapp='testMinimalApp.py', model_uri='test:') app.load() root = app._server result = root.runActions('http-request', dict(_name='foo')) response = "<html><body>page content.</body></html>" self.assertEquals(response, result) #XXX test for InputSource #result = app.InputSource.DefaultFactory.fromUri( # 'site:///foo', resolver=root.resolver).read() #print type(result), repr(result), result self.assertEquals(response, result) result = root.runActions('http-request', dict(_name='jj')) #print type(result), result self.assertEquals( '<html><body>not found!</body></html>', result)
def _testErrorHandling(self, appVars=None): app = vesper.app.createApp(baseapp='testErrorHandling-config.py', model_uri='test:', **(appVars or {})) app.load() root = app._server #make sure the error handler is run and sets the status code to 404 instead of the default 200 kw = dict(_name='foo', _responseHeaders=dict(_status="200 OK"), _environ={}) result = root.handleHTTPRequest(kw) self.assertEquals(kw['_responseHeaders']['_status'], '%d %s' % (404, root.statusMessages[404])) response = "404 not found" self.assertEquals(response, result) kw = dict(_name='errorInCommit', _responseHeaders=dict(_status="200 OK"), _environ={}) result = root.handleHTTPRequest(kw) self.assertEquals(kw['_responseHeaders']['_status'], '%d %s' % (503, root.statusMessages[503])) response = 'badCommit: True' self.assertEquals(response, result)
def testSequencerApp(self): app = vesper.app.createApp(baseapp='testSequencerApp.py', model_uri='test:') app.load() root = app._server result = root.runActions('http-request', dict(_name='foo')) self.assertEquals("<html><body>page content.</body></html>", result) app = vesper.app.createApp(baseapp='testSequencerApp.py', model_uri='test:') app.load() root = app._server # XXX createApp doesn't specify whether to create a RequestProcessor or HTTPRequestProcessor # root = web.HTTPRequestProcessor(a='testSequencerApp.py',model_uri = 'test:') kw = dict(_name='no such page', _responseHeaders={}, _environ={}) result = root.handleHTTPRequest(kw) self.assertEquals(kw['_responseHeaders']['_status'],"404 Not Found") kw = dict(_name='/static/testfile.txt', _responseHeaders=dict(_status="200 OK"), _environ={}) result = root.handleHTTPRequest(kw) self.assertEquals(result.read().strip(), "test file")
def testCreateApp(self): #this is minimal logconfig that python's logger seems to accept: app = vesper.app.createApp(static_path=['static'], logconfig = ''' [loggers] keys=root [handlers] keys=hand01 [formatters] keys=form01 [logger_root] level=DEBUG handlers=hand01 [handler_hand01] class=StreamHandler level=NOTSET formatter=form01 args=(sys.stdout,) [formatter_form01] format=%(asctime)s %(levelname)s %(name)s %(message)s datefmt=%d %b %H:%M:%S ''' ) root = app.load() self.failUnless(root) cmdline = ['-x', '--foo=bar', '--transaction_log=test.log', '-fname', '-c', 'test.config'] app = vesper.app.createApp() root = app.run(cmdline=cmdline) self.assertEquals(app.foo, 'bar') self.assertEquals(app.baz, 1) self.assertEquals(app.f, 'name') self.assertEquals(root.defaultStore.transaction_log, 'test.log') #test trying to loading a store with the wrong kind of file cmdline = ['-s', 'test.config'] app = vesper.app.createApp() from vesper.data.base.utils import ParseException try: root = app.run(cmdline=cmdline) except ParseException, e: #XXX should report better error message when failing to load store self.assertEquals(str(e), 'unrecognized or invalid file contents')
def testMultipleStores(self): app = vesper.app.createApp(stores = { 'config' : dict(storage_template='''{ "id" : "@c1", "prop" : 1 }''', model_options=dict( serializeOptions = dict(pjson=dict(nameMap=None)) ) ), 'data' : dict(default_store=True, storage_template='''{ "id" : "@d1", "prop" : 1 }''') }, storeDefaults=dict(model_options=dict( serializeOptions = dict(pjson=dict(nameMap={'refpattern': '!((::)?URIREF)'})) )) ) root = app.load() self.failUnless(root and root.defaultStore is root.stores.data) self.assertEquals(root.stores.config.model_options, {'serializeOptions': {'pjson': {'nameMap': None}}}) self.assertEquals(root.stores.data.model_options, {'serializeOptions': {'pjson': {'nameMap': {'refpattern': '!((::)?URIREF)'}}}}) def transaction(): root.stores.config.update(dict(id='c2', prop2=1)) root.stores.data.update(dict(id='d1', prop2=1)) root.executeTransaction(transaction) cdata = [{'id': '@c2', 'prop2': 1}, {'id': '@c1', u'prop': 1}] ddata = [{'id': '!d1', 'prop2': 1, u'prop': 1}] self.assertEquals(root.stores.config.query("{*}"), cdata) self.assertEquals(root.defaultStore.query("{*}"), ddata) #test that both stores rollback def transaction2(): root.stores.config.update(dict(id='c2', prop3=1)) root.stores.data.update(dict(id='d1', prop3=1)) raise Error() try: root.executeTransaction(transaction2) except: pass else: self.fail('should have raised an error') self.assertEquals(root.stores.config.query("{*}"), cdata) self.assertEquals(root.defaultStore.query("{*}"), ddata)
def testCreateApp(self): #this is minimal logconfig that python's logger seems to accept: app = vesper.app.createApp(static_path=['static'], logconfig = ''' [loggers] keys=root [handlers] keys=hand01 [formatters] keys=form01 [logger_root] level=DEBUG handlers=hand01 [handler_hand01] class=StreamHandler level=NOTSET formatter=form01 args=(sys.stdout,) [formatter_form01] format=%(asctime)s %(levelname)s %(name)s %(message)s datefmt=%d %b %H:%M:%S ''' ) root = app.load() self.failUnless(root) cmdline = ['-x', '--foo=bar', '--transaction_log=test.log', '-fname', '-c', 'test.config'] called = False @vesper.app.Command("foo") def testCmdFoo(kw, retVal): self.assertEquals(kw._params.foo, 'bar') self.assertEquals(kw._params.f, 'name') kw.__server__.testCmdCalled = True @vesper.app.Command("bar") def testCmdBar(kw, retVal): self.fail("shouldn't have been called") return retVal app = vesper.app.createApp(actions = { 'run-cmds' : [testCmdFoo, testCmdBar, lambda x,y: y], }) root = app.run(cmdline=cmdline) self.assertEquals(app.foo, 'bar') self.assertEquals(app.baz, 1) self.assertEquals(app.f, 'name') self.assertEquals(root.defaultStore.transaction_log, 'test.log') self.failUnless(root.testCmdCalled ) #test trying to loading a store with the wrong kind of file cmdline = ['-s', 'test.config'] app = vesper.app.createApp() from vesper.data.base.utils import ParseException try: root = app.run(cmdline=cmdline) except ParseException, e: #XXX should report better error message when failing to load store self.assertEquals(str(e), 'unrecognized or invalid file contents')