PyXR

c:\python24\lib\site-packages\win32 \ com \ test \ testall.py



0001 import sys, os, string, re
0002 import pythoncom
0003 import win32com.client
0004 from util import CheckClean, TestCase, CapturingFunctionTestCase, TestLoader
0005 import win32com.test.util
0006 import traceback
0007 import getopt
0008 
0009 import unittest
0010 
0011 verbosity = 1 # default unittest verbosity.
0012 
0013 try:
0014     this_file = __file__
0015 except NameError:
0016     this_file = sys.argv[0]
0017 
0018 def GenerateAndRunOldStyle():
0019     import GenTestScripts
0020     GenTestScripts.GenerateAll()
0021     try:
0022         pass #
0023     finally:
0024         GenTestScripts.CleanAll()
0025 
0026 def CleanGenerated():
0027     import win32com, shutil
0028     if os.path.isdir(win32com.__gen_path__):
0029         if verbosity > 1:
0030             print "Deleting files from %s" % (win32com.__gen_path__)
0031         shutil.rmtree(win32com.__gen_path__)
0032     import win32com.client.gencache
0033     win32com.client.gencache.__init__() # Reset
0034 
0035 def RemoveRefCountOutput(data):
0036     while 1:
0037         last_line_pos = data.rfind("\n")
0038         if not re.match("\[\d+ refs\]", data[last_line_pos+1:]):
0039             break
0040         if last_line_pos < 0:
0041             # All the output
0042             return ''
0043         data = data[:last_line_pos]
0044         
0045     return data
0046 
0047 def ExecuteSilentlyIfOK(cmd, testcase):
0048     f = os.popen(cmd)
0049     data = f.read().strip()
0050     rc = f.close()
0051     if rc:
0052         print data
0053         testcase.fail("Executing '%s' failed (%d)" % (cmd, rc))
0054     # for "_d" builds, strip the '[xxx refs]' line
0055     return RemoveRefCountOutput(data)
0056 
0057 class PyCOMTest(TestCase):
0058     no_leak_tests = True # done by the test itself
0059     def testit(self):
0060         # Execute testPyComTest in its own process so it can play
0061         # with the Python thread state
0062         fname = os.path.join(os.path.dirname(this_file), "testPyComTest.py")
0063         cmd = '%s "%s" -q 2>&1' % (sys.executable, fname)
0064         data = ExecuteSilentlyIfOK(cmd, self)
0065 
0066 class PippoTest(TestCase):
0067     def testit(self):
0068         python = sys.executable
0069         fname = os.path.join(os.path.dirname(this_file), "testPippo.py")
0070         cmd = '%s "%s" 2>&1' % (python, fname)
0071         ExecuteSilentlyIfOK(cmd, self)
0072 
0073 unittest_modules = [
0074         # Level 1 tests.
0075         """testIterators testvbscript_regexp testStorage 
0076           testStreams testWMI policySemantics testShell testROT
0077           testAXScript testxslt testDictionary testCollections
0078           testServers errorSemantics.test testvb testArrays
0079           testClipboard
0080         """.split(),
0081         # Level 2 tests.
0082         """testMSOffice.TestAll testMSOfficeEvents.test testAccess.test
0083            testExplorer.TestAll testExchange.test
0084         """.split(),
0085         # Level 3 tests.
0086         """testmakepy.TestAll
0087         """.split()
0088 ]
0089 
0090 output_checked_programs = [
0091         # Level 1 tests.
0092         [
0093             ("cscript.exe /nologo testInterp.vbs", "VBScript test worked OK"),
0094             ("cscript.exe /nologo testDictionary.vbs",
0095                          "VBScript has successfully tested Python.Dictionary"),
0096         ],
0097         # Level 2 tests.
0098         [
0099         ],
0100         # Level 3 tests
0101         [
0102         ],
0103 ]
0104 
0105 custom_test_cases = [
0106         # Level 1 tests.
0107         [
0108             PyCOMTest,
0109             PippoTest,
0110         ],
0111         # Level 2 tests.
0112         [
0113         ],
0114         # Level 3 tests
0115         [
0116         ],
0117 ]
0118 
0119 def get_test_mod_and_func(test_name, import_failures):
0120     if test_name.find(".")>0:
0121         mod_name, func_name = test_name.split(".")
0122     else:
0123         mod_name = test_name
0124         func_name = None
0125     try:
0126         mod = __import__(mod_name)
0127     except:
0128         import_failures.append((mod_name, sys.exc_info()[:2]))
0129         return None, None
0130     if func_name is None:
0131         func = None
0132     else:
0133         func = getattr(mod, func_name)
0134     return mod, func
0135 
0136 # Return a test suite all loaded with the tests we want to run
0137 def make_test_suite(test_level = 1):
0138     suite = unittest.TestSuite()
0139     import_failures = []
0140     loader = TestLoader()
0141     for i in range(testLevel):
0142         for mod_name in unittest_modules[i]:
0143             mod, func = get_test_mod_and_func(mod_name, import_failures)
0144             if mod is None:
0145                 continue
0146             if func is not None:
0147                 test = win32com.test.util.CapturingFunctionTestCase(func,
0148                                                      description=mod_name)
0149             else:
0150                 if hasattr(mod, "suite"):
0151                     test = mod.suite()
0152                 else:
0153                     test = loader.loadTestsFromModule(mod)
0154             assert test.countTestCases() > 0, "No tests loaded from %r" % mod
0155             suite.addTest(test)
0156         for cmd, output in output_checked_programs[i]:
0157             suite.addTest(win32com.test.util.ShellTestCase(cmd, output))
0158 
0159         for test_class in custom_test_cases[i]:
0160             suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(test_class))
0161     return suite, import_failures
0162 
0163 def usage(why):
0164     print why
0165     print
0166     print "win32com test suite"
0167     print "usage: testall [-v] test_level"
0168     print "  where test_level is an integer 1-3.  Level 1 tests are quick,"
0169     print "  level 2 tests invoke Word, IE etc, level 3 take ages!"
0170     sys.exit(1)
0171     
0172 if __name__=='__main__':
0173     try:
0174         opts, args = getopt.getopt(sys.argv[1:], "v")
0175     except getopt.error, why:
0176         usage(why)
0177     for opt, val in opts:
0178         if opt=='-v':
0179             verbosity += 1
0180     testLevel = 1 # default to quick test
0181     test_names = []
0182     for arg in args:
0183         try:
0184             testLevel = int(arg)
0185             if testLevel < 0 or testLevel > 3:
0186                 raise ValueError, "Only levels 1-3 are supported"
0187         except ValueError:
0188             test_names.append(arg)
0189     if test_names:
0190         usage("Test names are not supported yet")
0191     CleanGenerated()
0192     
0193     suite, import_failures = make_test_suite(testLevel)
0194     if verbosity:
0195         if hasattr(sys, "gettotalrefcount"):
0196             print "This is a debug build - memory leak tests will also be run."
0197             print "These tests may take *many* minutes to run - be patient!"
0198             print "(running from python.exe will avoid these leak tests)"
0199         print "Executing level %d tests - %d test cases will be run" \
0200                 % (testLevel, suite.countTestCases())
0201         if verbosity==1 and suite.countTestCases() < 70:
0202             # A little row of markers so the dots show how close to finished
0203             print '|' * suite.countTestCases()
0204     testRunner = unittest.TextTestRunner(verbosity=verbosity)
0205     testResult = testRunner.run(suite)
0206     if import_failures:
0207         testResult.stream.writeln("*** The following test modules could not be imported ***")
0208         for mod_name, (exc_type, exc_val) in import_failures:
0209             desc = testResult._exc_info_to_string( (exc_type, exc_val, None) )
0210             testResult.stream.write("%s: %s" % (mod_name, desc))
0211         testResult.stream.writeln("*** %d test(s) could not be run ***" % len(import_failures))
0212     
0213     # re-print unit-test error here so it is noticed
0214     if not testResult.wasSuccessful():
0215         print "*" * 20, "- unittest tests FAILED"
0216     
0217     CheckClean()
0218     pythoncom.CoUninitialize()
0219     CleanGenerated()
0220 

Generated by PyXR 0.9.4
SourceForge.net Logo