7
7
from types import ModuleType
8
8
from typing import Any
9
9
from typing import Generator
10
+ from typing import Iterator
10
11
11
12
import pytest
12
13
from _pytest .monkeypatch import MonkeyPatch
@@ -282,29 +283,36 @@ def test_invalid_path(self, tmp_path: Path) -> None:
282
283
import_path (tmp_path / "invalid.py" , root = tmp_path )
283
284
284
285
@pytest .fixture
285
- def simple_module (self , tmp_path : Path ) -> Path :
286
- fn = tmp_path / "_src/tests/mymod.py"
286
+ def simple_module (
287
+ self , tmp_path : Path , request : pytest .FixtureRequest
288
+ ) -> Iterator [Path ]:
289
+ name = f"mymod_{ request .node .name } "
290
+ fn = tmp_path / f"_src/tests/{ name } .py"
287
291
fn .parent .mkdir (parents = True )
288
292
fn .write_text ("def foo(x): return 40 + x" , encoding = "utf-8" )
289
- return fn
293
+ module_name = module_name_from_path (fn , root = tmp_path )
294
+ yield fn
295
+ sys .modules .pop (module_name , None )
290
296
291
- def test_importmode_importlib (self , simple_module : Path , tmp_path : Path ) -> None :
297
+ def test_importmode_importlib (
298
+ self , simple_module : Path , tmp_path : Path , request : pytest .FixtureRequest
299
+ ) -> None :
292
300
"""`importlib` mode does not change sys.path."""
293
301
module = import_path (simple_module , mode = "importlib" , root = tmp_path )
294
302
assert module .foo (2 ) == 42 # type: ignore[attr-defined]
295
303
assert str (simple_module .parent ) not in sys .path
296
304
assert module .__name__ in sys .modules
297
- assert module .__name__ == "_src.tests.mymod "
305
+ assert module .__name__ == f "_src.tests.mymod_ { request . node . name } "
298
306
assert "_src" in sys .modules
299
307
assert "_src.tests" in sys .modules
300
308
301
- def test_importmode_twice_is_different_module (
309
+ def test_remembers_previous_imports (
302
310
self , simple_module : Path , tmp_path : Path
303
311
) -> None :
304
- """`importlib` mode always returns a new module."""
312
+ """`importlib` mode called remembers previous module (#10341, #10811) ."""
305
313
module1 = import_path (simple_module , mode = "importlib" , root = tmp_path )
306
314
module2 = import_path (simple_module , mode = "importlib" , root = tmp_path )
307
- assert module1 is not module2
315
+ assert module1 is module2
308
316
309
317
def test_no_meta_path_found (
310
318
self , simple_module : Path , monkeypatch : MonkeyPatch , tmp_path : Path
@@ -317,6 +325,9 @@ def test_no_meta_path_found(
317
325
# mode='importlib' fails if no spec is found to load the module
318
326
import importlib .util
319
327
328
+ # Force module to be re-imported.
329
+ del sys .modules [module .__name__ ]
330
+
320
331
monkeypatch .setattr (
321
332
importlib .util , "spec_from_file_location" , lambda * args : None
322
333
)
0 commit comments