|
7 | 7 | import sys |
8 | 8 | import py_compile |
9 | 9 | import warnings |
| 10 | +import imp |
10 | 11 | from test.test_support import unlink, TESTFN, unload |
11 | 12 |
|
12 | 13 |
|
@@ -160,6 +161,45 @@ def test_import_initless_directory_warning(self): |
160 | 161 | warnings.simplefilter('error', ImportWarning) |
161 | 162 | self.assertRaises(ImportWarning, __import__, "site-packages") |
162 | 163 |
|
| 164 | + def test_failing_reload(self): |
| 165 | + # A failing reload should leave the module object in sys.modules. |
| 166 | + source = TESTFN + ".py" |
| 167 | + with open(source, "w") as f: |
| 168 | + f.write("a = 1\nb=2\n") |
| 169 | + |
| 170 | + sys.path.insert(0, os.curdir) |
| 171 | + try: |
| 172 | + mod = __import__(TESTFN) |
| 173 | + self.assert_(TESTFN in sys.modules, "expected module in sys.modules") |
| 174 | + self.assertEquals(mod.a, 1, "module has wrong attribute values") |
| 175 | + self.assertEquals(mod.b, 2, "module has wrong attribute values") |
| 176 | + |
| 177 | + # On WinXP, just replacing the .py file wasn't enough to |
| 178 | + # convince reload() to reparse it. Maybe the timestamp didn't |
| 179 | + # move enough. We force it to get reparsed by removing the |
| 180 | + # compiled file too. |
| 181 | + remove_files(TESTFN) |
| 182 | + |
| 183 | + # Now damage the module. |
| 184 | + with open(source, "w") as f: |
| 185 | + f.write("a = 10\nb=20//0\n") |
| 186 | + |
| 187 | + self.assertRaises(ZeroDivisionError, imp.reload, mod) |
| 188 | + # But we still expect the module to be in sys.modules. |
| 189 | + mod = sys.modules.get(TESTFN) |
| 190 | + self.failIf(mod is None, "expected module to still be in sys.modules") |
| 191 | + |
| 192 | + # We should have replaced a w/ 10, but the old b value should |
| 193 | + # stick. |
| 194 | + self.assertEquals(mod.a, 10, "module has wrong attribute values") |
| 195 | + self.assertEquals(mod.b, 2, "module has wrong attribute values") |
| 196 | + |
| 197 | + finally: |
| 198 | + sys.path.pop(0) |
| 199 | + remove_files(TESTFN) |
| 200 | + if TESTFN in sys.modules: |
| 201 | + del sys.modules[TESTFN] |
| 202 | + |
163 | 203 | class PathsTests(unittest.TestCase): |
164 | 204 | SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8', |
165 | 205 | 'test\u00b0\u00b3\u00b2') |
|
0 commit comments