blob: 6d0d59407ed24005bc1524c79e6ca595f453885a [file] [log] [blame]
Guido van Rossumc3a787e2002-06-04 05:52:47 +00001# Test the module type
Guido van Rossumd8faa362007-04-27 19:54:29 +00002import unittest
Antoine Pitrou4ed328c2013-08-01 19:20:31 +02003import weakref
Serhiy Storchakaa7930372016-07-03 22:27:26 +03004from test.support import gc_collect, requires_type_collecting
Berker Peksagce643912015-05-06 06:33:17 +03005from test.support.script_helper import assert_python_ok
Guido van Rossumc3a787e2002-06-04 05:52:47 +00006
7import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +00008ModuleType = type(sys)
Guido van Rossumc3a787e2002-06-04 05:52:47 +00009
Eric V. Smith984b11f2012-05-24 20:21:04 -040010class FullLoader:
11 @classmethod
12 def module_repr(cls, m):
13 return "<module '{}' (crafted)>".format(m.__name__)
14
15class BareLoader:
16 pass
17
18
Guido van Rossumd8faa362007-04-27 19:54:29 +000019class ModuleTests(unittest.TestCase):
20 def test_uninitialized(self):
21 # An uninitialized module has no __dict__ or __name__,
22 # and __doc__ is None
23 foo = ModuleType.__new__(ModuleType)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000024 self.assertTrue(foo.__dict__ is None)
Benjamin Peterson14327712009-08-15 13:23:05 +000025 self.assertRaises(SystemError, dir, foo)
Guido van Rossumd8faa362007-04-27 19:54:29 +000026 try:
27 s = foo.__name__
28 self.fail("__name__ = %s" % repr(s))
29 except AttributeError:
30 pass
31 self.assertEqual(foo.__doc__, ModuleType.__doc__)
Guido van Rossumc3a787e2002-06-04 05:52:47 +000032
Martin Panterf05641642016-05-08 13:48:10 +000033 def test_uninitialized_missing_getattr(self):
Ethan Furman7b9ff0e2014-04-24 14:47:47 -070034 # Issue 8297
35 # test the text in the AttributeError of an uninitialized module
36 foo = ModuleType.__new__(ModuleType)
37 self.assertRaisesRegex(
38 AttributeError, "module has no attribute 'not_here'",
39 getattr, foo, "not_here")
40
41 def test_missing_getattr(self):
42 # Issue 8297
43 # test the text in the AttributeError
44 foo = ModuleType("foo")
45 self.assertRaisesRegex(
46 AttributeError, "module 'foo' has no attribute 'not_here'",
47 getattr, foo, "not_here")
48
Guido van Rossumd8faa362007-04-27 19:54:29 +000049 def test_no_docstring(self):
50 # Regularly initialized module, no docstring
51 foo = ModuleType("foo")
52 self.assertEqual(foo.__name__, "foo")
53 self.assertEqual(foo.__doc__, None)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040054 self.assertIs(foo.__loader__, None)
55 self.assertIs(foo.__package__, None)
Eric Snowb523f842013-11-22 09:05:39 -070056 self.assertIs(foo.__spec__, None)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040057 self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": None,
Eric Snowb523f842013-11-22 09:05:39 -070058 "__loader__": None, "__package__": None,
59 "__spec__": None})
Guido van Rossumc3a787e2002-06-04 05:52:47 +000060
Guido van Rossumd8faa362007-04-27 19:54:29 +000061 def test_ascii_docstring(self):
62 # ASCII docstring
63 foo = ModuleType("foo", "foodoc")
64 self.assertEqual(foo.__name__, "foo")
65 self.assertEqual(foo.__doc__, "foodoc")
66 self.assertEqual(foo.__dict__,
Brett Cannon4c14b5d2013-05-04 13:56:58 -040067 {"__name__": "foo", "__doc__": "foodoc",
Eric Snowb523f842013-11-22 09:05:39 -070068 "__loader__": None, "__package__": None,
69 "__spec__": None})
Guido van Rossumc3a787e2002-06-04 05:52:47 +000070
Guido van Rossumd8faa362007-04-27 19:54:29 +000071 def test_unicode_docstring(self):
72 # Unicode docstring
Guido van Rossumef87d6e2007-05-02 19:09:54 +000073 foo = ModuleType("foo", "foodoc\u1234")
Guido van Rossumd8faa362007-04-27 19:54:29 +000074 self.assertEqual(foo.__name__, "foo")
Guido van Rossumef87d6e2007-05-02 19:09:54 +000075 self.assertEqual(foo.__doc__, "foodoc\u1234")
Guido van Rossumd8faa362007-04-27 19:54:29 +000076 self.assertEqual(foo.__dict__,
Brett Cannon4c14b5d2013-05-04 13:56:58 -040077 {"__name__": "foo", "__doc__": "foodoc\u1234",
Eric Snowb523f842013-11-22 09:05:39 -070078 "__loader__": None, "__package__": None,
79 "__spec__": None})
Guido van Rossumc3a787e2002-06-04 05:52:47 +000080
Guido van Rossumd8faa362007-04-27 19:54:29 +000081 def test_reinit(self):
82 # Reinitialization should not replace the __dict__
Guido van Rossumef87d6e2007-05-02 19:09:54 +000083 foo = ModuleType("foo", "foodoc\u1234")
Guido van Rossumd8faa362007-04-27 19:54:29 +000084 foo.bar = 42
85 d = foo.__dict__
86 foo.__init__("foo", "foodoc")
87 self.assertEqual(foo.__name__, "foo")
88 self.assertEqual(foo.__doc__, "foodoc")
89 self.assertEqual(foo.bar, 42)
90 self.assertEqual(foo.__dict__,
Brett Cannon4c14b5d2013-05-04 13:56:58 -040091 {"__name__": "foo", "__doc__": "foodoc", "bar": 42,
Eric Snowb523f842013-11-22 09:05:39 -070092 "__loader__": None, "__package__": None, "__spec__": None})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000093 self.assertTrue(foo.__dict__ is d)
Guido van Rossumc3a787e2002-06-04 05:52:47 +000094
Benjamin Petersona0dfa822009-11-13 02:25:08 +000095 def test_dont_clear_dict(self):
96 # See issue 7140.
97 def f():
98 foo = ModuleType("foo")
99 foo.bar = 4
100 return foo
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000101 gc_collect()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000102 self.assertEqual(f().__dict__["bar"], 4)
103
Serhiy Storchakaa7930372016-07-03 22:27:26 +0300104 @requires_type_collecting
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000105 def test_clear_dict_in_ref_cycle(self):
106 destroyed = []
107 m = ModuleType("foo")
108 m.destroyed = destroyed
109 s = """class A:
Benjamin Petersonca81bf72011-12-15 15:57:15 -0500110 def __init__(self, l):
111 self.l = l
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000112 def __del__(self):
Benjamin Petersonca81bf72011-12-15 15:57:15 -0500113 self.l.append(1)
114a = A(destroyed)"""
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000115 exec(s, m.__dict__)
116 del m
117 gc_collect()
118 self.assertEqual(destroyed, [1])
119
Antoine Pitrou4ed328c2013-08-01 19:20:31 +0200120 def test_weakref(self):
121 m = ModuleType("foo")
122 wr = weakref.ref(m)
123 self.assertIs(wr(), m)
124 del m
125 gc_collect()
126 self.assertIs(wr(), None)
127
Eric V. Smith984b11f2012-05-24 20:21:04 -0400128 def test_module_repr_minimal(self):
129 # reprs when modules have no __file__, __name__, or __loader__
130 m = ModuleType('foo')
131 del m.__name__
132 self.assertEqual(repr(m), "<module '?'>")
133
134 def test_module_repr_with_name(self):
135 m = ModuleType('foo')
136 self.assertEqual(repr(m), "<module 'foo'>")
137
138 def test_module_repr_with_name_and_filename(self):
139 m = ModuleType('foo')
140 m.__file__ = '/tmp/foo.py'
141 self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>")
142
143 def test_module_repr_with_filename_only(self):
144 m = ModuleType('foo')
145 del m.__name__
146 m.__file__ = '/tmp/foo.py'
147 self.assertEqual(repr(m), "<module '?' from '/tmp/foo.py'>")
148
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400149 def test_module_repr_with_loader_as_None(self):
150 m = ModuleType('foo')
151 assert m.__loader__ is None
152 self.assertEqual(repr(m), "<module 'foo'>")
153
Eric V. Smith984b11f2012-05-24 20:21:04 -0400154 def test_module_repr_with_bare_loader_but_no_name(self):
155 m = ModuleType('foo')
156 del m.__name__
157 # Yes, a class not an instance.
158 m.__loader__ = BareLoader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400159 loader_repr = repr(BareLoader)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400160 self.assertEqual(
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400161 repr(m), "<module '?' ({})>".format(loader_repr))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400162
163 def test_module_repr_with_full_loader_but_no_name(self):
164 # m.__loader__.module_repr() will fail because the module has no
165 # m.__name__. This exception will get suppressed and instead the
166 # loader's repr will be used.
167 m = ModuleType('foo')
168 del m.__name__
169 # Yes, a class not an instance.
170 m.__loader__ = FullLoader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400171 loader_repr = repr(FullLoader)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400172 self.assertEqual(
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400173 repr(m), "<module '?' ({})>".format(loader_repr))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400174
175 def test_module_repr_with_bare_loader(self):
176 m = ModuleType('foo')
177 # Yes, a class not an instance.
178 m.__loader__ = BareLoader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400179 module_repr = repr(BareLoader)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400180 self.assertEqual(
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400181 repr(m), "<module 'foo' ({})>".format(module_repr))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400182
183 def test_module_repr_with_full_loader(self):
184 m = ModuleType('foo')
185 # Yes, a class not an instance.
186 m.__loader__ = FullLoader
187 self.assertEqual(
188 repr(m), "<module 'foo' (crafted)>")
189
190 def test_module_repr_with_bare_loader_and_filename(self):
191 # Because the loader has no module_repr(), use the file name.
192 m = ModuleType('foo')
193 # Yes, a class not an instance.
194 m.__loader__ = BareLoader
195 m.__file__ = '/tmp/foo.py'
196 self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>")
197
198 def test_module_repr_with_full_loader_and_filename(self):
199 # Even though the module has an __file__, use __loader__.module_repr()
200 m = ModuleType('foo')
201 # Yes, a class not an instance.
202 m.__loader__ = FullLoader
203 m.__file__ = '/tmp/foo.py'
204 self.assertEqual(repr(m), "<module 'foo' (crafted)>")
205
206 def test_module_repr_builtin(self):
207 self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
208
209 def test_module_repr_source(self):
210 r = repr(unittest)
Brett Cannona24348c2013-11-22 13:22:22 -0500211 starts_with = "<module 'unittest' from '"
212 ends_with = "__init__.py'>"
213 self.assertEqual(r[:len(starts_with)], starts_with,
214 '{!r} does not start with {!r}'.format(r, starts_with))
215 self.assertEqual(r[-len(ends_with):], ends_with,
216 '{!r} does not end with {!r}'.format(r, ends_with))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400217
Serhiy Storchakaa7930372016-07-03 22:27:26 +0300218 @requires_type_collecting
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200219 def test_module_finalization_at_shutdown(self):
220 # Module globals and builtins should still be available during shutdown
221 rc, out, err = assert_python_ok("-c", "from test import final_a")
222 self.assertFalse(err)
223 lines = out.splitlines()
224 self.assertEqual(set(lines), {
225 b"x = a",
226 b"x = b",
227 b"final_a.x = a",
228 b"final_b.x = b",
229 b"len = len",
230 b"shutil.rmtree = rmtree"})
231
Martin Pantere26da7c2016-06-02 10:07:09 +0000232 def test_descriptor_errors_propagate(self):
Benjamin Peterson1184e262014-04-24 19:29:23 -0400233 class Descr:
234 def __get__(self, o, t):
235 raise RuntimeError
236 class M(ModuleType):
237 melon = Descr()
238 self.assertRaises(RuntimeError, getattr, M("mymod"), "melon")
239
Eric V. Smith984b11f2012-05-24 20:21:04 -0400240 # frozen and namespace module reprs are tested in importlib.
241
242
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243if __name__ == '__main__':
Zachary Ware38c707e2015-04-13 15:00:43 -0500244 unittest.main()