From ad5396ee066bb11553c8686b51821832ea55dd10 Mon Sep 17 00:00:00 2001 From: Martin Pool Date: Wed, 1 Jun 2011 16:46:29 +1000 Subject: [PATCH] Add tests for error_callback --- testtools/tests/test_helpers.py | 55 ++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/testtools/tests/test_helpers.py b/testtools/tests/test_helpers.py index 94f5686..83ae367 100644 --- a/testtools/tests/test_helpers.py +++ b/testtools/tests/test_helpers.py @@ -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():