Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def loadTestsFromTestCase(self, testCaseClass):
debug("Examining test case {}".format(testCaseClass.__name__), 3)
def filter_test_methods(attrname):
return attrname.startswith(self.testMethodPrefix) \
and callable(getattr(testCaseClass, attrname)) \
and not isTestCaseDisabled(testCaseClass, attrname)
test_case_names = list(filter(filter_test_methods, dir(testCaseClass)))
debug("Test case names: {}".format(test_case_names))
# Use default unittest.TestSuite sorting method if not overriden
test_case_names.sort(
key=functools.cmp_to_key(self.sortTestMethodsUsing))
if not test_case_names and hasattr(testCaseClass, 'runTest'):
test_case_names = ['runTest']
return flattenTestSuite(map(testCaseClass, test_case_names))
'\n' + color_func(outcome) +
' in ' + self.colors.bold(test.dotted_name))
# Traceback
if not self.args.no_tracebacks:
relevant_frames = []
for i, frame in enumerate(err.traceback_lines):
# Python2 tracebacks containing unicode need some special handling
# This doesn't always make it readable, but at least it doesn't
# crash
if sys.version_info[0] == 2: # pragma: no cover
try:
''.join([frame]) # intentionally trigger exceptions
except UnicodeDecodeError:
frame = frame.decode('utf-8')
debug('\n' + '*' * 30 + "Frame {}:".format(i) + '*' * 30
+ "\n{}".format(self.colors.yellow(frame)), level=3)
# Ignore useless frames
if self.verbose < 4:
if frame.strip() == "Traceback (most recent call last):":
continue
# Done with this frame, capture it.
relevant_frames.append(frame)
self.stream.write(''.join(relevant_frames))
# Captured output for failing tests
self.displayStdout(test)
self.displayStderr(test)
def loadFromModuleFilename(self, filename):
dotted_module, parent_dir = findDottedModuleAndParentDir(filename)
# Adding the parent path of the module to the start of sys.path is
# the closest we can get to an absolute import in Python that I can
# find.
sys.path.insert(0, parent_dir)
try:
__import__(dotted_module)
loaded_module = sys.modules[dotted_module]
debug("Imported {}".format(dotted_module), 2)
except unittest.case.SkipTest as e:
# TODO: #25 - Right now this mimics the behavior in unittest. Lets
# refactor it and simplify it after we make sure it works.
# This is a cause of the traceback mangling I observed.
reason = str(e)
@unittest.case.skip(reason)
def testSkipped(self):
pass # pragma: no cover
TestClass = type(
str("ModuleSkipped"),
(unittest.case.TestCase,),
{filename: testSkipped})
return self.suiteClass((TestClass(filename),))
except:
def loadTarget(self, target, file_pattern='test*.py'):
"""
"""
debug("Attempting to load target '{}' with file_pattern '{}'".format(
target, file_pattern))
# For a test loader, we want to always the current working directory to
# be the first item in sys.path, just like when a python interpreter is
# loaded interactively. See also
# https://docs.python.org/3.8/library/sys.html#sys.path
if sys.path[0] != '':
sys.path.insert(0, '')
# DIRECTORY VARIATIONS - These will discover all tests in a directory
# structure, whether or not they are accessible by the root package.
# some/real/dir
bare_dir = target
# some.real.dir
if ('.' in target) and (len(target) > 1):
def loadTestsFromTestCase(self, testCaseClass):
debug("Examining test case {}".format(testCaseClass.__name__), 3)
def filter_test_methods(attrname):
return attrname.startswith(self.testMethodPrefix) \
and callable(getattr(testCaseClass, attrname)) \
and not isTestCaseDisabled(testCaseClass, attrname)
test_case_names = list(filter(filter_test_methods, dir(testCaseClass)))
debug("Test case names: {}".format(test_case_names))
# Use default unittest.TestSuite sorting method if not overriden
test_case_names.sort(
key=functools.cmp_to_key(self.sortTestMethodsUsing))
if not test_case_names and hasattr(testCaseClass, 'runTest'):
test_case_names = ['runTest']
return flattenTestSuite(map(testCaseClass, test_case_names))
full dotted name of the module with respect to the package it is in, and
parent_dir is the absolute path to the parent directory of the package.
If the python file is not part of a package, I return (None, None).
For for filepath /a/b/c/d.py where b is the package, ('b.c.d', '/a')
would be returned.
"""
if not os.path.isfile(file_path):
raise ValueError("'{}' is not a file.".format(file_path))
parent_dir = os.path.dirname(os.path.abspath(file_path))
dotted_module = os.path.basename(file_path).replace('.py', '')
while isPackage(parent_dir):
dotted_module = os.path.basename(parent_dir) + '.' + dotted_module
parent_dir = os.path.dirname(parent_dir)
debug("Dotted module: {} -> {}".format(
parent_dir, dotted_module), 2)
return (dotted_module, parent_dir)
if target and (target[0] != '.'):
try:
filename = importlib.import_module(target).__file__
if '__init__.py' in filename:
pkg_in_path_dir = os.path.dirname(filename)
except:
pkg_in_path_dir = None
# => DISCOVER DIRS
tests = None
for candidate in [bare_dir, dot_dir, pkg_in_path_dir]:
if (candidate is None) or (not os.path.isdir(candidate)):
continue
tests = self.discover(candidate, file_pattern=file_pattern)
if tests and tests.countTestCases():
debug("Load method: DISCOVER - {}".format(candidate))
return flattenTestSuite(tests)
# DOTTED OBJECT - These will discover a specific object if it is
# globally importable or importable from the current working directory.
# Examples: pkg, pkg.module, pkg.module.class, pkg.module.class.func
tests = None
if target and (target[0] != '.'): # We don't handle relative
try: # dot objects
tests = self.suiteClass(self.loadTestsFromName(target))
for index, test in enumerate(tests):
if test.__class__.__name__ == '_FailedTest': # pragma: no cover
del(tests._tests[index])
except Exception as e:
debug("IGNORED exception: {}".format(e))
if tests and tests.countTestCases():
if subdir_suite:
suite.addTest(subdir_suite)
elif os.path.isfile(path):
# Skip irrelevant files
if not python_file_pattern.match(file_or_dir_name):
continue
if not fnmatch(file_or_dir_name, file_pattern):
continue
# Try loading the file as a module
module_suite = self.loadFromModuleFilename(path)
if module_suite:
suite.addTest(module_suite)
except OSError:
debug("WARNING: Test discovery failed at path {}".format(current_path))
return flattenTestSuite(suite) if suite.countTestCases() else None
# Add debug logging for stuff that happened before this point here
if config.files_loaded:
debug("Loaded config file(s): {}".format(
', '.join(config.files_loaded)))
# Discover/Load the test suite
if testing:
test_suite = None
else: # pragma: no cover
loader = GreenTestLoader()
test_suite = loader.loadTargets(args.targets,
file_pattern=args.file_pattern)
# We didn't even load 0 tests...
if not test_suite:
debug(
"No test loading attempts succeeded. Created an empty test suite.")
test_suite = GreenTestSuite()
# Actually run the test_suite
result = run(test_suite, stream, args, testing)
# Generate a test report if required
if args.junit_report:
from green.junit import JUnitXML
adapter = JUnitXML()
with open(args.junit_report, "w") as report_file:
adapter.save_as(result, report_file)
return(int(not result.wasSuccessful()))