#! /usr/bin/env python

import glob
import os
import struct
import sys
import unittest

_glob_test_py = 'test_*.py'

if os.linesep == '\n':
    def _print(text):
        print(text)
else:
    def _print(text):
        print(text.replace('\n', os.linesep))

def get_tests(dir='.', clean=False):
    '''Get a list of test module names in the given directory.
    '''
    res, dir_ = [], ''
     # walk recursively through all subdirectories
    if os.path.isdir(dir):
        if dir != '.':
           dir_ = dir.rstrip(os.sep) + os.sep
        for sub in os.listdir(dir):
            if sub[0] != '.':  # os.curdir
               sub = dir_ + sub
               if os.path.isdir(sub):
                   res.extend(get_tests(sub))
        glob_py = dir_ + _glob_test_py
#   elif dir[-3:] == '.py':
#       glob_py = dir
#       sub = os.path.split(dir)[0]
#       if sub:  # prefix
#           dir_ = sub + os.sep
    else:
        return res
     # append all tests as module names
    for test in glob.glob(glob_py):
        test = dir_ + os.path.basename(test)
        if clean:  # remove existing bytecodes
            for co in ('c', 'o'):
                try:
                    os.remove(test + co)
                except OSError:
                    pass
         # convert to module name
        test = test[:-3].replace(os.sep, '.')
        res.append(test)
    return res  # sorted(res)

def suite(dirs=['.'], clean=False, pre=True, verbose=2):
    '''Create a suite with all tests from the given directories.

    This will also include tests from subdirectories.
    '''
    all = True
    res = unittest.TestSuite()
    for dir in dirs:
        for test in get_tests(dir, clean):
            # Import tests relative to 'test' directory
            test = test[test.find('.')+1:]
            try:
                mod = test.rfind('.') + 1
                if mod > 0:  # from test import mod
                   mod = test[mod:]
                   mod = __import__(test, globals(), locals(), [mod])
                else:  # import test
                   mod = __import__(test)
                res.addTest(unittest.defaultTestLoader.loadTestsFromModule(mod))
            except (SyntaxError, NameError, ImportError):
                if pre:
                   _print('Warning: ignoring %r due to an error while importing' % test)
                else:
                   _print('Error: %r missing or not found' % test)
                if verbose > 2:
                    raise  # show the error
                all = False
    return res, all


if __name__ == '__main__':

     # default values for options
    clean   = False  # -c[lean]  -- remove all .pyo and .pyc files
    pre     = True   # -pre[-install]  or  -try  before installation
   #pre     = False  # -post[-install]  or  -test  after installation
    verbose = 2      # -v[erbose] <level>  -- verbosity level

     # get options and test case directories (files?)
    dirs = sys.argv[1:]
    while dirs:
        t = dirs[0]
        n = len(t)
        if '-clean'.startswith(t) and n > 1:
            clean = True
        elif ('-post-install'.startswith(t) and n > 4) or \
             ('-test'.startswith(t) and n > 2):
            pre = False
        elif ('-pre-install'.startswith(t) and n > 3) or \
             ('-try'.startswith(t) and n > 2):
            pre = True
        elif '-verbose'.startswith(t) and n > 1:
            verbose = int(dirs.pop(1))
        else:
            break
        dirs = dirs[1:]
    else:
        dirs = ['.']

     # insert parent directory such that
     # the code modules can be imported,
     # but only for pre-install testing
    t = os.path.split(sys.path[0])
    if t and pre:
        sys.path.insert(1, t[0])

     # print some details
    if verbose > 1:
        t = '%d-bit [' % (struct.calcsize('P') << 3)
        _print('Python %s\n' % sys.version.replace('[', t))
        if verbose > 4:
            t = '\n          '  # indentation
            _print('Sys.path: %s\n' % t.join(sys.path))
        if verbose > 3:
            _print('Test dirs: %r\n' % dirs)

     # build and run single test suite
    tst, all = suite(dirs, clean=clean, pre=pre, verbose=verbose)
    if pre or all:
        res = unittest.TextTestRunner(verbosity=verbose).run(tst)
        if res.wasSuccessful():
            sys.exit(0)
    sys.exit(1)

@@ -2721,18 +2721,15 @@
 l%5D  
-or  -
+-- 
 try 
- 
 befo
@@ -2788,19 +2788,16 @@
 l%5D  
-or  -
+-- 
 test 
- 
 afte
@@ -3090,17 +3090,16 @@
    elif 
-(
 '-post-i
@@ -3133,61 +3133,8 @@
  %3E 4
-) or %5C%0A             ('-test'.startswith(t) and n %3E 2)
 :%0A  
@@ -3168,17 +3168,16 @@
    elif 
-(
 '-pre-in
@@ -3210,60 +3210,8 @@
  %3E 3
-) or %5C%0A             ('-try'.startswith(t) and n %3E 2)
 :%0A  

remove duplicate options