def test_request_mini_field_storage_returns_a_list(self): storages = { 'test': [MiniFieldStorage('key', '1'), MiniFieldStorage('key', '2')] } self.request._set_standardized_request_variables(storages) assert self.request.input('test') == ['1', '2']
def testShowActionBadNumber(self): action = ShowAction(self.client) self.assertRaises(ValueError, action.handle) self.form.value.append(MiniFieldStorage('@number', 'A')) self.form.value.append(MiniFieldStorage('@type', 'issue')) with self.assertRaises(SeriousError) as ctx: action.handle() self.assertEqual('"A" is not an ID (issue ID required)', ctx.exception.args[0])
def testShowAction(self): self.client.base = 'BASE/' action = ShowAction(self.client) self.assertRaises(ValueError, action.handle) self.form.value.append(MiniFieldStorage('@type', 'issue')) self.assertRaises(SeriousError, action.handle) self.form.value.append(MiniFieldStorage('@number', '1')) self.assertRaisesMessage(Redirect, action.handle, 'BASE/issue1')
def assertLoginLeavesMessages(self, messages, username=None, password=None): if username is not None: self.form.value.append(MiniFieldStorage('__login_name', username)) if password is not None: self.form.value.append( MiniFieldStorage('__login_password', password)) LoginAction(self.client).handle() self.assertEqual(self.client.error_message, messages)
def test_to_python_invalid(self): from eportfolio.views.validators import ImageUploadConverter from cgi import MiniFieldStorage validator = ImageUploadConverter() image_path = join(dirname(__file__), 'data', 'image.pdf') fd = open(image_path, 'rb') storage = MiniFieldStorage('image', 'image.pdf') storage.file = fd storage.filename = 'image.pdf' self.assertRaises(Invalid, validator._to_python, storage, None)
def assertLoginRaisesRedirect(self, message, username=None, password=None, came_from=None): if username is not None: self.form.value.append(MiniFieldStorage('__login_name', username)) if password is not None: self.form.value.append( MiniFieldStorage('__login_password', password)) if came_from is not None: self.form.value.append(MiniFieldStorage('__came_from', came_from)) self.assertRaisesMessage(Redirect, LoginAction(self.client).handle, message)
def test_link(self): """Make sure lookup of a Link property works even in the presence of multiple values in the form.""" def lookup(key) : self.assertEqual(key, key.strip()) return "Status%s"%key self.form.list.append(MiniFieldStorage("status", "1")) self.form.list.append(MiniFieldStorage("status", "2")) status = hyperdb.Link("status") self.client.db.classes = dict \ ( issue = MockNull(getprops = lambda : dict(status = status)) , status = MockNull(get = lambda id, name : id, lookup = lookup) ) cls = HTMLClass(self.client, "issue") cls["status"]
def testLastUserActivityColon(self): self.assertEqual(self.action.lastUserActivity(), None) # test : special variable form self.client.form.value.append( MiniFieldStorage(':lastactivity', str(self.now))) self.assertEqual(self.action.lastUserActivity(), self.now)
def test_to_python_png(self): from eportfolio.views.validators import ImageUploadConverter from cgi import MiniFieldStorage validator = ImageUploadConverter() image_path = join(dirname(__file__), 'data', 'image.png') fd = open(image_path, 'rb') storage = MiniFieldStorage('image', 'image.png') storage.file = fd storage.filename = 'image.png' result = validator._to_python(storage, None) image = Image.open(result) # Image has been scaled # FIXME: why do we have 130 x 130 here self.assertEqual((130, 130), image.size) self.assertEqual('JPEG', image.format)
def testTokenizedStringKey(self): self.client.db.classes.get_transitive_prop = lambda x: hyperdb.String() self.form.value.append(MiniFieldStorage('foo', 'hello world')) self.assertFilterEquals('foo') # The single value gets replaced with the tokenized list. self.assertEqual([x.value for x in self.form['foo']], ['hello', 'world'])
def testNumKey( self ): # testing patch: http://hg.python.org/tracker/roundup/rev/98508a47c126 for val in ["-1000a", "test", "o0.9999", "o0", "1.00/10"]: print("testing ", val) self.client.db.classes.get_transitive_prop = lambda x: hyperdb.Number( ) self.form.value.append(MiniFieldStorage('foo', val)) # invalid numbers self.assertRaises(FormError, self.action.fakeFilterVars) del self.form.value[:] for val in [ "-1000.7738", "-556", "-0.9999", "-.456", "-5E-5", "0.00", "0", "1.00", "0556", "7.56E2", "1000.7738" ]: self.form.value.append(MiniFieldStorage('foo', val)) self.action.fakeFilterVars( ) # this should run and return. No errors, nothing to check. del self.form.value[:]
def testIntKey( self ): # testing patch: http://hg.python.org/tracker/roundup/rev/98508a47c126 for val in [ "-1000a", "test", "-5E-5", "0.9999", "0.0", "1.000", "0456", "1E4" ]: print("testing ", val) self.client.db.classes.get_transitive_prop = lambda x: hyperdb.Integer( ) self.form.value.append(MiniFieldStorage('foo', val)) self.assertRaises(FormError, self.action.fakeFilterVars) del self.form.value[:] for val in ["-1000", "-512", "0", "1", "100", "248"]: # no scientific notation apparently self.client.db.classes.get_transitive_prop = lambda x: hyperdb.Integer( ) self.form.value.append(MiniFieldStorage('foo', val)) self.action.fakeFilterVars( ) # this should run and return. No errors, nothing to check. del self.form.value[:]
def test_journal_add_view_image(self): from eportfolio.models.app import Application from eportfolio.views.journal import journal_add_view from cgi import MiniFieldStorage root = Application() project = self._add_project() student = self._add_student() project.students.append(student) # 'upload_directory' setting has to be set self.config.add_settings( upload_directory=join(dirname(__file__), 'data')) # Dummy repoze.filesafe data manager from repoze.filesafe.testing import setupDummyDataManager, cleanupDummyDataManager setupDummyDataManager() # Image file to upload image_path = join(dirname(__file__), 'data', 'image.jpg') fd = open(image_path, 'rb') storage = MiniFieldStorage('image', 'image.jpg') storage.file = fd storage.filename = 'image.jpg' # Student is logged in self.config.testing_securitypolicy(userid=student.email) request = testing.DummyRequest(root=root) request.POST['text'] = u'Entry with an image' request.POST['image'] = storage request.POST['form.submitted'] = 1 journal_add_view(project, request) self.assertEquals(1, project.journal_entries.count()) entry = project.journal_entries[0] self.assertEqual('image/jpeg', entry.image.content_type) cleanupDummyDataManager()
def test_journal_add_view_image(self): from eportfolio.models.app import Application from eportfolio.views.journal import journal_add_view from cgi import MiniFieldStorage root = Application() project = self._add_project() student = self._add_student() project.students.append(student) # 'upload_directory' setting has to be set self.config.add_settings(upload_directory=join(dirname(__file__), 'data')) # Dummy repoze.filesafe data manager from repoze.filesafe.testing import setupDummyDataManager, cleanupDummyDataManager setupDummyDataManager() # Image file to upload image_path = join(dirname(__file__), 'data', 'image.jpg') fd = open(image_path, 'rb') storage = MiniFieldStorage('image', 'image.jpg') storage.file = fd storage.filename = 'image.jpg' # Student is logged in self.config.testing_securitypolicy(userid=student.email) request = testing.DummyRequest(root=root) request.POST['text'] = u'Entry with an image' request.POST['image'] = storage request.POST['form.submitted'] = 1 journal_add_view(project, request) self.assertEquals(1, project.journal_entries.count()) entry = project.journal_entries[0] self.assertEqual('image/jpeg', entry.image.content_type) cleanupDummyDataManager()
def test_multilink(self): """`lookup` of an item will fail if leading or trailing whitespace has not been stripped. """ def lookup(key) : self.assertEqual(key, key.strip()) return "User%s"%key self.form.list.append(MiniFieldStorage("nosy", "1, 2")) nosy = hyperdb.Multilink("user") self.client.db.classes = dict \ ( issue = MockNull(getprops = lambda : dict(nosy = nosy)) , user = MockNull(get = lambda id, name : id, lookup = lookup) ) cls = HTMLClass(self.client, "issue") cls["nosy"]
def test_request_mini_field_storage_doesnt_return_brackets(self): storages = {'test[]': [MiniFieldStorage('key', '1')]} self.request._set_standardized_request_variables(storages) assert self.request.input('test') == '1'
def index(self, **kwargs): #return "".join(truth.servepage("/", dict([(x, MiniFieldStorage(x,y)) for x,y in kwargs.items()]))) yield from truth.servepage("/", dict([(x, MiniFieldStorage(x,y)) for x,y in kwargs.items()]))
def testQueryName(self): self.assertEqual(self.action.getQueryName(), '') self.form.value.append(MiniFieldStorage('@queryname', 'foo')) self.assertEqual(self.action.getQueryName(), 'foo')
def testShowActionNoType(self): action = ShowAction(self.client) self.assertRaises(ValueError, action.handle) self.form.value.append(MiniFieldStorage('@number', '1')) self.assertRaisesMessage(ValueError, action.handle, 'No type specified')
def test_request_mini_field_storage_index(self): storages = {'test[index]': [MiniFieldStorage('key', '1')]} self.request._set_standardized_request_variables(storages) self.assertEqual(self.request.input('test[index]'), '1')
def testLastUserActivity(self): self.assertEqual(self.action.lastUserActivity(), None) self.client.form.value.append( MiniFieldStorage('@lastactivity', str(self.now))) self.assertEqual(self.action.lastUserActivity(), self.now)
def testStringKey(self): self.client.db.classes.getprops = lambda: {'foo': hyperdb.String()} self.form.value.append(MiniFieldStorage('foo', 'hello')) self.assertFilterEquals('foo')
for i in ma.keys(): if not i in res.keys(): assert False if res[i] != ma[i]: yield "key", i yield "expected", ma[i] yield "got", res[i] assert False assert res == ma if __name__ == "__main__": cgitb.enable() #sys.setrecursionlimit(40) if len(sys.argv) > 1: form = dict((d, MiniFieldStorage(d,i)) for (d,i) in json.loads(sys.argv[1]).items()) else: if not "REMOTE_ADDR" in os.environ: print( """Usage: {} {}""".format(sys.argv[0], shlex.quote(json.dumps({"type":"small","names":"a,b,c,d","funstr":"a and b or not (c and d)"}))) ) sys.exit(1) form = cgi.FieldStorage() print("Content-Type: text/html\n") starttime = time.time() #myprint = lambda x: print(x,end="") def myprint(x): #if time.time() - starttime > 5: raise Exception("timed out!: computed this: " + x) #if not isinstance(x, str): # raise Exception(x)
def testStandardKey(self): self.form.value.append(MiniFieldStorage('foo', '1')) self.assertFilterEquals('foo')
def testEmptyKey(self): self.form.value.append(MiniFieldStorage('foo', '')) self.assertFilterEquals(None)
def testNonEmptyMultilink(self): self.form.value.append(MiniFieldStorage('foo', '')) self.form.value.append(MiniFieldStorage('foo', '1')) self.assertFilterEquals('foo')
def test_request_mini_field_storage_returns_single_value(self): storages = {'test': [MiniFieldStorage('key', '1')]} self.request._set_standardized_request_variables(storages) assert self.request.input('test') == '1'
def test_request_mini_field_storage_with_dot_notation(self): storages = {'test[index]': [MiniFieldStorage('key', '1')]} self.request._set_standardized_request_variables(storages) assert self.request.input('test.index') == '1'