changeset 2453:adf5ec4874ed

fix ParameterParser, rewrite ParameterParser tests for py.test (and add more tests), refactor Hits macro
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Sat, 21 Jul 2007 21:30:47 +0200
parents 839b360413a9
children 18c71299e2bb
files MoinMoin/_tests/test_wikiutil.py MoinMoin/macro/Hits.py MoinMoin/wikiutil.py
diffstat 3 files changed, 77 insertions(+), 68 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/_tests/test_wikiutil.py	Fri Jul 20 23:53:59 2007 +0200
+++ b/MoinMoin/_tests/test_wikiutil.py	Sat Jul 21 21:30:47 2007 +0200
@@ -162,39 +162,55 @@
                 '"%(name)s" is NOT a valid template name' % locals())
 
 
-class TestParmeterParser(unittest.TestCase):
-
-    def testNoWantedArguments(self):
-        args = ''
-        argParser = wikiutil.ParameterParser('')
-        self.arg_list, self.arg_dict = argParser.parse_parameters(args)
-        result = len(self.arg_dict)
-        expected = 0
-        self.assert_(result == expected,
-                     'Expected "%(expected)s" but got "%(result)s"' % locals())
+class TestParmeterParser:
 
-    def testWantedArguments(self):
-        test_args = ('',
-                     'width=100',
-                     'width=100, height=200', )
+    def testParameterParser(self):
+        tests = [
+            # trivial
+            ('', '', {}),
 
-        argParser = wikiutil.ParameterParser("%(width)s%(height)s")
-        for args in test_args:
-            self.arg_list, self.arg_dict = argParser.parse_parameters(args)
-            result = len(self.arg_dict)
-            expected = 2
-            self.assert_(result == expected,
-                         'Expected "%(expected)s" but got "%(result)s"' % locals())
+            # boolean
+            ("%(t)b%(f)b", '', {'t': None, 'f': None}),
+            ("%(t)b%(f)b", 't=1', {'t': True, 'f': None}),
+            ("%(t)b%(f)b", 'f=False', {'t': None, 'f': False}),
+            ("%(t)b%(f)b", 't=True, f=0', {'t': True, 'f': False}),
+
+            # integer
+            ("%(width)i%(height)i", '', {'width': None, 'height': None}),
+            ("%(width)i%(height)i", 'width=100', {'width': 100, 'height': None}),
+            ("%(width)i%(height)i", 'height=200', {'width': None, 'height': 200}),
+            ("%(width)i%(height)i", 'width=100, height=200', {'width': 100, 'height': 200}),
+
+            # float
+            ("%(width)f%(height)f", '', {'width': None, 'height': None}),
+            ("%(width)f%(height)f", 'width=100.0', {'width': 100.0, 'height': None}),
+            ("%(width)f%(height)f", 'height=2.0E2', {'width': None, 'height': 200.0}),
+            ("%(width)f%(height)f", 'width=1000.0E-1, height=200.0', {'width': 100.0, 'height': 200.0}),
+
+            # string
+            ("%(width)s%(height)s", '', {'width': None, 'height': None}),
+            ("%(width)s%(height)s", 'width="really wide"', {'width': 'really wide', 'height': None}),
+            ("%(width)s%(height)s", 'height="not too high"', {'width': None, 'height': 'not too high'}),
+            ("%(width)s%(height)s", 'width="really wide", height="not too high"', {'width': 'really wide', 'height': 'not too high'}),
+            # XXX for the next 2 tests: unclear: wanted str, given int, shall that give int?
+            ("%(width)s%(height)s", 'width=100', {'width': 100, 'height': None}),
+            ("%(width)s%(height)s", 'width=100, height=200', {'width': 100, 'height': 200}),
+        ]
+        for format, args, result in tests:
+            argParser = wikiutil.ParameterParser(format)
+            arg_list, arg_dict = argParser.parse_parameters(args)
+            assert arg_dict == result
 
     def testTooMuchWantedArguments(self):
-        py.test.skip("fails because of unfinished wikiutil.ParameterParser code crashing")
         args = 'width=100, height=200, alt=Example'
         argParser = wikiutil.ParameterParser("%(width)s%(height)s")
-        self.arg_list, self.arg_dict = argParser.parse_parameters(args)
-        result = len(self.arg_dict)
-        expected = 2
-        self.assert_(result == expected,
-                     'Expected "%(expected)s" but got "%(result)s"' % locals())
+        py.test.raises(ValueError, argParser.parse_parameters, args)
+
+    def testMalformedArguments(self):
+        args = '='
+        argParser = wikiutil.ParameterParser("%(width)s%(height)s")
+        py.test.raises(ValueError, argParser.parse_parameters, args)
+
 
 coverage_modules = ['MoinMoin.wikiutil']
 
--- a/MoinMoin/macro/Hits.py	Fri Jul 20 23:53:59 2007 +0200
+++ b/MoinMoin/macro/Hits.py	Sat Jul 21 21:30:47 2007 +0200
@@ -10,10 +10,11 @@
         all: if set to 1 then cummulative hits over all wiki pages is returned. Default is 0
         filter: if set to SAVEPAGE then the saved pages are counted. Default is VIEWPAGE.
 
