diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst --- a/Doc/library/unittest.rst +++ b/Doc/library/unittest.rst @@ -223,6 +223,22 @@ Stop the test run on the first error or failure. +.. cmdoption:: -u, --use= + + Manage the use of the resources named in *resourcelist*. *resourcelist* is + a comma-separated list of resource names to enable or disable. Names + starting with ``-`` are disabled, all others are enabled. Both ``+`` and + ``-`` are removed from the beginning of names before use, so ``+`` may be + used for explicitly enabling a resources. ``all`` is a special value which + will enable or disable all registered resources. As *resourcelist* is + evaluated from left to right, use of ``all`` only makes sense at the + beginning of the list. + + See :ref:`unittest_resources` below. + +.. versionadded:: 3.4 + The command-line option ``-u`` was added. + .. versionadded:: 3.2 The command-line options ``-b``, ``-c`` and ``-f`` were added. @@ -563,6 +579,98 @@ Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run. +.. _unittest_resources: + +Managing execution of resource-intensive tests +---------------------------------------------- + +.. versionadded:: 3.4 + +Some tests are impossible to write without using some resource that is either +scarce, unreliable, or just annoying---like disk space, network connectivity, +or a GUI environment. To guard tests that use such resources, unittest +provides the :func:`require` function and :func:`requires` decorator. + +.. function:: require(resource) + + Check whether the given resource is enabled and available, skip the test if + not. If the given resource is not registered, a :exc:`ResourceError` is + raised, which will cause the test to fail. + +.. decorator:: requires(resource) + + A decorator form of :func:`require`. This decorator can be applied to + classes or methods---anywhere the :func:`skip` decorator can be used. + +Before a resource can be required, it must be registered. + +.. function:: registerResource(name, checker=True) + + Register the resource *name*. If supplied, *checker* should be a boolean + value or a function that takes no arguments and returns such a value. The + first time the resource is required, *checker* will be called to determine + whether the resource is available. Subsequent checks use the cached value + from the first check. + +Three exceptions are used to implement resource management: + +.. exception:: ResourceDenied + + Raised when a required resource has not been enabled. If unhandled, this + exception will cause a test to be marked as skipped when raised. + +.. exception:: ResourceUnavailable + + Raised when a required resource is not available, as determined by the + resource's checker function. Like :exc:`ResourceDenied`, this exception + will mark a test as skipped. + +.. exception:: ResourceError + + Raised when a required resource has not been registered. This exception + will cause the currently executing test to fail. + +Some common resources are already registered by unittest. These are: + + - *audio* -- intended to be used for tests which may emit sound from the + computer's speakers + - *cpu* -- intended for tests which are expected to take a lot of + processing power. + - *filesystem* -- use this resource for tests which need access to the + filesystem. A temporary file is written (and deleted) to ensure access + before allowing use. + - *gui* -- intended for tests which require a GUI environment to be + available. + - *largefile* -- this resource is meant for tests which may need to write + multi-gigabyte files, which can take a very long time on some platforms + and may be impossible on others. + - *memory* -- useful for tests which may consume large quantities of memory. + - *network* -- for tests that require network access. + +A toy example:: + + def weather_checker(): + if sky_color == 'blue': + return True + return False + + unittest.registerResource('sun', weather_checker) + + @unittest.requires('cpu') + class ExpensiveTest(unittest.TestCase): + @unittest.requires('sun') + @unittest.requires('filesystem') + def test_writer(self): + if not sys.platform == 'win32': + unittest.require('gui') + write_to_disk() + self.assertEqual(sizeof_file(), expected_size) + +In this example, the test will only run if cpu-intensive tests are enabled, +the sun is out (for some reason), and the filesystem can be written to. Also, +if not running on Windows, the test must be allowed to use a GUI environment. + + .. _subtests: Distinguishing test iterations using subtests @@ -1890,7 +1998,8 @@ .. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \ testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, \ - failfast=None, catchbreak=None, buffer=None, warnings=None) + failfast=None, catchbreak=None, buffer=None, use=None, \ + warnings=None) A command-line program that loads a set of tests from *module* and runs them; this is primarily for making test modules conveniently executable. @@ -1924,7 +2033,7 @@ >>> from unittest import main >>> main(module='test_module', exit=False) - The *failfast*, *catchbreak* and *buffer* parameters have the same + The *failfast*, *catchbreak*, *buffer*, and *use* parameters have the same effect as the same-name `command-line options`_. The *warning* argument specifies the :ref:`warning filter ` @@ -1946,6 +2055,9 @@ The *defaultTest* parameter was changed to also accept an iterable of test names. + .. versionchanged:: 3.4 + The *use* parameter was added. + load_tests Protocol ################### diff --git a/Lib/unittest/__init__.py b/Lib/unittest/__init__.py --- a/Lib/unittest/__init__.py +++ b/Lib/unittest/__init__.py @@ -48,7 +48,9 @@ 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', 'expectedFailure', 'TextTestResult', 'installHandler', - 'registerResult', 'removeResult', 'removeHandler'] + 'registerResult', 'removeResult', 'removeHandler', + 'ResourceError', 'ResourceDenied', 'ResourceUnavailable', + 'registerResource', 'require', 'requires'] # Expose obsolete functions for backwards compatibility __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) @@ -62,6 +64,8 @@ from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames, findTestCases) from .main import TestProgram, main +from .resources import (ResourceUnavailable, ResourceDenied, ResourceError, + registerResource, require, requires) from .runner import TextTestRunner, TextTestResult from .signals import installHandler, registerResult, removeResult, removeHandler diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -10,8 +10,9 @@ import contextlib from . import result +from .resources import _do_check from .util import (strclass, safe_repr, _count_diff_all_purpose, - _count_diff_hashable) + _count_diff_hashable, _BaseSkip) __unittest = True @@ -19,7 +20,7 @@ DIFF_OMITTED = ('\nDiff is %s characters long. ' 'Set self.maxDiff to None to see it.') -class SkipTest(Exception): +class SkipTest(_BaseSkip): """ Raise this exception in a test to skip it. @@ -56,7 +57,7 @@ yield except KeyboardInterrupt: raise - except SkipTest as e: + except _BaseSkip as e: self.success = False self.skipped.append((test_case, str(e))) except _ShouldStop: @@ -472,12 +473,24 @@ result.startTest(self) testMethod = getattr(self, self._testMethodName) - if (getattr(self.__class__, "__unittest_skip__", False) or + class_resources = getattr(self.__class__, + '__unittest_check_resources__', + []) + resource_message = _do_check(self.__class__, class_resources) + if not resource_message: + method_resources = getattr(testMethod, + '__unittest_check_resources__', + []) + resource_message = _do_check(testMethod, method_resources) + if (resource_message or + getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False)): # If the class or method was skipped. try: - skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') - or getattr(testMethod, '__unittest_skip_why__', '')) + skip_why = ( + resource_message or + getattr(self.__class__, '__unittest_skip_why__', '') or + getattr(testMethod, '__unittest_skip_why__', '')) self._addSkip(result, self, skip_why) finally: result.stopTest(self) diff --git a/Lib/unittest/loader.py b/Lib/unittest/loader.py --- a/Lib/unittest/loader.py +++ b/Lib/unittest/loader.py @@ -270,7 +270,7 @@ name = self._get_name_from_path(full_path) try: module = self._get_module_from_name(name) - except case.SkipTest as e: + except util._BaseSkip as e: yield _make_skipped_test(name, e, self.suiteClass) except: yield _make_failed_import_test(name, self.suiteClass) diff --git a/Lib/unittest/main.py b/Lib/unittest/main.py --- a/Lib/unittest/main.py +++ b/Lib/unittest/main.py @@ -4,7 +4,7 @@ import optparse import os -from . import loader, runner +from . import loader, runner, resources from .signals import installHandler __unittest = True @@ -20,7 +20,13 @@ -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output -%(failfast)s%(catchbreak)s%(buffer)s +%(failfast)s%(catchbreak)s%(buffer)s\ + -u, --use names Enable or disable tests using the named resources. + "names" must be a comma-separated list of names, + optionally starting with '-', which will disable that + resource. You may also specify "all" to enable/disable + all registered resources. E.g. "-u cpu,-filesystem,audio" + Examples: %(progName)s test_module - run tests from test_module %(progName)s module.TestClass - run tests from module.TestClass @@ -33,7 +39,9 @@ Options: -v, --verbose Verbose output -%(failfast)s%(catchbreak)s%(buffer)s -s directory Directory to start discovery ('.' default) +%(failfast)s%(catchbreak)s%(buffer)s\ + -u, --use names As above. + -s directory Directory to start discovery ('.' default) -p pattern Pattern to match test files ('test*.py' default) -t directory Top level directory of project (default to start directory) @@ -49,7 +57,13 @@ -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output -%(failfast)s%(catchbreak)s%(buffer)s +%(failfast)s%(catchbreak)s%(buffer)s\ + -u, --use names Enable or disable tests using the named resources. + "names" must be a comma-separated list of names, + optionally starting with '-', which will disable that + resource. You may also specify "all" to enable/disable + all registered resources. E.g. "-u cpu,-filesystem,audio" + Examples: %(progName)s - run default set of tests %(progName)s MyTestSuite - run suite 'MyTestSuite' @@ -85,12 +99,12 @@ USAGE = USAGE_FROM_MODULE # defaults for testing - failfast = catchbreak = buffer = progName = warnings = None + failfast = catchbreak = buffer = progName = use = warnings = None def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, - buffer=None, warnings=None): + buffer=None, use=None, warnings=None): if isinstance(module, str): self.module = __import__(module) for part in module.split('.')[1:]: @@ -105,6 +119,7 @@ self.catchbreak = catchbreak self.verbosity = verbosity self.buffer = buffer + self.use = use if warnings is None and not sys.warnoptions: # even if DreprecationWarnings are ignored by default # print them anyway unless other warnings settings are @@ -124,6 +139,17 @@ self.parseArgs(argv) self.runTests() + def _handleResources(self): + names = self.use.split(',') + for name in names: + first = name[0] + if first in '+-': + name = name[1:] + if first == '-': + resources._disableResource(name) + else: + resources._enableResource(name) + def usageExit(self, msg=None): if msg: print(msg) @@ -185,6 +211,8 @@ help='Verbose output', action='store_true') parser.add_option('-q', '--quiet', dest='quiet', default=False, help='Quiet output', action='store_true') + parser.add_option('-u', '--use', dest='use', default=None, + help='Manage the use of resources') if self.failfast != False: parser.add_option('-f', '--failfast', dest='failfast', default=False, @@ -209,6 +237,10 @@ self.catchbreak = options.catchbreak if self.buffer is None: self.buffer = options.buffer + if self.use is None: + self.use = options.use + if self.use is not None: + self._handleResources() if options.verbose: self.verbosity = 2 diff --git a/Lib/unittest/resources.py b/Lib/unittest/resources.py new file mode 100644 --- /dev/null +++ b/Lib/unittest/resources.py @@ -0,0 +1,166 @@ +"""Resource Guarding""" + +__unittest = True + +from functools import wraps +from .util import _BaseSkip + +class ResourceError(Exception): pass + +class ResourceUnavailable(_BaseSkip): pass + +UNAVAILABLE = '{} resource is unavailable' + +class ResourceDenied(ResourceUnavailable): pass + +NOT_ENABLED = '{} resource is not enabled' + +# Empty defaults + +_resources = {} +_enabled_resources = set() +_disabled_resources = set() + +def _enabled(resource): + if resource in _disabled_resources: + return False + if 'all' in _enabled_resources: + return True + return resource in _enabled_resources + +def _available(resource): + try: + checker = _resources[resource] + except KeyError: + msg = 'Resource {!r} is not registered'.format(resource) + raise ResourceError(msg) from None + + if checker in (True, False): + return checker + + _resources[resource] = checker() + return _resources[resource] + +def _enableResource(name): + """ + Declare that the named resource is permissible to use. + """ + if name == 'all': + _disabled_resources.clear() + + _enabled_resources.add(name) + try: + _disabled_resources.remove(name) + except KeyError: + pass + +def _disableResource(name): + """ + Disallow the use of the named resource. + """ + if name == 'all': + _enabled_resources.clear() + return + + _disabled_resources.add(name) + try: + _enabled_resources.remove(name) + except KeyError: + pass + +def _do_check(test_item, to_check): + for resource in to_check: + try: + require(resource) + except ResourceUnavailable as e: + return str(e) + return '' + + + +def require(resource): + """ + Check if the given resource is available. If available, return. + Otherwise, raise an appropriate exception. + """ + if not _enabled(resource): + raise ResourceDenied(NOT_ENABLED.format(resource)) + if not _available(resource): + raise ResourceUnavailable(UNAVAILABLE.format(resource)) + +def requires(resource): + """ + Decorator factory for requiring a resource. + """ + def decorator(test_item): + if not isinstance(test_item, type): + func = test_item + @wraps(test_item) + def require_wrapper(*args, **kwargs): + require(resource) + func(*args, **kwargs) + test_item = require_wrapper + + to_check = getattr(test_item, '__unittest_check_resources__', []) + to_check.append(resource) + test_item.__unittest_check_resources__ = to_check + return test_item + return decorator + +def registerResource(name, checker=True): + """ + Register resource 'name' and checker function for future availability + checking. 'checker' should be a bool or a function returning a bool, + which will be called once when availability is checked for the first time. + """ + _resources[name] = checker + + +# Default resource checkers + +def _filesystem_available(): + # test to see if we can write to the filesystem + import tempfile + try: + with tempfile.NamedTemporaryFile() as f: + f.write(b'Please delete this file.') + f.flush() + except OSError: + return False + else: + return True + +def _largefile_ops_available(): + import sys + import tempfile + if sys.platform[:3] == 'win' or sys.platform == 'darwin': + return True # Windows and OSX can handle large files by default + else: # Not all filesystems can + try: + with tempfile.NamedTemporaryFile(buffering=0) as f: + # 2**31 == 2147483648 + f.seek(2147483649) + # Seeking is not enough: you must write and flush, too! + f.write(b'Please delete this file.') + f.flush() + except (OSError, OverflowError): + return False + else: + return True + +# Default resources +for r in (['audio'], + ['cpu'], + ['filesystem', _filesystem_available], + ['gui'], + ['largefile', _largefile_ops_available], + ['memory'], + ['network'], + ['urlfetch'] + ): + registerResource(*r) + +# Resources enabled by default +for r in ['filesystem', + ]: + _enableResource(r) diff --git a/Lib/unittest/test/test_program.py b/Lib/unittest/test/test_program.py --- a/Lib/unittest/test/test_program.py +++ b/Lib/unittest/test/test_program.py @@ -201,6 +201,47 @@ program.parseArgs([None, opt]) self.assertEqual(getattr(program, attr), not_none) + def testUse(self): + r = unittest.resources + saved_enabled = r._enabled_resources.copy() + saved_disabled = r._disabled_resources.copy() + def cleanup(): + r._enabled_resources.clear() + r._enabled_resources.update(saved_enabled) + r._disabled_resources.clear() + r._disabled_resources.update(saved_disabled) + + self.addCleanup(cleanup) + + program = self.program + + def _parse_and_reset(arg_string): + args = [None] + args.extend(arg_string.split()) + program.parseArgs(args) + setattr(program, 'use', None) + + _parse_and_reset('-u-all') + self.assertFalse(r._enabled_resources) + + _parse_and_reset('--use all') + self.assertIn('all', r._enabled_resources) + bogus = 'booga booga' + self.assertTrue(r._enabled(bogus)) + with self.assertRaises(unittest.ResourceError): + unittest.require(bogus) + + r._disableResource('all') + _parse_and_reset('-ucpu,-filesystem,audio') + self.assertEqual(r._enabled_resources, {'cpu', 'audio'}) + + r._disableResource('all') + _parse_and_reset('--use all,-cpu,-audio') + for res in ['cpu', 'audio']: + with self.assertRaises(unittest.ResourceDenied): + unittest.require(res) + self.assertTrue(r._enabled('bogus')) + def testWarning(self): """Test the warnings argument""" # see #10535 diff --git a/Lib/unittest/test/test_resources.py b/Lib/unittest/test/test_resources.py new file mode 100644 --- /dev/null +++ b/Lib/unittest/test/test_resources.py @@ -0,0 +1,310 @@ +import unittest + +from .support import LoggingResult +from unittest import resources + +BOGUS_NOT_ENABLED = resources.NOT_ENABLED.format('bogus') +BOGUS_UNAVAILABLE = resources.UNAVAILABLE.format('bogus') + +def clear_resources(): + resources._enabled_resources.clear() + resources._disabled_resources.clear() + +class TestResources(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.saved_resources = resources._resources.copy() + cls.saved_enabled = resources._enabled_resources.copy() + cls.saved_disabled = resources._disabled_resources.copy() + + def setUp(self): + # clear resources before each test + clear_resources() + # reset 'bogus' to default + unittest.registerResource('bogus') + + @classmethod + def tearDownClass(cls): + clear_resources() + resources._enabled_resources.update(cls.saved_enabled) + resources._disabled_resources.update(cls.saved_disabled) + resources._resources.clear() + resources._resources.update(cls.saved_resources) + assert resources._enabled_resources == cls.saved_enabled + assert resources._disabled_resources == cls.saved_disabled + assert resources._resources == cls.saved_resources + + def test_require(self): + class Foo(unittest.TestCase): + def test_need_bogus(self): + unittest.require('bogus') + events = [] + result = LoggingResult(events) + test = Foo("test_need_bogus") + test.run(result) + self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) + self.assertEqual(result.skipped, [(test, BOGUS_NOT_ENABLED)]) + + resources._enableResource('bogus') + + events = [] + result = LoggingResult(events) + test.run(result) + self.assertEqual(events, ['startTest', 'addSuccess', 'stopTest']) + self.assertEqual(result.skipped, []) + + unittest.registerResource('bogus', False) + + events = [] + result = LoggingResult(events) + test.run(result) + self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) + self.assertEqual(result.skipped, [(test, BOGUS_UNAVAILABLE)]) + + unittest.registerResource('bogus') + + resources._disableResource('bogus') + # let setUp make the requirement + class Foo(unittest.TestCase): + def setUp(self): + unittest.require('bogus') + def test_nothing(self): pass + events = [] + result = LoggingResult(events) + test = Foo("test_nothing") + test.run(result) + self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) + self.assertEqual(result.skipped, [(test, BOGUS_NOT_ENABLED)]) + self.assertEqual(result.testsRun, 1) + + resources._enableResource('bogus') + + events = [] + result = LoggingResult(events) + test = Foo("test_nothing") + test.run(result) + self.assertEqual(events, ['startTest', 'addSuccess', 'stopTest']) + self.assertEqual(result.skipped, []) + + unittest.registerResource('bogus', False) + + events = [] + result = LoggingResult(events) + test.run(result) + self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) + self.assertEqual(result.skipped, [(test, BOGUS_UNAVAILABLE)]) + + + def test_requires(self): + class Foo(unittest.TestCase): + @unittest.requires('bogus') + def test_require_bogus(self): pass + + test = Foo('test_require_bogus') + events = [] + result = LoggingResult(events) + test.run(result) + self.assertEqual(len(result.skipped), 1) + self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) + self.assertEqual(result.skipped, [(test, BOGUS_NOT_ENABLED)]) + self.assertTrue(result.wasSuccessful()) + + resources._enableResource('bogus') + + events = [] + result = LoggingResult(events) + test.run(result) + self.assertEqual(len(result.skipped), 0) + self.assertEqual(events, ['startTest', 'addSuccess', 'stopTest']) + self.assertEqual(result.testsRun, 1) + self.assertTrue(result.wasSuccessful()) + + + def test_requires_on_class(self): + resources._enableResource('bogus') + + @unittest.requires('bogus') + class Foo(unittest.TestCase): + def test_1(self): + record.append(1) + record = [] + result = unittest.TestResult() + test = Foo("test_1") + suite = unittest.TestSuite([test]) + suite.run(result) + self.assertEqual(len(result.skipped), 0) + self.assertEqual(record, [1]) + + + resources._disableResource('bogus') + record = [] + result = unittest.TestResult() + suite.run(result) + self.assertEqual(result.skipped, [(test, BOGUS_NOT_ENABLED)]) + self.assertEqual(record, []) + + + def test_requires_on_non_unittest_class(self): + @unittest.requires("bogus") + class Mixin: + def test_1(self): + record.append(1) + class Foo(Mixin, unittest.TestCase): + pass + record = [] + result = unittest.TestResult() + test = Foo("test_1") + suite = unittest.TestSuite([test]) + suite.run(result) + self.assertEqual(result.skipped, [(test, BOGUS_NOT_ENABLED)]) + self.assertEqual(record, []) + + + def test_requires_doesnt_run_setup(self): + class Foo(unittest.TestCase): + wasSetUp = False + wasTornDown = False + def setUp(self): + Foo.wasSetUp = True + def tornDown(self): + Foo.wasTornDown = True + @unittest.requires('bogus') + def test_1(self): + pass + + result = unittest.TestResult() + test = Foo("test_1") + suite = unittest.TestSuite([test]) + suite.run(result) + self.assertEqual(result.skipped, [(test, BOGUS_NOT_ENABLED)]) + self.assertFalse(Foo.wasSetUp) + self.assertFalse(Foo.wasTornDown) + + + def test_requires_decorated(self): + def decorator(func): + def inner(*a): + return func(*a) + return inner + + class Foo(unittest.TestCase): + @decorator + @unittest.requires('bogus') + def test_1(self): + pass + + result = unittest.TestResult() + test = Foo("test_1") + suite = unittest.TestSuite([test]) + suite.run(result) + self.assertEqual(result.skipped, [(test, BOGUS_NOT_ENABLED)]) + + + def test_multiple_requires(self): + checkers_called = [] + def bogus1(): + checkers_called.append('bogus1') + return True + def bogus2(): + checkers_called.append('bogus2') + return True + def bogus3(): + checkers_called.append('bogus3') + return True + + unittest.registerResource('bogus1', bogus1) + unittest.registerResource('bogus2', bogus2) + unittest.registerResource('bogus3', bogus3) + resources._enableResource('all') + test_run = [] + class Foo(unittest.TestCase): + @unittest.requires('bogus1') + @unittest.requires('bogus2') + @unittest.requires('bogus3') + def test_requires_a_lot(self): + test_run.append(True) + + result = unittest.TestResult() + test = Foo('test_requires_a_lot') + test.run(result) + self.assertEqual(sorted(checkers_called), + sorted(['bogus1', 'bogus2', 'bogus3'])) + self.assertTrue(test_run) + + resources._disableResource('all') + + result = unittest.TestResult() + test.run(result) + self.assertEqual(len(result.skipped), 1) + + + def test_checking(self): + bc_args = [] + bc_kwargs = [] + bc_called = [] + test_run = [] + def bogus_checker(*args, **kwargs): + if args: + bc_args.append(args) + if kwargs: + bc_kwargs.append(kwargs) + bc_called.append(True) + return True + unittest.registerResource('bogus', bogus_checker) + resources._enableResource('bogus') + + class Foo(unittest.TestCase): + @unittest.requires('bogus') + def test_bogus(self): + test_run.append(True) + + result = unittest.TestResult() + test = Foo("test_bogus") + + test.run(result) + self.assertTrue(bc_called, "checker should have been called") + self.assertFalse(bc_args and bc_kwargs, + "checker should not be given arguments") + self.assertTrue(test_run, "test should have run") + + bc_called = [] + test_run = [] + + test.run(result) + self.assertTrue(test_run) + # bogus is disabled, checker shouldn't be called unless enabled + self.assertFalse(bc_called, + "checker shouldn't be called twice") + + unittest.registerResource('bogus', bogus_checker) + resources._disableResource('bogus') + + bc_called = [] + test_run = [] + + test.run(result) + self.assertFalse(bc_called, + "checker shouldn't be called with resource disabled") + self.assertFalse(test_run, + "test should not have run with resource disabled") + + + def test_bad_resource_name(self): + resources._enableResource('blarg') + self.assertRaises(unittest.ResourceError, unittest.require, 'blarg') + + + +class TestResourceCheckers(unittest.TestCase): + @unittest.requires('filesystem') + def test_filesystem_checker(self): + """ + If TestResources.test_checking passes, this test isn't improperly + skipped, and the requires call didn't blow up, we're good. + """ + + @unittest.requires('largefile') + def test_largefile_checker(self): + """ + Same as test_filesystem_checker. + """ diff --git a/Lib/unittest/util.py b/Lib/unittest/util.py --- a/Lib/unittest/util.py +++ b/Lib/unittest/util.py @@ -4,6 +4,11 @@ __unittest = True +class _BaseSkip(Exception): + """ + Base skipping exception, subclassed by SkipTest and the resource skips. + """ + _MAX_LENGTH = 80 def safe_repr(obj, short=False): try: