add python --test-file support
authorAntony Lesuisse <al@openerp.com>
Sun, 9 Feb 2014 01:46:36 +0000 (02:46 +0100)
committerAntony Lesuisse <al@openerp.com>
Sun, 9 Feb 2014 01:46:36 +0000 (02:46 +0100)
bzr revid: al@openerp.com-20140209014636-2fbl15q8wrubmiup

openerp/addons/base/__init__.py
openerp/cli/server.py
openerp/service/server.py
openerp/sql_db.py
openerp/tools/config.py

index a5bc4c5..26b39de 100644 (file)
@@ -25,6 +25,7 @@ import module
 import res
 import report
 import test
+import tests
 
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
 
index 09557a7..004cb1a 100644 (file)
@@ -89,19 +89,6 @@ def setup_pid_file():
             pidtext = "%d" % (os.getpid())
             fd.write(pidtext)
 
-def run_test_file(dbname, test_file):
-    """ Preload a registry, possibly run a test file, and start the cron."""
-    try:
-        config = openerp.tools.config
-        registry = openerp.modules.registry.RegistryManager.new(dbname, update_module=config['init'] or config['update'])
-        cr = registry.db.cursor()
-        _logger.info('loading test file %s', test_file)
-        openerp.tools.convert_yaml_import(cr, 'base', file(test_file), 'test', {}, 'test', True)
-        cr.rollback()
-        cr.close()
-    except Exception:
-        _logger.exception('Failed to initialize database `%s` and run test file `%s`.', dbname, test_file)
-
 def export_translation():
     config = openerp.tools.config
     dbname = config['db_name']
@@ -146,8 +133,7 @@ def main(args):
     config = openerp.tools.config
 
     if config["test_file"]:
-        run_test_file(config['db_name'], config['test_file'])
-        sys.exit(0)
+        config["test_enable"] = True
 
     if config["translate_out"]:
         export_translation()
index 4f05e17..aaf469c 100644 (file)
@@ -9,6 +9,7 @@ import os.path
 import platform
 import psutil
 import random
+import re
 import resource
 import select
 import signal
@@ -17,6 +18,7 @@ import subprocess
 import sys
 import threading
 import time
+import unittest2
 
 import werkzeug.serving
 
@@ -823,16 +825,45 @@ def _reexec(updated_modules=None):
         args.insert(0, exe)
     os.execv(sys.executable, args)
 
+def load_test_file_yml(test_file):
+    cr = registry.db.cursor()
+    openerp.tools.convert_yaml_import(cr, 'base', file(test_file), 'test', {}, 'test', True)
+    cr.rollback()
+    cr.close()
+
+def load_test_file_py(test_file):
+    # Locate python module based on its filename and run the tests
+    test_path, _ = os.path.splitext(os.path.abspath(test_file))
+    for mod_name, mod_mod in sys.modules.items():
+        if mod_mod:
+            mod_path, _ = os.path.splitext(getattr(mod_mod, '__file__', ''))
+            if test_path == mod_path:
+                suite = unittest2.TestSuite()
+                for t in unittest2.TestLoader().loadTestsFromModule(mod_mod):
+                    suite.addTest(t)
+                _logger.log(logging.INFO, 'running tests %s.', mod_mod.__name__)
+                result = unittest2.TextTestRunner(verbosity=2, stream=openerp.modules.module.TestStream()).run(suite)
+                if not result.wasSuccessful():
+                    r = False
+                    _logger.error('module %s: at least one error occurred in a test', module_name)
+
 def preload_registries(dbnames):
-    """ Preload a registries."""
+    """ Preload a registries, possibly run a test file."""
+    # TODO: move all config checks to args dont check tools.config here
+    config = openerp.tools.config
+    test_file = config['test_file']
     dbnames = dbnames or []
     for dbname in dbnames:
         try:
-            update_module = openerp.tools.config['init'] or openerp.tools.config['update']
+            update_module = config['init'] or config['update']
             registry = openerp.modules.registry.RegistryManager.new(dbname, update_module=update_module)
-            #if config['test_enable']:
-            #    openerp.modules.module.run_http_test(config['db_name'])
-            #if registry._assertion_report.failures != 0:
+            # run test_file if provided
+            if test_file:
+                _logger.info('loading test file %s', test_file)
+                if test_file.endswith('yml'):
+                    load_test_file_yml(test_file)
+                elif test_file.endswith('py'):
+                    load_test_file_py(test_file)
         except Exception:
             _logger.exception('Failed to initialize database `%s`.', dbname)
             return
index d8dc5c7..de9d21d 100644 (file)
@@ -282,9 +282,6 @@ class Cursor(object):
         return self._close(False)
 
     def _close(self, leak=False):
-        #import traceback
-        #traceback.print_stack()
-
         if not self._obj:
             return
 
index ebfd8ce..91fdbca 100644 (file)
@@ -157,7 +157,7 @@ class configmanager(object):
         # Testing Group
         group = optparse.OptionGroup(parser, "Testing Configuration")
         group.add_option("--test-file", dest="test_file", my_default=False,
-                         help="Launch a YML test file.")
+                         help="Launch a python or YML test file.")
         group.add_option("--test-report-directory", dest="test_report_directory", my_default=False,
                          help="If set, will save sample of all reports in this directory.")
         group.add_option("--test-enable", action="store_true", dest="test_enable",