def test_loadTestsFromName__function_with_different_name_than_method(self):
# lambdas have the name '<lambda>'.
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
test = lambda: 1
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['testcase_1.test'], m)
self.assertIsInstance(suite, loader.suiteClass)
ref_suite = unittest.TestSuite([MyTestCase('test')])
self.assertEqual(list(suite), [ref_suite])
# "The specifier name is a ``dotted name'' that may resolve ... to ... a
# test method within a test case class"
#
# Does the method gracefully handle names that initially look like they
# resolve to "a test method within a test case class" but don't?
python类TestSuite()的实例源码
def test_loadTestsFromNames__relative_invalid_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest2.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['testcase_1.testfoo'], m)
error, test = self.check_deferred_error(loader, list(suite)[0])
expected = "type object 'MyTestCase' has no attribute 'testfoo'"
self.assertIn(
expected, error,
'missing error string in %r' % error)
self.assertRaisesRegex(AttributeError, expected, test.testfoo)
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a ... TestSuite instance"
def test_loadTestsFromNames__callable__TestSuite(self):
m = types.ModuleType('m')
testcase_1 = unittest2.FunctionTestCase(lambda: None)
testcase_2 = unittest2.FunctionTestCase(lambda: None)
def return_TestSuite():
return unittest2.TestSuite([testcase_1, testcase_2])
m.return_TestSuite = return_TestSuite
loader = unittest2.TestLoader()
suite = loader.loadTestsFromNames(['return_TestSuite'], m)
self.assertIsInstance(suite, loader.suiteClass)
expected = unittest2.TestSuite([testcase_1, testcase_2])
self.assertEqual(list(suite), [expected])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase ... instance"
def test_loadTestsFromNames__callable__call_staticmethod(self):
m = types.ModuleType('m')
class Test1(unittest2.TestCase):
def test(self):
pass
testcase_1 = Test1('test')
class Foo(unittest2.TestCase):
@staticmethod
def foo():
return testcase_1
m.Foo = Foo
loader = unittest2.TestLoader()
suite = loader.loadTestsFromNames(['Foo.foo'], m)
self.assertIsInstance(suite, loader.suiteClass)
ref_suite = unittest2.TestSuite([testcase_1])
self.assertEqual(list(suite), [ref_suite])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase or TestSuite instance"
#
# What happens when the callable returns something else?
def test_testMethodPrefix__loadTestsFromTestCase(self):
class Foo(unittest2.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
tests_1 = unittest2.TestSuite([Foo('foo_bar')])
tests_2 = unittest2.TestSuite([Foo('test_1'), Foo('test_2')])
loader = unittest2.TestLoader()
loader.testMethodPrefix = 'foo'
self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
loader.testMethodPrefix = 'test'
self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
# "String giving the prefix of method names which will be interpreted as
# test methods"
#
# Implicit in the documentation is that testMethodPrefix is respected by
# all loadTestsFrom* methods.
def test_testMethodPrefix__loadTestsFromModule(self):
m = types.ModuleType('m')
class Foo(unittest2.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests_1 = [unittest2.TestSuite([Foo('foo_bar')])]
tests_2 = [unittest2.TestSuite([Foo('test_1'), Foo('test_2')])]
loader = unittest2.TestLoader()
loader.testMethodPrefix = 'foo'
self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
loader.testMethodPrefix = 'test'
self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
# "String giving the prefix of method names which will be interpreted as
# test methods"
#
# Implicit in the documentation is that testMethodPrefix is respected by
# all loadTestsFrom* methods.
def test_testMethodPrefix__loadTestsFromName(self):
m = types.ModuleType('m')
class Foo(unittest2.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests_1 = unittest2.TestSuite([Foo('foo_bar')])
tests_2 = unittest2.TestSuite([Foo('test_1'), Foo('test_2')])
loader = unittest2.TestLoader()
loader.testMethodPrefix = 'foo'
self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
loader.testMethodPrefix = 'test'
self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
# "String giving the prefix of method names which will be interpreted as
# test methods"
#
# Implicit in the documentation is that testMethodPrefix is respected by
# all loadTestsFrom* methods.
def loadTests(self, namespace):
"""
Load L{csb.test.Case}s from the given CSB C{namespace}. If the namespace
ends with a wildcard, tests from sub-packages will be loaded as well.
If the namespace is '__main__' or '.', tests are loaded from __main__.
@param namespace: test module namespace, e.g. 'csb.test.cases.bio' will
load tests from '/csb/test/cases/bio/__init__.py'
@type namespace: str
@return: a C{unittest.TestSuite} ready for the test runner
@rtype: C{unittest.TestSuite}
"""
if namespace.strip() == '.*':
namespace = '__main__.*'
elif namespace.strip() == '.':
namespace = '__main__'
if namespace.endswith('.*'):
return self.loadAllTests(namespace[:-2])
else:
loader = unittest.TestLoader()
tests = loader.loadTestsFromName(namespace)
return unittest.TestSuite(self._filter(tests))
def loadMultipleTests(self, namespaces):
"""
Load L{csb.test.Case}s from a list of given CSB C{namespaces}.
@param namespaces: a list of test module namespaces, e.g.
('csb.test.cases.bio', 'csb.test.cases.bio.io') will
load tests from '/csb/test/cases/bio.py' and
'/csb/test/cases/bio/io.py'
@type namespaces: tuple of str
@return: a C{unittest.TestSuite} ready for the test runner
@rtype: C{unittest.TestSuite}
"""
if not csb.core.iterable(namespaces):
raise TypeError(namespaces)
return unittest.TestSuite(self.loadTests(n) for n in namespaces)
def loadTests(self, namespace):
if namespace.strip() == '.*':
namespace = '__main__.*'
elif namespace.strip() == '.':
namespace = '__main__'
if namespace.endswith('.*'):
return self.loadAllTests(namespace[:-2])
else:
try:
mod = __import__(namespace, fromlist=[''])
except ImportError:
raise InvalidNamespaceError('Namespace {0} is not importable'.format(namespace))
suites = self._inspect(mod)
return unittest.TestSuite(suites)
def _filter(self, factories):
"""
Filter a list of objects using C{self.labels}.
"""
filtered = []
for obj in factories:
for label in self.labels:
if hasattr(obj, label) and getattr(obj, label) is True:
suite = obj()
if not isinstance(suite, unittest.TestSuite):
raise ValueError('Custom test function {0} must return a '
'unittest.TestSuite, not {1}'.format(obj.__name__, type(suite)))
filtered.append(suite)
return filtered
def custom(function):
"""
A function decorator, used to mark functions which build custom (dynamic)
test suites when called.
@param function: a callable object, which returns a dynamically compiled
C{unittest.TestSuite}
@type function: callable
"""
if isinstance(function, type):
raise TypeError("Can't apply function decorator on a class")
elif not hasattr(function, '__call__'):
raise TypeError("Can't apply function decorator on non-callable {0}".format(type(function)))
setattr(function, Attributes.CUSTOM, True)
return function
def exclude_tests(suite, blacklist):
"""
Example:
blacklist = [
'test_some_test_that_should_be_skipped',
'test_another_test_that_should_be_skipped'
]
"""
new_suite = unittest.TestSuite()
for test_group in suite._tests:
for test in test_group:
if not hasattr(test, '_tests'):
# e.g. ModuleImportFailure
new_suite.addTest(test)
continue
for subtest in test._tests:
method = subtest._testMethodName
if method in blacklist:
setattr(test,
method,
getattr(SkipCase(), 'skeleton_run_test'))
new_suite.addTest(test)
return new_suite
def _run_suite(suite):
"""Run tests from a unittest.TestSuite-derived class."""
if verbose:
runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
failfast=failfast)
else:
runner = BasicTestRunner()
result = runner.run(suite)
if not result.wasSuccessful():
if len(result.errors) == 1 and not result.failures:
err = result.errors[0][1]
elif len(result.failures) == 1 and not result.errors:
err = result.failures[0][1]
else:
err = "multiple errors occurred"
if not verbose: err += "; run in verbose mode for details"
raise TestFailed(err)
def _run_suite(suite):
"""Run tests from a unittest.TestSuite-derived class."""
if verbose:
runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
failfast=failfast)
else:
runner = BasicTestRunner()
result = runner.run(suite)
if not result.wasSuccessful():
if len(result.errors) == 1 and not result.failures:
err = result.errors[0][1]
elif len(result.failures) == 1 and not result.errors:
err = result.failures[0][1]
else:
err = "multiple errors occurred"
if not verbose: err += "; run in verbose mode for details"
raise TestFailed(err)
def _run_suite(suite):
"""Run tests from a unittest.TestSuite-derived class."""
if verbose:
runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
failfast=failfast)
else:
runner = BasicTestRunner()
result = runner.run(suite)
if not result.wasSuccessful():
if len(result.errors) == 1 and not result.failures:
err = result.errors[0][1]
elif len(result.failures) == 1 and not result.errors:
err = result.failures[0][1]
else:
err = "multiple errors occurred"
if not verbose: err += "; run in verbose mode for details"
raise TestFailed(err)
def _run_suite(suite):
"""Run tests from a unittest.TestSuite-derived class."""
if verbose:
runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
failfast=failfast)
else:
runner = BasicTestRunner()
result = runner.run(suite)
if not result.wasSuccessful():
if len(result.errors) == 1 and not result.failures:
err = result.errors[0][1]
elif len(result.failures) == 1 and not result.errors:
err = result.failures[0][1]
else:
err = "multiple errors occurred"
if not verbose: err += "; run in verbose mode for details"
raise TestFailed(err)
def suite():
"""The global test suite.
"""
logging.basicConfig(level=logging.DEBUG)
mysuite = unittest.TestSuite()
mysuite.addTests(test_scene.suite())
mysuite.addTests(test_dataset.suite())
mysuite.addTests(test_writers.suite())
mysuite.addTests(test_readers.suite())
mysuite.addTests(test_resample.suite())
mysuite.addTests(test_yaml_reader.suite())
mysuite.addTests(test_helper_functions.suite())
mysuite.addTests(reader_tests.suite())
mysuite.addTests(writer_tests.suite())
mysuite.addTests(test_file_handlers.suite())
mysuite.addTests(test_utils.suite())
mysuite.addTests(test_enhancements.suite())
return mysuite
def _run_suite(suite):
"""Run tests from a unittest.TestSuite-derived class."""
if verbose:
runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
failfast=failfast)
else:
runner = BasicTestRunner()
result = runner.run(suite)
if not result.wasSuccessful():
if len(result.errors) == 1 and not result.failures:
err = result.errors[0][1]
elif len(result.failures) == 1 and not result.errors:
err = result.failures[0][1]
else:
err = "multiple errors occurred"
if not verbose: err += "; run in verbose mode for details"
raise TestFailed(err)
def _run_suite(suite):
"""Run tests from a unittest.TestSuite-derived class."""
if verbose:
runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
failfast=failfast)
else:
runner = BasicTestRunner()
result = runner.run(suite)
if not result.wasSuccessful():
if len(result.errors) == 1 and not result.failures:
err = result.errors[0][1]
elif len(result.failures) == 1 and not result.errors:
err = result.failures[0][1]
else:
err = "multiple errors occurred"
if not verbose: err += "; run in verbose mode for details"
raise TestFailed(err)