-   @copyright: 2004-2007 MoinMoin:ReimarBauer
+   @copyright: 2004-2007 MoinMoin:ReimarBauer,
                2005 BenjaminVrolijk
    @license: GNU GPL, see COPYING for details.
 """
+
 Dependencies = ['time'] # do not cache
 
 from MoinMoin import wikiutil
@@ -21,39 +22,38 @@
 
 class Hits:
     def __init__(self, macro, args):
-        self.macro = macro
         self.request = macro.request
         self.formatter = macro.formatter
+        self.this_page = macro.formatter.page.page_name
         argParser = wikiutil.ParameterParser("%(all)s%(filter)s")
         try:
             self.arg_list, self.arg_dict = argParser.parse_parameters(args)
-        except ValueError:
-            # TODO Set defaults until raise in ParameterParser.parse_parameters is changed
-            self.arg_dict = {}
-            self.arg_dict["filter"] = None
-            self.arg_dict["all"] = 0
-
-        self.count = 0
+            self.error = None
+        except ValueError, err:
+            self.error = str(err)
 
     def renderInText(self):
-        return self.formatter.text("%s" % (self.getHits()))
+        if self.error:
+            text = "Hits macro: %s" % self.error
+        else:
+            text = "%d" % self.getHits()
+        return self.formatter.text(text)
 
     def getHits(self):
-        formatter = self.macro.formatter
-        kw = self.arg_dict
-        if not kw["filter"]: kw["filter"] = "VIEWPAGE"
+        event_filter = self.arg_dict["filter"]
+        if not event_filter:
+            event_filter = "VIEWPAGE"
+        count_all_pages = self.arg_dict["all"]
 
         event_log = eventlog.EventLog(self.request)
-        event_log.set_filter([kw["filter"]])
+        event_log.set_filter([event_filter])
+        count = 0
         for event in event_log.reverse():
-            pagename = event[2].get('pagename', None)
-            if not kw["all"]:
-                if pagename == formatter.page.page_name:
-                    self.count += 1
-            else:
-                self.count += 1
+            pagename = event[2].get('pagename')
+            if count_all_pages or pagename == self.this_page:
+                count += 1
 
-        return self.count
+        return count
 
 def execute(macro, args):
     """ Temporary glue code to use with moin current macro system """
--- a/MoinMoin/wikiutil.py	Fri Jul 20 23:53:59 2007 +0200
+++ b/MoinMoin/wikiutil.py	Sat Jul 21 21:30:47 2007 +0200
@@ -3,6 +3,8 @@
     MoinMoin - Wiki Utility Functions
 
     @copyright: 2000-2004 Juergen Hermann <jh@web.de>,
+                2004 by Florian Festi,
+                2006 by Mikko Virkkil,
                 2005-2007 MoinMoin:ThomasWaldmann,
                 2007 MoinMoin:ReimarBauer
     @license: GNU GPL, see COPYING for details.
@@ -1303,10 +1305,6 @@
             ("John Smith", male=True)
         this will result in the following dict:
             {"name": "John Smith", "age": None, "male": True}
-
-        @copyright: 2004 by Florian Festi,
-                    2006 by Mikko Virkkilä
-        @license: GNU GPL, see COPYING for details.
     """
 
     def __init__(self, pattern):
@@ -1356,22 +1354,18 @@
         """
         #Default list to "None"s
         parameter_list = [None] * len(self.param_list)
-        parameter_dict = {}
+        parameter_dict = dict([(key, None) for key in self.param_dict])
         check_list = [0] * len(self.param_list)
 
         i = 0
         start = 0
         named = False
 
-        if not params:
-            params = '""'
-
         while start < len(params):
             match = re.match(self.param_re, params[start:])
             if not match:
-                raise ValueError, "Misformatted value"
+                raise ValueError("malformed parameters")
             start += match.end()
-            value = None
             if match.group("int"):
                 value = int(match.group("int"))
                 type = 'i'
@@ -1388,25 +1382,24 @@
                 value = match.group("name_param")
                 type = 'n'
             else:
-                value = None
+                raise ValueError("Parameter parser code does not fit param_re regex")
 
             parameter_list.append(value)
-            if match.group("name"):
-                if match.group("name") not in self.param_dict:
+            name = match.group("name")
+            if name:
+                if name not in self.param_dict:
                     # TODO we should think on inheritance of parameters
-                    raise ValueError, "Unknown parameter name '%s'" % match.group("name")
-                nr = self.param_dict[match.group("name")]
+                    raise ValueError("unknown parameter name '%s'" % name)
+                nr = self.param_dict[name]
                 if check_list[nr]:
-                    #raise ValueError, "Parameter specified twice"
-                    #TODO: Something saner that raising an exception. This is pretty good, since it ignores it.
-                    pass
+                    raise ValueError("parameter '%s' specified twice" % name)
                 else:
                     check_list[nr] = 1
-                parameter_dict[match.group("name")] = value
+                parameter_dict[name] = value
                 parameter_list[nr] = value
                 named = True
             elif named:
-                raise ValueError, "Only named parameters allowed"
+                raise ValueError("only named parameters allowed after first named parameter")
             else:
                 nr = i
                 parameter_list[nr] = value