User:Hanya/Python Test Executor
From Apache OpenOffice Wiki
If new version of Python is introduced as shipped Python, bundled test cases should be executed to check standard libraries work well. There are a few problems to execute these test cases from Python macro. Here is Python script having some settings that avoids errors.
Store the following content into $(user)/Scripts/python/test.py and execute test_all or test_ function.
import uno import sys import os.path import platform import locale import builtins STORE_IN_LOGFILE = False LOG_PATH = None LOGGER = None # some tests have problem with the uno importer function, # so use default import function in regression test _default_importer = uno._g_delegatee _uno_importer = uno._uno_import def _set_default_importer(): builtins.__dict__["__import__"] = _default_importer def _set_uno_importer(): builtins.__dict__["__import__"] = _uno_importer class LogWriter: def write(self, s): if LOG_PATH: with open(LOG_PATH, "a") as f: f.seek(0, whence=2) f.write(s) def create(script_context, name): ctx = script_context.getComponentContext() return ctx.getServiceManager().createInstanceWithContext(name, ctx) def _set_io(): if STORE_IN_LOGFILE: global LOG_PATH if LOG_PATH is None: LOG_PATH = uno.fileUrlToSystemPath( create(XSCRIPTCONTEXT, "com.sun.star.util.PathSubstitution").substituteVariables( "$(user)/Scripts/python/test.log")) global LOGGER = LogWriter() sys.stdout = LOGGER sys.stderr = LOGGER def _reset_io(): sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ def _set_vars(): python_name = "python.exe" if platform.system() == "Windows" else "python" office_dir = create(XSCRIPTCONTEXT, "com.sun.star.util.OfficeInstallationDirectories").getOfficeInstallationDirectoryURL() python_path = os.path.join(uno.fileUrlToSystemPath(office_dir), "program", python_name) # set parameters for test through command line arguments sys.argv = ["-r", "-w", "-n", "-u" "all"]#"all,-largefile,-audio,-gui"] # set executable path because not executable path has been set sys.executable = python_path # for some modules such as datetime locale.setlocale(locale.LC_ALL, "C") def test_all(): """ Execute all regression test. """ if STORE_IN_LOGFILE: _set_io() _set_vars() _set_default_importer() try: import test.__main__ except: pass finally: _set_uno_importer() if STORE_IN_LOGFILE: _reset_io() class TestEnv: def __init__(self, module): self.module = module def __enter__(self): _set_vars() _set_default_importer() return self def __exit__(self, *args): _set_uno_importer() return False def start(self): _exec_test(self.module) def _exec_test(module): module.test_main() def test_(): """ Execute selected test. """ import test.test_ssl as module with TestEnv(module) as t: t.start() g_exportedScripts = test_all, test_,