Add tests for error_callback

This commit is contained in:
Martin Pool
2011-06-01 16:46:29 +10:00
parent fd74e35582
commit ad5396ee06

View File

@@ -1,4 +1,4 @@
# Copyright (c) 2010 testtools developers. See LICENSE for details.
# Copyright (c) 2010-2011 testtools developers. See LICENSE for details.
from testtools import TestCase
from testtools.helpers import (
@@ -8,7 +8,35 @@ from testtools.helpers import (
from testtools.matchers import (
Equals,
Is,
Not,
)
def check_error_callback(test, function, arg, expected_error_count,
expect_result):
"""General test template for error_callback argument.
:param test: Test case instance.
:param function: Either try_import or try_imports.
:param arg: Name or names to import.
:param expected_error_count: Expected number of calls to the callback.
:param expect_result: Boolean for whether a module should
ultimately be returned or not.
"""
cb_calls = []
def cb(e):
test.assertIsInstance(e, ImportError)
cb_calls.append(e)
try:
result = function(arg, error_callback=cb)
except ImportError, e:
test.assertFalse(expect_result)
else:
if expect_result:
test.assertThat(result, Not(Is(None)))
else:
test.assertThat(result, Is(None))
test.assertEquals(len(cb_calls), expected_error_count)
class TestTryImport(TestCase):
@@ -51,7 +79,20 @@ class TestTryImport(TestCase):
result = try_import('os.path.join')
import os
self.assertThat(result, Is(os.path.join))
def test_error_callback(self):
# the error callback is called on failures.
check_error_callback(self, try_import, 'doesntexist', 1, False)
def test_error_callback_missing_module_member(self):
# the error callback is called on failures to find an object
# inside an existing module.
check_error_callback(self, try_import, 'os.nonexistent', 1, False)
def test_error_callback_not_on_success(self):
# the error callback is not called on success.
check_error_callback(self, try_import, 'os.path', 0, True)
class TestTryImports(TestCase):
@@ -99,6 +140,18 @@ class TestTryImports(TestCase):
result = try_imports(['os.doesntexist', 'os.path'])
import os
self.assertThat(result, Is(os.path))
def test_error_callback(self):
# One error for every class that doesn't exist.
check_error_callback(self, try_imports,
['os.doesntexist', 'os.notthiseither'],
2, False)
check_error_callback(self, try_imports,
['os.doesntexist', 'os.notthiseither', 'os'],
2, True)
check_error_callback(self, try_imports,
['os.path'],
0, True)
def test_suite():