1 # Test the module type 2 import unittest 3 from test.test_support import run_unittest, gc_collect 4 5 import sys 6 ModuleType = type(sys) 7 8 class ModuleTests(unittest.TestCase): 9 def test_uninitialized(self): 10 # An uninitialized module has no __dict__ or __name__, 11 # and __doc__ is None 12 foo = ModuleType.__new__(ModuleType) 13 self.assertTrue(foo.__dict__ is None) 14 self.assertRaises(SystemError, dir, foo) 15 try: 16 s = foo.__name__ 17 self.fail("__name__ = %s" % repr(s)) 18 except AttributeError: 19 pass 20 self.assertEqual(foo.__doc__, ModuleType.__doc__) 21 22 def test_no_docstring(self): 23 # Regularly initialized module, no docstring 24 foo = ModuleType("foo") 25 self.assertEqual(foo.__name__, "foo") 26 self.assertEqual(foo.__doc__, None) 27 self.assertEqual(foo.__dict__, {"__name__": "foo", "__doc__": None}) 28 29 def test_ascii_docstring(self): 30 # ASCII docstring 31 foo = ModuleType("foo", "foodoc") 32 self.assertEqual(foo.__name__, "foo") 33 self.assertEqual(foo.__doc__, "foodoc") 34 self.assertEqual(foo.__dict__, 35 {"__name__": "foo", "__doc__": "foodoc"}) 36 37 def test_unicode_docstring(self): 38 # Unicode docstring 39 foo = ModuleType("foo", u"foodoc\u1234") 40 self.assertEqual(foo.__name__, "foo") 41 self.assertEqual(foo.__doc__, u"foodoc\u1234") 42 self.assertEqual(foo.__dict__, 43 {"__name__": "foo", "__doc__": u"foodoc\u1234"}) 44 45 def test_reinit(self): 46 # Reinitialization should not replace the __dict__ 47 foo = ModuleType("foo", u"foodoc\u1234") 48 foo.bar = 42 49 d = foo.__dict__ 50 foo.__init__("foo", "foodoc") 51 self.assertEqual(foo.__name__, "foo") 52 self.assertEqual(foo.__doc__, "foodoc") 53 self.assertEqual(foo.bar, 42) 54 self.assertEqual(foo.__dict__, 55 {"__name__": "foo", "__doc__": "foodoc", "bar": 42}) 56 self.assertTrue(foo.__dict__ is d) 57 58 @unittest.expectedFailure 59 def test_dont_clear_dict(self): 60 # See issue 7140. 61 def f(): 62 foo = ModuleType("foo") 63 foo.bar = 4 64 return foo 65 gc_collect() 66 self.assertEqual(f().__dict__["bar"], 4) 67 68 def test_clear_dict_in_ref_cycle(self): 69 destroyed = [] 70 m = ModuleType("foo") 71 m.destroyed = destroyed 72 s = """class A: 73 def __del__(self, destroyed=destroyed): 74 destroyed.append(1) 75 a = A()""" 76 exec(s, m.__dict__) 77 del m 78 gc_collect() 79 self.assertEqual(destroyed, [1]) 80 81 def test_main(): 82 run_unittest(ModuleTests) 83 84 if __name__ == '__main__': 85 test_main() 86