Imported Upstream version 3.13.1
[platform/upstream/pygobject2.git] / tests / test_import_machinery.py
1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # vim: tabstop=4 shiftwidth=4 expandtab
3
4 import sys
5 import unittest
6
7 import gi.overrides
8 import gi.module
9
10 try:
11     from gi.repository import Regress
12     Regress  # pyflakes
13 except ImportError:
14     Regress = None
15
16
17 class TestRegistry(unittest.TestCase):
18     def test_non_gi(self):
19         class MyClass:
20             pass
21
22         try:
23             gi.overrides.override(MyClass)
24             self.fail('unexpected success of overriding non-GI class')
25         except TypeError as e:
26             self.assertTrue('Can not override a type MyClass' in str(e))
27
28     @unittest.skipUnless(Regress, 'built without cairo support')
29     def test_separate_path(self):
30         # Regress override is in tests/gi/overrides, separate from gi/overrides
31         # https://bugzilla.gnome.org/show_bug.cgi?id=680913
32         self.assertEqual(Regress.REGRESS_OVERRIDE, 42)
33
34
35 class TestModule(unittest.TestCase):
36     # Tests for gi.module
37
38     def test_get_introspection_module_caching(self):
39         # This test attempts to minimize side effects by
40         # using a DynamicModule directly instead of going though:
41         # from gi.repository import Foo
42
43         # Clear out introspection module cache before running this test.
44         old_modules = gi.module._introspection_modules
45         gi.module._introspection_modules = {}
46
47         mod_name = 'GIMarshallingTests'
48         mod1 = gi.module.get_introspection_module(mod_name)
49         mod2 = gi.module.get_introspection_module(mod_name)
50         self.assertTrue(mod1 is mod2)
51
52         # Using a DynamicModule will use get_introspection_module internally
53         # in its _load method.
54         mod_overridden = gi.module.DynamicModule(mod_name)
55         mod_overridden._load()
56         self.assertTrue(mod1 is mod_overridden._introspection_module)
57
58         # Restore the previous cache
59         gi.module._introspection_modules = old_modules
60
61
62 class TestImporter(unittest.TestCase):
63     def test_invalid_repository_module_name(self):
64         with self.assertRaises(ImportError) as context:
65             from gi.repository import InvalidGObjectRepositoryModuleName
66             InvalidGObjectRepositoryModuleName  # pyflakes
67
68         exception_string = str(context.exception)
69
70         self.assertTrue('InvalidGObjectRepositoryModuleName' in exception_string)
71
72         # The message of the custom exception in gi/importer.py is eaten in Python 2.7
73         if sys.version_info.major < 3:
74             self.assertTrue('introspection typelib' not in exception_string)
75         else:
76             self.assertTrue('introspection typelib' in exception_string)