pygame is sharing code with you
Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.
Don't show this againpygame / test_runner.py
- Tag
- release_1_8_1rc2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | ################################################################################
import sys, os, re, unittest, StringIO, time, optparse
from inspect import getdoc, getmembers, isclass
from pprint import pformat
################################################################################
def prepare_test_env():
main_dir = os.path.split(os.path.abspath(__file__))[0]
test_subdir = os.path.join(main_dir, 'test')
sys.path.insert(0, test_subdir)
fake_test_subdir = os.path.join(test_subdir, 'run_tests__tests')
return main_dir, test_subdir, fake_test_subdir
main_dir, test_subdir, fake_test_subdir = prepare_test_env()
import test_utils
################################################################################
# Set the command line options
#
# options are shared with run_tests.py so make sure not to conflict
# in time more will be added here
opt_parser = optparse.OptionParser()
opt_parser.add_option (
"-i", "--incomplete", action = 'store_true',
help = "fail incomplete tests" )
opt_parser.add_option (
"-s", "--subprocess", action = 'store_true',
help = "run test suites in subprocesses (default: same process)" )
opt_parser.add_option (
"-d", "--dump", action = 'store_true',
help = "dump failures/errors as dict ready to eval" )
opt_parser.add_option (
"-e", "--exclude",
help = "exclude tests containing any of TAGS" )
opt_parser.add_option (
"-a", "--all", action = 'store_true',
help = "dump all results not just errors eg. -da" )
opt_parser.add_option (
"-H", "--human", action = 'store_true',
help = "dump results as dict ready to eval if unsure "
"that pieced together results are correct "
"(subprocess mode)" ) # TODO
opt_parser.add_option (
"-m", "--multi_thread", metavar = 'THREADS', type = 'int',
help = "run subprocessed tests in x THREADS" )
opt_parser.add_option (
"-t", "--time_out", metavar = 'SECONDS', type = 'int',
help = "kill stalled subprocessed tests after SECONDS" )
opt_parser.add_option (
"-f", "--fake", metavar = "DIR",
help = "run fake tests in run_tests__tests/$DIR" )
opt_parser.add_option (
"-p", "--python", metavar = "PYTHON",
help = "path to python excutable to run subproccesed tests\n"
"default (sys.executable): %s" % sys.executable)
################################################################################
TEST_RESULTS_START = "<--!! TEST RESULTS START HERE !!-->"
TEST_RESULTS_RE = re.compile('%s\n(.*)' % TEST_RESULTS_START, re.DOTALL | re.M)
FILE_LINENUMBER_RE = re.compile(r'File "([^"]+)", line ([0-9]+)')
def get_test_results(raw_return):
test_results = TEST_RESULTS_RE.search(raw_return)
if test_results:
try: return eval(test_results.group(1))
except: raise Exception (
"BUGGY TEST RESULTS EVAL:\n %s" % test_results.group(1)
)
def count(results, *args, **kw):
if kw.get('single'): results = {'single' : results}
for arg in args:
all_of = [a for a in [v.get(arg) for v in results.values()] if a]
if not all_of: yield 0
else:
if isinstance(all_of[0], int): the_sum = all_of
else: the_sum = (len(v) for v in all_of)
yield sum(the_sum)
################################################################################
def redirect_output():
yield sys.stderr, sys.stdout
sys.stderr, sys.stdout = StringIO.StringIO(), StringIO.StringIO()
yield sys.stderr, sys.stdout
def restore_output(err, out):
sys.stderr, sys.stdout = err, out
def StringIOContents(io):
io.seek(0)
return io.read()
def merged_dict(*args):
dictionary = {}
for arg in args: dictionary.update(arg)
return dictionary
def from_namespace(ns, listing):
return dict((i, ns[i]) for i in listing)
def many_modules_key(modules):
return ', '.join(modules)
################################################################################
# ERRORS
unittest._TextTestResult.monkeyRepr = lambda self, flavour, errors: [
(
"%s: %s" % (flavour, self.getDescription(e[0])), # Description
e[1], # TraceBack
FILE_LINENUMBER_RE.search(e[1]).groups(), # Blame Info
)
for e in errors
]
def make_complete_failure_error(result):
return (
"ERROR: all_tests_for (%s.AllTestCases)" % result['module'],
"Complete Failure (ret code: %s)" % result['return_code'],
(result['test_file'], '1'),
)
def combined_errs(results):
for result in results.itervalues():
combined_errs = result['errors'] + result['failures']
for err in combined_errs:
yield err
# For combined results, plural, used in subprocess mode
def test_failures(results):
errors = {}
total, = count(results, 'num_tests')
for module, result in results.items():
num_errors = sum(count(result, 'failures', 'errors', single = 1))
if num_errors is 0 and result['return_code']:
result.update(RESULTS_TEMPLATE)
result['errors'].append(make_complete_failure_error(result))
num_errors += 1
if num_errors: errors.update({module:result})
return total, errors
################################################################################
TAGS_RE = re.compile(r"\|[tT]ags:([ a-zA-Z,0-9_\n]+)\|", re.DOTALL | re.MULTILINE)
def get_tags(obj):
tags = TAGS_RE.search(getdoc(obj) or '')
return tags and [t.strip() for t in tags.group(1).split(',')] or []
def is_test_case(obj):
return isclass(obj) and issubclass(obj, unittest.TestCase)
def is_test(obj):
return callable(obj) and obj.__name__.startswith('test_')
def filter_by_tags(module, tags):
for tcstr, test_case in (m for m in getmembers(module, is_test_case)):
for tstr, test in (t for t in getmembers(test_case, is_test)):
for tag in get_tags(test):
if tag in tags:
exec 'del module.%s.%s' % (tcstr, tstr)
break
################################################################################
# For complete failures (+ namespace saving)
RESULTS_TEMPLATE = {
'output' : '',
'stderr' : '',
'stdout' : '',
'num_tests' : 0,
'failures' : [],
'errors' : [],
}
################################################################################
def run_test(modules, options):
if isinstance(modules, str): modules = [modules]
suite = unittest.TestSuite()
#TODO: ability to pass module.TestCase etc (names) from run_test.py
for module in modules:
m = __import__(module)
print 'loading', module
if options.exclude:
filter_by_tags(m, [e.strip() for e in options.exclude.split(',')])
# decorate tests with profiling wrappers etc
test = unittest.defaultTestLoader.loadTestsFromName(module)
suite.addTest(test)
(realerr, realout), (stderr, stdout) = redirect_output()
# restore_output(realerr, realout) DEBUG
output = StringIO.StringIO()
runner = unittest.TextTestRunner(stream = output)
test_utils.fail_incomplete_tests = options.incomplete
results = runner.run(suite)
output, stderr, stdout = map(StringIOContents, (output, stderr, stdout))
restore_output(realerr, realout)
num_tests = results.testsRun
failures = results.monkeyRepr('FAIL', results.failures)
errors = results.monkeyRepr('ERROR', results.errors)
# conditional adds here
results = {
many_modules_key(modules): from_namespace(locals(), RESULTS_TEMPLATE)
}
if options.subprocess:
print TEST_RESULTS_START
print pformat(results)
else:
return results
if __name__ == '__main__':
options, args = opt_parser.parse_args()
if not args: sys.exit('Called from run_tests.py, use that')
run_test(args[0], options)
################################################################################
|