blob: 9da353633385ac53ca794402c5366386bb58f4af [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
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +00004from test.support import run_unittest, gc_collect
Antoine Pitroudcedaf62013-07-31 23:14:08 +02005from test.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
Ethan Furman7b9ff0e2014-04-24 14:47:47 -070033 def test_unintialized_missing_getattr(self):
34 # 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
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000104 def test_clear_dict_in_ref_cycle(self):
105 destroyed = []
106 m = ModuleType("foo")
107 m.destroyed = destroyed
108 s = """class A:
Benjamin Petersonca81bf72011-12-15 15:57:15 -0500109 def __init__(self, l):
110 self.l = l
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000111 def __del__(self):
Benjamin Petersonca81bf72011-12-15 15:57:15 -0500112 self.l.append(1)
113a = A(destroyed)"""
Benjamin Peterson5c4bfc42010-10-12 22:57:59 +0000114 exec(s, m.__dict__)
115 del m
116 gc_collect()
117 self.assertEqual(destroyed, [1])
118
Antoine Pitrou4ed328c2013-08-01 19:20:31 +0200119 def test_weakref(self):
120 m = ModuleType("foo")
121 wr = weakref.ref(m)
122 self.assertIs(wr(), m)
123 del m
124 gc_collect()
125 self.assertIs(wr(), None)
126
Eric V. Smith984b11f2012-05-24 20:21:04 -0400127 def test_module_repr_minimal(self):
128 # reprs when modules have no __file__, __name__, or __loader__
129 m = ModuleType('foo')
130 del m.__name__
131 self.assertEqual(repr(m), "<module '?'>")
132
133 def test_module_repr_with_name(self):
134 m = ModuleType('foo')
135 self.assertEqual(repr(m), "<module 'foo'>")
136
137 def test_module_repr_with_name_and_filename(self):
138 m = ModuleType('foo')
139 m.__file__ = '/tmp/foo.py'
140 self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>")
141
142 def test_module_repr_with_filename_only(self):
143 m = ModuleType('foo')
144 del m.__name__
145 m.__file__ = '/tmp/foo.py'
146 self.assertEqual(repr(m), "<module '?' from '/tmp/foo.py'>")
147
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400148 def test_module_repr_with_loader_as_None(self):
149 m = ModuleType('foo')
150 assert m.__loader__ is None
151 self.assertEqual(repr(m), "<module 'foo'>")
152
Eric V. Smith984b11f2012-05-24 20:21:04 -0400153 def test_module_repr_with_bare_loader_but_no_name(self):
154 m = ModuleType('foo')
155 del m.__name__
156 # Yes, a class not an instance.
157 m.__loader__ = BareLoader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400158 loader_repr = repr(BareLoader)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400159 self.assertEqual(
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400160 repr(m), "<module '?' ({})>".format(loader_repr))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400161
162 def test_module_repr_with_full_loader_but_no_name(self):
163 # m.__loader__.module_repr() will fail because the module has no
164 # m.__name__. This exception will get suppressed and instead the
165 # loader's repr will be used.
166 m = ModuleType('foo')
167 del m.__name__
168 # Yes, a class not an instance.
169 m.__loader__ = FullLoader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400170 loader_repr = repr(FullLoader)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400171 self.assertEqual(
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400172 repr(m), "<module '?' ({})>".format(loader_repr))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400173
174 def test_module_repr_with_bare_loader(self):
175 m = ModuleType('foo')
176 # Yes, a class not an instance.
177 m.__loader__ = BareLoader
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400178 module_repr = repr(BareLoader)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400179 self.assertEqual(
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400180 repr(m), "<module 'foo' ({})>".format(module_repr))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400181
182 def test_module_repr_with_full_loader(self):
183 m = ModuleType('foo')
184 # Yes, a class not an instance.
185 m.__loader__ = FullLoader
186 self.assertEqual(
187 repr(m), "<module 'foo' (crafted)>")
188
189 def test_module_repr_with_bare_loader_and_filename(self):
190 # Because the loader has no module_repr(), use the file name.
191 m = ModuleType('foo')
192 # Yes, a class not an instance.
193 m.__loader__ = BareLoader
194 m.__file__ = '/tmp/foo.py'
195 self.assertEqual(repr(m), "<module 'foo' from '/tmp/foo.py'>")
196
197 def test_module_repr_with_full_loader_and_filename(self):
198 # Even though the module has an __file__, use __loader__.module_repr()
199 m = ModuleType('foo')
200 # Yes, a class not an instance.
201 m.__loader__ = FullLoader
202 m.__file__ = '/tmp/foo.py'
203 self.assertEqual(repr(m), "<module 'foo' (crafted)>")
204
205 def test_module_repr_builtin(self):
206 self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
207
208 def test_module_repr_source(self):
209 r = repr(unittest)
Brett Cannona24348c2013-11-22 13:22:22 -0500210 starts_with = "<module 'unittest' from '"
211 ends_with = "__init__.py'>"
212 self.assertEqual(r[:len(starts_with)], starts_with,
213 '{!r} does not start with {!r}'.format(r, starts_with))
214 self.assertEqual(r[-len(ends_with):], ends_with,
215 '{!r} does not end with {!r}'.format(r, ends_with))
Eric V. Smith984b11f2012-05-24 20:21:04 -0400216
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200217 def test_module_finalization_at_shutdown(self):
218 # Module globals and builtins should still be available during shutdown
219 rc, out, err = assert_python_ok("-c", "from test import final_a")
220 self.assertFalse(err)
221 lines = out.splitlines()
222 self.assertEqual(set(lines), {
223 b"x = a",
224 b"x = b",
225 b"final_a.x = a",
226 b"final_b.x = b",
227 b"len = len",
228 b"shutil.rmtree = rmtree"})
229
Benjamin Peterson1184e262014-04-24 19:29:23 -0400230 def test_descriptor_errors_propogate(self):
231 class Descr:
232 def __get__(self, o, t):
233 raise RuntimeError
234 class M(ModuleType):
235 melon = Descr()
236 self.assertRaises(RuntimeError, getattr, M("mymod"), "melon")
237
Eric V. Smith984b11f2012-05-24 20:21:04 -0400238 # frozen and namespace module reprs are tested in importlib.
239
240
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241def test_main():
242 run_unittest(ModuleTests)
243
Eric V. Smith984b11f2012-05-24 20:21:04 -0400244
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245if __name__ == '__main__':
246 test_main()