コード例 #1
0
 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']
コード例 #2
0
 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])
コード例 #3
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')
コード例 #4
0
    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)
コード例 #5
0
    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)
コード例 #6
0
 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)
     
コード例 #7
0
ファイル: test_actions.py プロジェクト: jerrykan/roundup
    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)
コード例 #8
0
 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"]
コード例 #9
0
ファイル: test_actions.py プロジェクト: jerrykan/roundup
    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)
コード例 #10
0
 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)
コード例 #11
0
    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)
コード例 #12
0
    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'])
コード例 #13
0
ファイル: test_actions.py プロジェクト: jerrykan/roundup
    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[:]
コード例 #14
0
ファイル: test_actions.py プロジェクト: jerrykan/roundup
    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[:]
コード例 #15
0
ファイル: test_journal.py プロジェクト: FvD/cobal.eportfolio
    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()
コード例 #16
0
ファイル: test_journal.py プロジェクト: FvD/cobal.eportfolio
 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()
コード例 #17
0
 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"]
コード例 #18
0
 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'
コード例 #19
0
 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()]))
コード例 #20
0
    def testQueryName(self):
        self.assertEqual(self.action.getQueryName(), '')

        self.form.value.append(MiniFieldStorage('@queryname', 'foo'))
        self.assertEqual(self.action.getQueryName(), 'foo')
コード例 #21
0
 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')
コード例 #22
0
 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')
コード例 #23
0
    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)
コード例 #24
0
 def testStringKey(self):
     self.client.db.classes.getprops = lambda: {'foo': hyperdb.String()}
     self.form.value.append(MiniFieldStorage('foo', 'hello'))
     self.assertFilterEquals('foo')
コード例 #25
0
    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)
コード例 #26
0
 def testStandardKey(self):
     self.form.value.append(MiniFieldStorage('foo', '1'))
     self.assertFilterEquals('foo')
コード例 #27
0
 def testEmptyKey(self):
     self.form.value.append(MiniFieldStorage('foo', ''))
     self.assertFilterEquals(None)
コード例 #28
0
    def testNonEmptyMultilink(self):
        self.form.value.append(MiniFieldStorage('foo', ''))
        self.form.value.append(MiniFieldStorage('foo', '1'))

        self.assertFilterEquals('foo')
コード例 #29
0
 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'
コード例 #30
0
 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'