[KSS-checkins] r49500 - in kukit/kss.demo/trunk/kss/demo: . browser selenium_utils

reebalazs at codespeak.net reebalazs at codespeak.net
Fri Dec 7 12:10:03 CET 2007


Author: reebalazs
Date: Fri Dec  7 12:10:03 2007
New Revision: 49500

Added:
   kukit/kss.demo/trunk/kss/demo/selenium_utils/builder.py
Modified:
   kukit/kss.demo/trunk/kss/demo/browser/registry.py
   kukit/kss.demo/trunk/kss/demo/interfaces.py
   kukit/kss.demo/trunk/kss/demo/registry.py
Log:
Some cleanup and preparation for zelenium hookup to registry.

Modified: kukit/kss.demo/trunk/kss/demo/browser/registry.py
==============================================================================
--- kukit/kss.demo/trunk/kss/demo/browser/registry.py	(original)
+++ kukit/kss.demo/trunk/kss/demo/browser/registry.py	Fri Dec  7 12:10:03 2007
@@ -4,6 +4,7 @@
 from zope.publisher.interfaces import NotFound
 from zope.component import getUtility
 from zope.interface import implements
+from kss.demo.selenium_utils.builder import cookSeleniumTests
 try:
     from Products.Five import BrowserView
     BrowserView         # make pyflakes happy
