1 # Copyright (c) 2010 Jonathan M. Lange. See LICENSE for details.
3 from testtools import TestCase
4 from testtools.helpers import (
8 from testtools.matchers import (
14 class TestTryImport(TestCase):
16 def test_doesnt_exist(self):
17 # try_import('thing', foo) returns foo if 'thing' doesn't exist.
19 result = try_import('doesntexist', marker)
20 self.assertThat(result, Is(marker))
22 def test_None_is_default_alternative(self):
23 # try_import('thing') returns None if 'thing' doesn't exist.
24 result = try_import('doesntexist')
25 self.assertThat(result, Is(None))
27 def test_existing_module(self):
28 # try_import('thing', foo) imports 'thing' and returns it if it's a
30 result = try_import('os', object())
32 self.assertThat(result, Is(os))
34 def test_existing_submodule(self):
35 # try_import('thing.another', foo) imports 'thing' and returns it if
36 # it's a module that exists.
37 result = try_import('os.path', object())
39 self.assertThat(result, Is(os.path))
41 def test_nonexistent_submodule(self):
42 # try_import('thing.another', foo) imports 'thing' and returns foo if
43 # 'another' doesn't exist.
45 result = try_import('os.doesntexist', marker)
46 self.assertThat(result, Is(marker))
48 def test_object_from_module(self):
49 # try_import('thing.object') imports 'thing' and returns
50 # 'thing.object' if 'thing' is a module and 'object' is not.
51 result = try_import('os.path.join')
53 self.assertThat(result, Is(os.path.join))
56 class TestTryImports(TestCase):
58 def test_doesnt_exist(self):
59 # try_imports('thing', foo) returns foo if 'thing' doesn't exist.
61 result = try_imports(['doesntexist'], marker)
62 self.assertThat(result, Is(marker))
64 def test_fallback(self):
65 result = try_imports(['doesntexist', 'os'])
67 self.assertThat(result, Is(os))
69 def test_None_is_default_alternative(self):
70 # try_imports('thing') returns None if 'thing' doesn't exist.
71 e = self.assertRaises(
72 ImportError, try_imports, ['doesntexist', 'noreally'])
75 Equals("Could not import any of: doesntexist, noreally"))
77 def test_existing_module(self):
78 # try_imports('thing', foo) imports 'thing' and returns it if it's a
80 result = try_imports(['os'], object())
82 self.assertThat(result, Is(os))
84 def test_existing_submodule(self):
85 # try_imports('thing.another', foo) imports 'thing' and returns it if
86 # it's a module that exists.
87 result = try_imports(['os.path'], object())
89 self.assertThat(result, Is(os.path))
91 def test_nonexistent_submodule(self):
92 # try_imports('thing.another', foo) imports 'thing' and returns foo if
93 # 'another' doesn't exist.
95 result = try_imports(['os.doesntexist'], marker)
96 self.assertThat(result, Is(marker))
98 def test_fallback_submodule(self):
99 result = try_imports(['os.doesntexist', 'os.path'])
101 self.assertThat(result, Is(os.path))
105 from unittest import TestLoader
106 return TestLoader().loadTestsFromName(__name__)