Debian Codegraph @

tests/test_zzz_autoreload.py

raw
1 """Tests for autoreload extension."""
2
3 # -----------------------------------------------------------------------------
4 # Copyright (c) 2012 IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 # -----------------------------------------------------------------------------
10
11 # -----------------------------------------------------------------------------
12 # Imports
13 # -----------------------------------------------------------------------------
14
15 import os
16 import platform
17 import pytest
18 import sys
19 import tempfile
20 import textwrap
21 import shutil
22 import random
23 import time
24 import traceback
25 from io import StringIO
26 from dataclasses import dataclass
27
28 import IPython.testing.tools as tt
29
30 from unittest import TestCase
31
32 from IPython.extensions.autoreload import AutoreloadMagics
33 from IPython.core.events import EventManager, pre_run_cell
34 from IPython.testing.decorators import skipif_not_numpy
35 from IPython.core.interactiveshell import ExecutionInfo
36 from IPython.core import inputtransformer2 as ipt2
37
38 if platform.python_implementation() == "PyPy":
39 pytest.skip(
40 "Current autoreload implementation is extremely slow on PyPy",
41 allow_module_level=True,
42 )
43
44 # -----------------------------------------------------------------------------
45 # Test fixture
46 # -----------------------------------------------------------------------------
47
48 noop = lambda *a, **kw: None
49
50
51 class FakeShell:
52 def __init__(self):
53 self.ns = {}
54 self.user_ns = self.ns
55 self.user_ns["In"] = []
56 self.user_ns_hidden = {}
57 self.events = EventManager(self, {"pre_run_cell", pre_run_cell})
58 self.auto_magics = AutoreloadMagics(shell=self)
59 self.events.register("pre_run_cell", self.auto_magics.pre_run_cell)
60 self.input_transformer_manager = ipt2.TransformerManager()
61
62 register_magics = set_hook = noop
63
64 def showtraceback(
65 self,
66 exc_tuple=None,
67 filename=None,
68 tb_offset=None,
69 exception_only=False,
70 running_compiled_code=False,
71 ):
72 traceback.print_exc()
73
74 def run_code(self, code):
75 transformed_cell = self.input_transformer_manager.transform_cell(code)
76 self.events.trigger(
77 "pre_run_cell",
78 ExecutionInfo(
79 raw_cell=code,
80 transformed_cell=code,
81 store_history=False,
82 silent=False,
83 shell_futures=False,
84 cell_id=None,
85 ),
86 )
87 exec(code, self.user_ns)
88 self.auto_magics.post_execute_hook()
89
90 def push(self, items):
91 self.ns.update(items)
92
93 def magic_autoreload(self, parameter):
94 self.auto_magics.autoreload(parameter)
95
96 def magic_aimport(self, parameter, stream=None):
97 self.auto_magics.aimport(parameter, stream=stream)
98 self.auto_magics.post_execute_hook()
99
100
101 class Fixture(TestCase):
102 """Fixture for creating test module files"""
103
104 test_dir = None
105 old_sys_path = None
106 filename_chars = "abcdefghijklmopqrstuvwxyz0123456789"
107
108 def setUp(self):
109 self.test_dir = tempfile.mkdtemp()
110 self.old_sys_path = list(sys.path)
111 sys.path.insert(0, self.test_dir)
112 self.shell = FakeShell()
113
114 def tearDown(self):
115 shutil.rmtree(self.test_dir)
116 sys.path = self.old_sys_path
117
118 self.test_dir = None
119 self.old_sys_path = None
120 self.shell = None
121
122 def get_module(self):
123 module_name = "tmpmod_" + "".join(random.sample(self.filename_chars, 20))
124 if module_name in sys.modules:
125 del sys.modules[module_name]
126 file_name = os.path.join(self.test_dir, module_name + ".py")
127 return module_name, file_name
128
129 def write_file(self, filename, content):
130 """
131 Write a file, and force a timestamp difference of at least one second
132
133 Notes
134 -----
135 Python's .pyc files record the timestamp of their compilation
136 with a time resolution of one second.
137
138 Therefore, we need to force a timestamp difference between .py
139 and .pyc, without having the .py file be timestamped in the
140 future, and without changing the timestamp of the .pyc file
141 (because that is stored in the file). The only reliable way
142 to achieve this seems to be to sleep.
143 """
144 content = textwrap.dedent(content)
145 # Sleep one second + eps
146 time.sleep(1.05)
147
148 # Write
149 with open(filename, "w", encoding="utf-8") as f:
150 f.write(content)
151
152 def new_module(self, code):
153 code = textwrap.dedent(code)
154 mod_name, mod_fn = self.get_module()
155 with open(mod_fn, "w", encoding="utf-8") as f:
156 f.write(code)
157 return mod_name, mod_fn
158
159
160 # -----------------------------------------------------------------------------
161 # Test automatic reloading
162 # -----------------------------------------------------------------------------
163
164
165 def pickle_get_current_class(obj):
166 """
167 Original issue comes from pickle; hence the name.
168 """
169 name = obj.__class__.__name__
170 module_name = getattr(obj, "__module__", None)
171 obj2 = sys.modules[module_name]
172 for subpath in name.split("."):
173 obj2 = getattr(obj2, subpath)
174 return obj2
175
176
177 class TestAutoreload(Fixture):
178 def test_reload_enums(self):
179 mod_name, mod_fn = self.new_module(
180 textwrap.dedent(
181 """
182 from enum import Enum
183 class MyEnum(Enum):
184 A = 'A'
185 B = 'B'
186 """
187 )
188 )
189 self.shell.magic_autoreload("2")
190 self.shell.magic_aimport(mod_name)
191 self.write_file(
192 mod_fn,
193 textwrap.dedent(
194 """
195 from enum import Enum
196 class MyEnum(Enum):
197 A = 'A'
198 B = 'B'
199 C = 'C'
200 """
201 ),
202 )
203 with tt.AssertNotPrints(
204 ("[autoreload of %s failed:" % mod_name), channel="stderr"
205 ):
206 self.shell.run_code("pass") # trigger another reload
207
208 def test_reload_class_type(self):
209 self.shell.magic_autoreload("2")
210 mod_name, mod_fn = self.new_module(
211 """
212 class Test():
213 def meth(self):
214 return "old"
215 """
216 )
217 assert "test" not in self.shell.ns
218 assert "result" not in self.shell.ns
219
220 self.shell.run_code("from %s import Test" % mod_name)
221 self.shell.run_code("test = Test()")
222
223 self.write_file(
224 mod_fn,
225 """
226 class Test():
227 def meth(self):
228 return "new"
229 """,
230 )
231
232 test_object = self.shell.ns["test"]
233
234 # important to trigger autoreload logic !
235 self.shell.run_code("pass")
236
237 test_class = pickle_get_current_class(test_object)
238 assert isinstance(test_object, test_class)
239
240 # extra check.
241 self.shell.run_code("import pickle")
242 self.shell.run_code("p = pickle.dumps(test)")
243
244 def test_reload_class_attributes(self):
245 self.shell.magic_autoreload("2")
246 mod_name, mod_fn = self.new_module(
247 textwrap.dedent(
248 """
249 class MyClass:
250
251 def __init__(self, a=10):
252 self.a = a
253 self.b = 22
254 # self.toto = 33
255
256 def square(self):
257 print('compute square')
258 return self.a*self.a
259 """
260 )
261 )
262 self.shell.run_code("from %s import MyClass" % mod_name)
263 self.shell.run_code("first = MyClass(5)")
264 self.shell.run_code("first.square()")
265 with self.assertRaises(AttributeError):
266 self.shell.run_code("first.cube()")
267 with self.assertRaises(AttributeError):
268 self.shell.run_code("first.power(5)")
269 self.shell.run_code("first.b")
270 with self.assertRaises(AttributeError):
271 self.shell.run_code("first.toto")
272
273 # remove square, add power
274
275 self.write_file(
276 mod_fn,
277 textwrap.dedent(
278 """
279 class MyClass:
280
281 def __init__(self, a=10):
282 self.a = a
283 self.b = 11
284
285 def power(self, p):
286 print('compute power '+str(p))
287 return self.a**p
288 """
289 ),
290 )
291
292 self.shell.run_code("second = MyClass(5)")
293
294 for object_name in {"first", "second"}:
295 self.shell.run_code(f"{object_name}.power(5)")
296 with self.assertRaises(AttributeError):
297 self.shell.run_code(f"{object_name}.cube()")
298 with self.assertRaises(AttributeError):
299 self.shell.run_code(f"{object_name}.square()")
300 self.shell.run_code(f"{object_name}.b")
301 self.shell.run_code(f"{object_name}.a")
302 with self.assertRaises(AttributeError):
303 self.shell.run_code(f"{object_name}.toto")
304
305 @skipif_not_numpy
306 def test_comparing_numpy_structures(self):
307 self.shell.magic_autoreload("2")
308 self.shell.run_code("1+1")
309 mod_name, mod_fn = self.new_module(
310 textwrap.dedent(
311 """
312 import numpy as np
313 class MyClass:
314 a = (np.array((.1, .2)),
315 np.array((.2, .3)))
316 """
317 )
318 )
319 self.shell.run_code("from %s import MyClass" % mod_name)
320 self.shell.run_code("first = MyClass()")
321
322 # change property `a`
323 self.write_file(
324 mod_fn,
325 textwrap.dedent(
326 """
327 import numpy as np
328 class MyClass:
329 a = (np.array((.3, .4)),
330 np.array((.5, .6)))
331 """
332 ),
333 )
334
335 with tt.AssertNotPrints(
336 ("[autoreload of %s failed:" % mod_name), channel="stderr"
337 ):
338 self.shell.run_code("pass") # trigger another reload
339
340 def test_autoload_newly_added_objects(self):
341 # All of these fail with %autoreload 2
342 self.shell.magic_autoreload("3")
343 mod_code = """
344 def func1(): pass
345 """
346 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
347 self.shell.run_code(f"from {mod_name} import *")
348 self.shell.run_code("func1()")
349 with self.assertRaises(NameError):
350 self.shell.run_code("func2()")
351 with self.assertRaises(NameError):
352 self.shell.run_code("t = Test()")
353 with self.assertRaises(NameError):
354 self.shell.run_code("number")
355
356 # ----------- TEST NEW OBJ LOADED --------------------------
357
358 new_code = """
359 def func1(): pass
360 def func2(): pass
361 class Test: pass
362 number = 0
363 from enum import Enum
364 class TestEnum(Enum):
365 A = 'a'
366 """
367 self.write_file(mod_fn, textwrap.dedent(new_code))
368
369 # test function now exists in shell's namespace namespace
370 self.shell.run_code("func2()")
371 # test function now exists in module's dict
372 self.shell.run_code(f"import sys; sys.modules['{mod_name}'].func2()")
373 # test class now exists
374 self.shell.run_code("t = Test()")
375 # test global built-in var now exists
376 self.shell.run_code("number")
377 # test the enumerations gets loaded successfully
378 self.shell.run_code("TestEnum.A")
379
380 # ----------- TEST NEW OBJ CAN BE CHANGED --------------------
381
382 new_code = """
383 def func1(): return 'changed'
384 def func2(): return 'changed'
385 class Test:
386 def new_func(self):
387 return 'changed'
388 number = 1
389 from enum import Enum
390 class TestEnum(Enum):
391 A = 'a'
392 B = 'added'
393 """
394 self.write_file(mod_fn, textwrap.dedent(new_code))
395 self.shell.run_code("assert func1() == 'changed'")
396 self.shell.run_code("assert func2() == 'changed'")
397 self.shell.run_code("t = Test(); assert t.new_func() == 'changed'")
398 self.shell.run_code("assert number == 1")
399
400 # ----------- TEST IMPORT FROM MODULE --------------------------
401
402 new_mod_code = """
403 from enum import Enum
404 class Ext(Enum):
405 A = 'ext'
406 def ext_func():
407 return 'ext'
408 class ExtTest:
409 def meth(self):
410 return 'ext'
411 ext_int = 2
412 """
413 new_mod_name, new_mod_fn = self.new_module(textwrap.dedent(new_mod_code))
414 current_mod_code = f"""
415 from {new_mod_name} import *
416 """
417 self.write_file(mod_fn, textwrap.dedent(current_mod_code))
418 self.shell.run_code("assert Ext.A.value == 'ext'")
419 self.shell.run_code("assert ext_func() == 'ext'")
420 self.shell.run_code("t = ExtTest(); assert t.meth() == 'ext'")
421 self.shell.run_code("assert ext_int == 2")
422
423 def test_autoload3_import_Y_as_Z(self):
424 self.shell.magic_autoreload("3")
425 mod_code = """
426 def func1(): pass
427 n = 1
428 """
429 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
430 self.shell.run_code(f"from {mod_name} import n as foo")
431 self.shell.run_code("foo")
432 with self.assertRaises(NameError):
433 self.shell.run_code("func1()")
434
435 new_code = """
436 n = 100
437 def func2(): pass
438 def func1(): pass
439 m = 5
440 """
441 self.write_file(mod_fn, textwrap.dedent(new_code))
442
443 self.shell.run_code("foo")
444 with self.assertRaises(NameError):
445 self.shell.run_code("n")
446
447 def test_autoload3_import_Y_as_Z_overloading(self):
448 self.shell.magic_autoreload("3")
449 mod_code = """
450 def func1(): pass
451 n = 1
452 """
453 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
454 self.shell.run_code(f"from {mod_name} import n as foo")
455 self.shell.run_code("foo")
456 with self.assertRaises(NameError):
457 self.shell.run_code("func1()")
458
459 new_code = """
460 n = 100
461 def func2(): pass
462 def func1(): pass
463 foo = 45
464 """
465 self.write_file(mod_fn, textwrap.dedent(new_code))
466 self.shell.run_code(f"assert foo == 100")
467 self.shell.run_code(f"from {mod_name} import foo")
468 self.shell.run_code(f"assert foo == 45")
469
470 def test_autoload3_normalimport(self):
471 self.shell.magic_autoreload("3")
472 mod_code = """
473 def func1(): pass
474 n = 1
475 """
476 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
477 self.shell.run_code(f"import {mod_name}")
478 self.shell.run_code(f"{mod_name}.func1()")
479 self.shell.run_code(f"{mod_name}.n")
480
481 new_code = """
482 n = 100
483 def func2(): pass
484 def func1(): pass
485 m = 5
486 """
487 self.write_file(mod_fn, textwrap.dedent(new_code))
488
489 self.shell.run_code(f"{mod_name}.func1()")
490 self.shell.run_code(f"{mod_name}.n")
491 self.shell.run_code(f"{mod_name}.func2()")
492 self.shell.run_code(f"{mod_name}.m")
493
494 self.shell.run_code(f"from {mod_name} import n")
495 self.shell.run_code(f"{mod_name}.func1()")
496 self.shell.run_code(f"n")
497
498 def test_autoload3_normalimport_2(self):
499 self.shell.magic_autoreload("3")
500 mod_code = """
501 def func1(): pass
502 n = 1
503 """
504 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
505 self.shell.run_code(f"from {mod_name} import n")
506 with self.assertRaises(NameError):
507 self.shell.run_code("func1()")
508 self.shell.run_code("n")
509
510 new_code = """
511 n = 100
512 def func2(): pass
513 def func1(): pass
514 m = 5
515 """
516 self.shell.run_code(f"import {mod_name}")
517 self.write_file(mod_fn, textwrap.dedent(new_code))
518 self.shell.run_code(f"{mod_name}.func1()")
519 self.shell.run_code(f"{mod_name}.n")
520 self.shell.run_code(f"{mod_name}.func2()")
521 self.shell.run_code(f"{mod_name}.m")
522 self.shell.run_code(f"n")
523
524 def test_autoload_3_does_not_add_all(self):
525 # Tests that %autoreload 3 does not effectively run from X import *
526 self.shell.magic_autoreload("3")
527 mod_code = """
528 def func1(): pass
529 n = 1
530 """
531 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
532 self.shell.run_code(f"from {mod_name} import n")
533 self.shell.run_code("n")
534 with self.assertRaises(NameError):
535 self.shell.run_code("func()")
536
537 new_code = """
538 n = 1
539 def func2(): pass
540 def func1(): pass
541 m = 5
542 """
543 self.write_file(mod_fn, textwrap.dedent(new_code))
544 self.shell.run_code("n")
545 with self.assertRaises(NameError):
546 self.shell.run_code("func1()")
547 with self.assertRaises(NameError):
548 self.shell.run_code("func2()")
549 with self.assertRaises(NameError):
550 self.shell.run_code("m")
551
552 self.shell.run_code(f"from {mod_name} import m")
553 self.shell.run_code("n")
554 self.shell.run_code("m")
555 with self.assertRaises(NameError):
556 self.shell.run_code("func1()")
557 with self.assertRaises(NameError):
558 self.shell.run_code("func2()")
559
560 self.shell.run_code(f"from {mod_name} import func1,func2")
561 self.shell.run_code("n")
562 self.shell.run_code("m")
563 self.shell.run_code("func1()")
564 self.shell.run_code("func2()")
565
566 def test_verbose_names(self):
567 # Asserts correspondense between original mode names and their verbose equivalents.
568 @dataclass
569 class AutoreloadSettings:
570 check_all: bool
571 enabled: bool
572 autoload_obj: bool
573
574 def gather_settings(mode):
575 self.shell.magic_autoreload(mode)
576 module_reloader = self.shell.auto_magics._reloader
577 return AutoreloadSettings(
578 module_reloader.check_all,
579 module_reloader.enabled,
580 module_reloader.autoload_obj,
581 )
582
583 assert gather_settings("0") == gather_settings("off")
584 assert gather_settings("0") == gather_settings("OFF") # Case insensitive
585 assert gather_settings("1") == gather_settings("explicit")
586 assert gather_settings("2") == gather_settings("all")
587 assert gather_settings("3") == gather_settings("complete")
588
589 # And an invalid mode name raises an exception.
590 with self.assertRaises(ValueError):
591 self.shell.magic_autoreload("4")
592
593 def test_aimport_parsing(self):
594 # Modules can be included or excluded all in one line.
595 module_reloader = self.shell.auto_magics._reloader
596 self.shell.magic_aimport("os") # import and mark `os` for auto-reload.
597 assert module_reloader.modules["os"] is True
598 assert "os" not in module_reloader.skip_modules.keys()
599
600 self.shell.magic_aimport("-math") # forbid autoreloading of `math`
601 assert module_reloader.skip_modules["math"] is True
602 assert "math" not in module_reloader.modules.keys()
603
604 self.shell.magic_aimport(
605 "-os, math"
606 ) # Can do this all in one line; wasn't possible before.
607 assert module_reloader.modules["math"] is True
608 assert "math" not in module_reloader.skip_modules.keys()
609 assert module_reloader.skip_modules["os"] is True
610 assert "os" not in module_reloader.modules.keys()
611
612 def test_autoreload_output(self):
613 self.shell.magic_autoreload("complete")
614 mod_code = """
615 def func1(): pass
616 """
617 mod_name, mod_fn = self.new_module(mod_code)
618 self.shell.run_code(f"import {mod_name}")
619 with tt.AssertPrints("", channel="stdout"): # no output; this is default
620 self.shell.run_code("pass")
621
622 self.shell.magic_autoreload("complete --print")
623 self.write_file(mod_fn, mod_code) # "modify" the module
624 with tt.AssertPrints(
625 f"Reloading '{mod_name}'.", channel="stdout"
626 ): # see something printed out
627 self.shell.run_code("pass")
628
629 self.shell.magic_autoreload("complete -p")
630 self.write_file(mod_fn, mod_code) # "modify" the module
631 with tt.AssertPrints(
632 f"Reloading '{mod_name}'.", channel="stdout"
633 ): # see something printed out
634 self.shell.run_code("pass")
635
636 self.shell.magic_autoreload("complete --print --log")
637 self.write_file(mod_fn, mod_code) # "modify" the module
638 with tt.AssertPrints(
639 f"Reloading '{mod_name}'.", channel="stdout"
640 ): # see something printed out
641 self.shell.run_code("pass")
642
643 self.shell.magic_autoreload("complete --print --log")
644 self.write_file(mod_fn, mod_code) # "modify" the module
645 with self.assertLogs(logger="autoreload") as lo: # see something printed out
646 self.shell.run_code("pass")
647 assert lo.output == [f"INFO:autoreload:Reloading '{mod_name}'."]
648
649 self.shell.magic_autoreload("complete -l")
650 self.write_file(mod_fn, mod_code) # "modify" the module
651 with self.assertLogs(logger="autoreload") as lo: # see something printed out
652 self.shell.run_code("pass")
653 assert lo.output == [f"INFO:autoreload:Reloading '{mod_name}'."]
654
655 def _check_smoketest(self, use_aimport=True):
656 """
657 Functional test for the automatic reloader using either
658 '%autoreload 1' or '%autoreload 2'
659 """
660
661 mod_name, mod_fn = self.new_module(
662 """
663 x = 9
664
665 z = 123 # this item will be deleted
666
667 def foo(y):
668 return y + 3
669
670 class Baz(object):
671 def __init__(self, x):
672 self.x = x
673 def bar(self, y):
674 return self.x + y
675 @property
676 def quux(self):
677 return 42
678 def zzz(self):
679 '''This method will be deleted below'''
680 return 99
681
682 class Bar: # old-style class: weakref doesn't work for it on Python < 2.7
683 def foo(self):
684 return 1
685 """
686 )
687
688 #
689 # Import module, and mark for reloading
690 #
691 if use_aimport:
692 self.shell.magic_autoreload("1")
693 self.shell.magic_aimport(mod_name)
694 stream = StringIO()
695 self.shell.magic_aimport("", stream=stream)
696 self.assertIn(("Modules to reload:\n%s" % mod_name), stream.getvalue())
697
698 with self.assertRaises(ImportError):
699 self.shell.magic_aimport("tmpmod_as318989e89ds")
700 else:
701 self.shell.magic_autoreload("2")
702 self.shell.run_code("import %s" % mod_name)
703 stream = StringIO()
704 self.shell.magic_aimport("", stream=stream)
705 self.assertTrue(
706 "Modules to reload:\nall-except-skipped" in stream.getvalue()
707 )
708 self.assertIn(mod_name, self.shell.ns)
709
710 mod = sys.modules[mod_name]
711
712 #
713 # Test module contents
714 #
715 old_foo = mod.foo
716 old_obj = mod.Baz(9)
717 old_obj2 = mod.Bar()
718
719 def check_module_contents():
720 self.assertEqual(mod.x, 9)
721 self.assertEqual(mod.z, 123)
722
723 self.assertEqual(old_foo(0), 3)
724 self.assertEqual(mod.foo(0), 3)
725
726 obj = mod.Baz(9)
727 self.assertEqual(old_obj.bar(1), 10)
728 self.assertEqual(obj.bar(1), 10)
729 self.assertEqual(obj.quux, 42)
730 self.assertEqual(obj.zzz(), 99)
731
732 obj2 = mod.Bar()
733 self.assertEqual(old_obj2.foo(), 1)
734 self.assertEqual(obj2.foo(), 1)
735
736 check_module_contents()
737
738 #
739 # Simulate a failed reload: no reload should occur and exactly
740 # one error message should be printed
741 #
742 self.write_file(
743 mod_fn,
744 """
745 a syntax error
746 """,
747 )
748
749 with tt.AssertPrints(
750 ("[autoreload of %s failed:" % mod_name), channel="stderr"
751 ):
752 self.shell.run_code("pass") # trigger reload
753 with tt.AssertNotPrints(
754 ("[autoreload of %s failed:" % mod_name), channel="stderr"
755 ):
756 self.shell.run_code("pass") # trigger another reload
757 check_module_contents()
758
759 #
760 # Rewrite module (this time reload should succeed)
761 #
762 self.write_file(
763 mod_fn,
764 """
765 x = 10
766
767 def foo(y):
768 return y + 4
769
770 class Baz(object):
771 def __init__(self, x):
772 self.x = x
773 def bar(self, y):
774 return self.x + y + 1
775 @property
776 def quux(self):
777 return 43
778
779 class Bar: # old-style class
780 def foo(self):
781 return 2
782 """,
783 )
784
785 def check_module_contents():
786 self.assertEqual(mod.x, 10)
787 self.assertFalse(hasattr(mod, "z"))
788
789 self.assertEqual(old_foo(0), 4) # superreload magic!
790 self.assertEqual(mod.foo(0), 4)
791
792 obj = mod.Baz(9)
793 self.assertEqual(old_obj.bar(1), 11) # superreload magic!
794 self.assertEqual(obj.bar(1), 11)
795
796 self.assertEqual(old_obj.quux, 43)
797 self.assertEqual(obj.quux, 43)
798
799 self.assertFalse(hasattr(old_obj, "zzz"))
800 self.assertFalse(hasattr(obj, "zzz"))
801
802 obj2 = mod.Bar()
803 self.assertEqual(old_obj2.foo(), 2)
804 self.assertEqual(obj2.foo(), 2)
805
806 self.shell.run_code("pass") # trigger reload
807 check_module_contents()
808
809 #
810 # Another failure case: deleted file (shouldn't reload)
811 #
812 os.unlink(mod_fn)
813
814 self.shell.run_code("pass") # trigger reload
815 check_module_contents()
816
817 #
818 # Disable autoreload and rewrite module: no reload should occur
819 #
820 if use_aimport:
821 self.shell.magic_aimport("-" + mod_name)
822 stream = StringIO()
823 self.shell.magic_aimport("", stream=stream)
824 self.assertTrue(("Modules to skip:\n%s" % mod_name) in stream.getvalue())
825
826 # This should succeed, although no such module exists
827 self.shell.magic_aimport("-tmpmod_as318989e89ds")
828 else:
829 self.shell.magic_autoreload("0")
830
831 self.write_file(
832 mod_fn,
833 """
834 x = -99
835 """,
836 )
837
838 self.shell.run_code("pass") # trigger reload
839 self.shell.run_code("pass")
840 check_module_contents()
841
842 #
843 # Re-enable autoreload: reload should now occur
844 #
845 if use_aimport:
846 self.shell.magic_aimport(mod_name)
847 else:
848 self.shell.magic_autoreload("")
849
850 self.shell.run_code("pass") # trigger reload
851 self.assertEqual(mod.x, -99)
852
853 def test_smoketest_aimport(self):
854 self._check_smoketest(use_aimport=True)
855
856 def test_smoketest_autoreload(self):
857 self._check_smoketest(use_aimport=False)
858
859 def test_autoreload_with_user_defined_In_variable(self):
860 """
861 Check that autoreload works when the user has defined an In variable.
862 """
863 mod_name, mod_fn = self.new_module(
864 textwrap.dedent(
865 """
866 def hello():
867 return "Hello"
868 """
869 )
870 )
871 self.shell.magic_autoreload("2")
872 self.shell.run_code(f"import {mod_name}")
873 self.shell.run_code(f"res = {mod_name}.hello()")
874 assert self.shell.user_ns["res"] == "Hello"
875
876 self.shell.user_ns["In"] = "some_value"
877
878 self.write_file(
879 mod_fn,
880 textwrap.dedent(
881 """
882 def hello():
883 return "Changed"
884 """
885 ),
886 )
887
888 self.shell.run_code(f"res = {mod_name}.hello()")
889 assert self.shell.user_ns["res"] == "Changed"
890
891 def test_import_from_tracker_conflict_resolution(self):
892 """Test that ImportFromTracker properly handles import conflicts"""
893 from IPython.extensions.autoreload import ImportFromTracker
894 from unittest.mock import Mock
895
896 # Create a test module with both 'foo' and 'bar' attributes
897 mod_name, mod_fn = self.new_module(
898 textwrap.dedent(
899 """
900 foo = "original_foo"
901 bar = "original_bar"
902 """
903 )
904 )
905
906 # Mock the module in sys.modules instead of actually importing it
907 mock_module = Mock()
908 mock_module.foo = "original_foo"
909 mock_module.bar = "original_bar"
910 sys.modules[mod_name] = mock_module
911
912 try:
913 # Create a tracker
914 tracker = ImportFromTracker({}, {})
915
916 # Test case 1: "from x import y as z" then "from x import z"
917 # First import: from mod_name import foo as bar
918 tracker.add_import(mod_name, "foo", "bar")
919
920 # Verify initial state
921 assert mod_name in tracker.imports_froms
922 assert "foo" in tracker.imports_froms[mod_name]
923 assert tracker.symbol_map[mod_name]["foo"] == ["bar"]
924
925 # Second import: from mod_name import bar (conflicts with previous "bar")
926 tracker.add_import(mod_name, "bar", "bar")
927
928 # The second import should take precedence since "bar" is a valid import
929 assert "bar" in tracker.imports_froms[mod_name]
930 assert "foo" not in tracker.imports_froms[mod_name] # Should be removed
931 assert tracker.symbol_map[mod_name]["bar"] == ["bar"]
932 assert "foo" not in tracker.symbol_map[mod_name] # Should be removed
933 finally:
934 # Clean up sys.modules
935 if mod_name in sys.modules:
936 del sys.modules[mod_name]
937
938 def test_import_from_tracker_reverse_conflict(self):
939 """Test the reverse case: 'from x import z' then 'from x import y as z'"""
940 from IPython.extensions.autoreload import ImportFromTracker
941 from unittest.mock import Mock
942
943 # Create a test module
944 mod_name, mod_fn = self.new_module(
945 textwrap.dedent(
946 """
947 foo = "original_foo"
948 bar = "original_bar"
949 """
950 )
951 )
952
953 # Mock the module in sys.modules instead of actually importing it
954 mock_module = Mock()
955 mock_module.foo = "original_foo"
956 mock_module.bar = "original_bar"
957 sys.modules[mod_name] = mock_module
958
959 try:
960 # Create a tracker
961 tracker = ImportFromTracker({}, {})
962
963 # First import: from mod_name import bar
964 tracker.add_import(mod_name, "bar", "bar")
965
966 # Verify initial state
967 assert "bar" in tracker.imports_froms[mod_name]
968 assert tracker.symbol_map[mod_name]["bar"] == ["bar"]
969
970 # Second import: from mod_name import foo as bar (conflicts with previous "bar")
971 tracker.add_import(mod_name, "foo", "bar")
972
973 # The second import should take precedence since "foo" is a valid import
974 assert "foo" in tracker.imports_froms[mod_name]
975 assert "bar" not in tracker.imports_froms[mod_name] # Should be removed
976 assert tracker.symbol_map[mod_name]["foo"] == ["bar"]
977 assert "bar" not in tracker.symbol_map[mod_name] # Should be removed
978 finally:
979 # Clean up sys.modules
980 if mod_name in sys.modules:
981 del sys.modules[mod_name]
982
983 def test_import_from_tracker_invalid_import(self):
984 """Test that ImportFromTracker works correctly with the post-execution approach"""
985 from IPython.extensions.autoreload import ImportFromTracker
986
987 # Create a test module with only 'foo' attribute
988 mod_name, mod_fn = self.new_module(
989 textwrap.dedent(
990 """
991 foo = "original_foo"
992 """
993 )
994 )
995
996 # Create a tracker
997 tracker = ImportFromTracker({}, {})
998
999 # First import: from mod_name import foo as bar
1000 # Since we're simulating post-execution, this is a valid import
1001 tracker.add_import(mod_name, "foo", "bar")
1002
1003 # Verify initial state
1004 assert "foo" in tracker.imports_froms[mod_name]
1005 assert tracker.symbol_map[mod_name]["foo"] == ["bar"]
1006
1007 # Second import: from mod_name import foo2 as bar (conflicting import)
1008 # In the new approach, this would only be called if the import actually succeeded
1009 # So this represents a case where the module was updated to have foo2
1010 tracker.add_import(mod_name, "foo2", "bar")
1011
1012 # The new mapping should replace the old one since it's more recent
1013 assert "foo2" in tracker.imports_froms[mod_name]
1014 assert "foo" not in tracker.imports_froms[mod_name] # Should be replaced
1015 assert tracker.symbol_map[mod_name]["foo2"] == ["bar"]
1016 assert "foo" not in tracker.symbol_map[mod_name] # Should be replaced
1017
1018 def test_import_from_tracker_integration(self):
1019 """Test the integration of ImportFromTracker with autoreload"""
1020 # Create a test module
1021 mod_name, mod_fn = self.new_module(
1022 textwrap.dedent(
1023 """
1024 foo = "original_foo"
1025 bar = "original_bar"
1026 """
1027 )
1028 )
1029
1030 # Enable autoreload mode 3 (complete)
1031 self.shell.magic_autoreload("3")
1032
1033 # First import: from mod_name import foo as bar
1034 # This will naturally load the module into sys.modules
1035 self.shell.run_code(f"from {mod_name} import foo as bar")
1036 assert self.shell.user_ns["bar"] == "original_foo"
1037
1038 # Second import: from mod_name import bar (should override the alias)
1039 # The module is already in sys.modules, so this should work with our validation
1040 self.shell.run_code(f"from {mod_name} import bar")
1041 assert self.shell.user_ns["bar"] == "original_bar" # Should now be the real bar
1042
1043 # Modify the module
1044 self.write_file(
1045 mod_fn,
1046 textwrap.dedent(
1047 """
1048 foo = "modified_foo"
1049 bar = "modified_bar"
1050 """
1051 ),
1052 )
1053
1054 # Trigger autoreload by running any code
1055 self.shell.run_code("x = 1")
1056
1057 # The 'bar' variable should now contain the modified 'bar', not 'foo'
1058 assert self.shell.user_ns["bar"] == "modified_bar"
1059
1060 def test_autoreload3_double_import(self):
1061 """Test the integration of ImportFromTracker with autoreload"""
1062 # Create a test module
1063 mod_name, mod_fn = self.new_module(
1064 textwrap.dedent(
1065 """
1066 foo = "original_foo"
1067 bar = "original_bar"
1068 """
1069 )
1070 )
1071 # Enable autoreload mode 3 (complete)
1072 self.shell.magic_autoreload("3")
1073
1074 # First import: from mod_name import foo as bar
1075 # This will naturally load the module into sys.modules
1076 self.shell.run_code(f"from {mod_name} import foo as bar")
1077 self.shell.run_code(f"from {mod_name} import foo")
1078 assert self.shell.user_ns["bar"] == "original_foo"
1079 assert self.shell.user_ns["foo"] == "original_foo"
1080 # Modify the module
1081 self.write_file(
1082 mod_fn,
1083 textwrap.dedent(
1084 """
1085 foo = "modified_foo"
1086 bar = "modified_bar"
1087 """
1088 ),
1089 )
1090 self.shell.run_code("pass")
1091 assert self.shell.user_ns["bar"] == "modified_foo"
1092 assert self.shell.user_ns["foo"] == "modified_foo"
1093
1094 def test_import_from_tracker_unloaded_module(self):
1095 """Test that ImportFromTracker works with the post-execution approach"""
1096 from IPython.extensions.autoreload import ImportFromTracker
1097
1098 # With the new approach, we only track imports after successful execution
1099 # So even if a module isn't initially in sys.modules, if an import executed
1100 # successfully, we should track it
1101
1102 fake_mod_name = "test_module_12345"
1103
1104 # Create a tracker
1105 tracker = ImportFromTracker({}, {})
1106
1107 # Simulate an import that executed successfully
1108 # (In reality, this would only be called if the import actually succeeded)
1109 tracker.add_import(fake_mod_name, "some_attr", "some_name")
1110
1111 # Since the import "succeeded", it should be tracked
1112 assert fake_mod_name in tracker.imports_froms
1113 assert fake_mod_name in tracker.symbol_map
1114 assert "some_attr" in tracker.imports_froms[fake_mod_name]
1115 assert tracker.symbol_map[fake_mod_name]["some_attr"] == ["some_name"]
1116
1117 # Simulate a conflict scenario - another import succeeded
1118 tracker.add_import(fake_mod_name, "another_attr", "some_name")
1119
1120 # The newer import should replace the older one
1121 assert fake_mod_name in tracker.imports_froms
1122 assert fake_mod_name in tracker.symbol_map
1123 assert "another_attr" in tracker.imports_froms[fake_mod_name]
1124 assert (
1125 "some_attr" not in tracker.imports_froms[fake_mod_name]
1126 ) # Should be replaced
1127 assert tracker.symbol_map[fake_mod_name]["another_attr"] == ["some_name"]
1128 assert (
1129 "some_attr" not in tracker.symbol_map[fake_mod_name]
1130 ) # Should be replaced
1131
1132 def test_import_from_tracker_multiple_resolved_names(self):
1133 """Test that the same original name can map to multiple resolved names"""
1134 from IPython.extensions.autoreload import ImportFromTracker
1135
1136 # Create a tracker
1137 tracker = ImportFromTracker({}, {})
1138
1139 fake_mod_name = "test_module_abc"
1140
1141 # Simulate: from test_module_abc import foo as bar
1142 tracker.add_import(fake_mod_name, "foo", "bar")
1143
1144 # Verify initial state
1145 assert "foo" in tracker.imports_froms[fake_mod_name]
1146 assert tracker.symbol_map[fake_mod_name]["foo"] == ["bar"]
1147
1148 # Simulate: from test_module_abc import foo (same original name, different resolved name)
1149 tracker.add_import(fake_mod_name, "foo", "foo")
1150
1151 # Both resolved names should be tracked for the same original name
1152 assert "foo" in tracker.imports_froms[fake_mod_name]
1153 assert set(tracker.symbol_map[fake_mod_name]["foo"]) == {"bar", "foo"}