@@ -90,5 +91,8 @@
         of kss.demo.selenium_utils .
         """
         registry = getUtility(IKSSDemoRegistry)
-        registry.cookSeleniumTests()
-        return "Selenium tests cooked OK. (%i)" % (len(registry.selenium_tests), )
+        filenames = registry.selenium_tests
+        # Cook them. This will create seltest_all.py. 
+        cookSeleniumTests(filenames)
+        # We are done.
+        return "Selenium tests cooked OK. (%i)" % (len(filenames), )

Modified: kukit/kss.demo/trunk/kss/demo/interfaces.py
==============================================================================
--- kukit/kss.demo/trunk/kss/demo/interfaces.py	(original)
+++ kukit/kss.demo/trunk/kss/demo/interfaces.py	Fri Dec  7 12:10:03 2007
@@ -126,13 +126,6 @@
     def unregisterSeleniumTestFile(test_filename):
         """Unregister the given test directory."""
 
-    def cookSeleniumTests():
-        """Cook selenium tests
-
-        The *.html tests from each plugin are produced
-        into the file seltest_all.pty in the directory
-        of kss.demo.selenium_utils .
-        """
 
 # --
 # Event that gets redispatched, for allowing

Modified: kukit/kss.demo/trunk/kss/demo/registry.py
==============================================================================
--- kukit/kss.demo/trunk/kss/demo/registry.py	(original)
+++ kukit/kss.demo/trunk/kss/demo/registry.py	Fri Dec  7 12:10:03 2007
@@ -16,25 +16,12 @@
     IRegistered,
     IUnregistered,
     )
-import sys, os, re, textwrap
-from elementtree import HTMLTreeBuilder
-from string import Template
-import kss.demo.selenium_utils
-# shut the mouth of pyflakes
-kss.demo.selenium_utils
+from kss.demo.selenium_utils.builder import getSeleniumTestsFromSuite
 
 # --
 # Registry implementation for use with Zope
 # --
 
-def getRootDirOfModule(module_name):
-    return os.path.dirname(sys.modules[module_name].__file__)
-
-def getRootDirOfClass(cls):
-    return getRootDirOfModule(cls.__module__)
-
-def getRootDirOfInstance(obj):
-    return getRootDirOfClass(obj.__class__)
 
 # Create a mesh of provided interfaces
 # This is needed, because an utility must have a single interface.
@@ -76,6 +63,8 @@
         for name, plugin in site.getUtilitiesFor(IKSSDemoResource):
             for demo in plugin.demos:
                 self.registerDemo(demo)
+            for test_filename in self._getSeleniumTestsFromPlugin(plugin):
+                self.registerSeleniumTestFile(test_filename)
 
     @adapter(IKSSDemoResource, IUtilityRegistration, IRegistered, IKSSDemoRegistrationEvent)
     def registerDemosFromPlugin(self, plugin, registration=None, event=None, new_event=None):
@@ -142,13 +131,9 @@
     @staticmethod
     def _getSeleniumTestsFromPlugin(plugin):
         test_filenames = []
-        root_dir = getRootDirOfInstance(plugin)
-        for selenium_test_directory in plugin.selenium_tests:
-            tests_root_dir = os.path.join(root_dir, selenium_test_directory.test_directory)
-            for test_filename in os.listdir(tests_root_dir):
-                if test_filename.lower().endswith('.html') or \
-                        test_filename.endswith('.htm'):
-                    test_filenames.append(os.path.join(tests_root_dir, test_filename))
+        for selenium_test_suite in plugin.selenium_tests:
+            filenames = getSeleniumTestsFromSuite(plugin,  selenium_test_suite)
+            test_filenames.extend(filenames)
         return test_filenames
 
     @adapter(IKSSSeleniumTestResource, IUtilityRegistration, IRegistered, IKSSDemoRegistrationEvent)
@@ -178,77 +163,3 @@
             del self.selenium_tests[test_filename]
         except KeyError:
             raise Exception, 'The selenium test for %s is yet unregistered. Cannot remove.' % (test_filename, )
-
-    template = Template(textwrap.dedent('''\
-            from seleniumtestcase import SeleniumTestCase
-            import unittest, time
-
-            class seltest_$testname(SeleniumTestCase):
-
-            $tests
-
-            def test_suite():
-                return unittest.makeSuite(seltest_$testname)
-
-            if __name__ == "__main__":
-                unittest.main()
-            '''))
-
-    variable_regexp = re.compile('\$\{(?P<varname>\w*)\}')
-    @classmethod
-    def formatcommand(cls, command, *args):
-        if not command:
-            return '' # Change this to raise an exception?
-
-        arguments = []
-        for arg in args:
-            if not arg:
-                continue
-            matched = cls.variable_regexp.match(arg)
-            if matched is None:
-                arguments.append('"%s"'%arg)
-            else:
-                arguments.append("self.getVar('%s')"%matched.group('varname'))
-        return 'self.%s(%s)' % (command, ', '.join(arguments))
-
-    def cookSeleniumTests(self):
-        """Cook selenium tests
-
-        The *.html tests from each plugin are produced
-        into the file seltest_all.pty in the directory
-        of kss.demo.selenium_utils .
-        """
-        # Try to open the file for writing.
-        output_dir =  getRootDirOfModule('kss.demo.selenium_utils')
-        output_filename = os.path.join(output_dir, 'seltest_all.py')
-        try:
-            f = open(output_filename, 'wb')
-        except IOError, exc:
-            raise IOError, ('Cannot open file "%s" for writing. '
-                            'Make sure zope process has write access in directory. '
-                            '["%s"]') \
-                            % (output_filename, exc)
-
-        htmlparser = HTMLTreeBuilder.TreeBuilder()
-        tests = []
-        for filename in self.selenium_tests:
-            tree = HTMLTreeBuilder.parse(filename)
-            root = tree.getroot()
-
-            try:
-                testname = root.find('.//title').text
-            except AttributeError:
-                continue
-            commands = []
-            for row in root.findall('.//tbody/tr'):
-                commands.append(self.formatcommand(*[td.text for td in row.findall('td')]))
-
-            testfilename = 'seltest_%s.py' % testname
-            testbody='    def test_%s(self):\n'%testname+' '*8+'\n        '.join(commands)+'\n'
-            tests.append(testbody)
-
-        f.write(self.template.substitute(dict(
-            testname=testname,
-            tests='\n'.join(tests),
-            )))
-        f.close()

Added: kukit/kss.demo/trunk/kss/demo/selenium_utils/builder.py
==============================================================================
--- (empty file)
+++ kukit/kss.demo/trunk/kss/demo/selenium_utils/builder.py	Fri Dec  7 12:10:03 2007
@@ -0,0 +1,113 @@
+
+import sys, os, re, textwrap
+from elementtree import HTMLTreeBuilder
+from string import Template
+
+# --
+# This is used to build the seltest_all.py file into the same directory.
+# --
+
+# root directory finding code
+def getRootDirOfModule(module_name):
+    return os.path.dirname(sys.modules[module_name].__file__)
+
+def getRootDirOfClass(cls):
+    return getRootDirOfModule(cls.__module__)
+
+def getRootDirOfInstance(obj):
+    return getRootDirOfClass(obj.__class__)
+
+def getSeleniumTestsFromSuite(owner_instance, suite):
+    """Get absolute filenames of all tests from the suite.
+    Suite contains the directory that we need to find.
+    owner_instance is used for the directory finding,
+    the suite's directory is traversed relative from that.
+    """
+    test_filenames = []
+    # The owner instance is only used to traverse the sute directory
+    # relative from it.
+    root_dir = getRootDirOfInstance(owner_instance)
+    tests_root_dir = os.path.join(root_dir, suite.test_directory)
+    for test_filename in os.listdir(tests_root_dir):
+        if test_filename.lower().endswith('.html') or \
+                test_filename.endswith('.htm'):
+            test_filenames.append(os.path.join(tests_root_dir, test_filename))
+    return test_filenames
+
+template = Template(textwrap.dedent('''\
+        from seleniumtestcase import SeleniumTestCase
+        import unittest, time
+
+        class seltest_$testname(SeleniumTestCase):
+
+        $tests
+
+        def test_suite():
+            return unittest.makeSuite(seltest_$testname)
+
+        if __name__ == "__main__":
+            unittest.main()
+        '''))
+
+variable_regexp = re.compile('\$\{(?P<varname>\w*)\}')
+
+def formatcommand(command, *args):
+    if not command:
+        return '' # Change this to raise an exception?
+
+    arguments = []
+    for arg in args:
+        if not arg:
+            continue
+        matched = variable_regexp.match(arg)
+        if matched is None:
+            arguments.append('"%s"'%arg)
+        else:
+            arguments.append("self.getVar('%s')"%matched.group('varname'))
+    return 'self.%s(%s)' % (command, ', '.join(arguments))
+
+
+
+def cookSeleniumTests(filenames):
+    """Cook selenium tests
+    """
+    # Try to open the file for writing.
+    output_dir =  getRootDirOfModule('kss.demo.selenium_utils')
+    output_filename = os.path.join(output_dir, 'seltest_all.py')
+    try:
+        f = open(output_filename, 'wb')
+    except IOError, exc:
+        raise IOError, ('Cannot open file "%s" for writing. '
+                        'Make sure zope process has write access in directory. '
+                        '["%s"]') \
+                        % (output_filename, exc)
+
+    htmlparser = HTMLTreeBuilder.TreeBuilder()
+    tests = []
+
+    # Now, we find all filenames that are in the suite passed to us.
+    testname = 'all'
+
+    for filename in filenames:
+        tree = HTMLTreeBuilder.parse(filename)
+        root = tree.getroot()
+
+        try:
+            testname = root.find('.//title').text
+        except AttributeError:
+            continue
+        commands = []
+        for row in root.findall('.//tbody/tr'):
+            commands.append(formatcommand(*[td.text for td in row.findall('td')]))
+
+        testfilename = 'seltest_%s.py' % testname
+        testbody='    def test_%s(self):\n'%testname+' '*8+'\n        '.join(commands)+'\n'
+        tests.append(testbody)
+
+    # Use the last test's name as filename (???)
+    # XXX I think we want to change this.
+    f.write(template.substitute(dict(
+        testname=testname,
+        tests='\n'.join(tests),
+        )))
+    f.close()


More information about the Kukit-checkins mailing list