[issue39551] mock patch should match behavior of import from when module isn't present in sys.modules

Dino Viehland report at bugs.python.org
Thu Feb 6 16:27:50 EST 2020


Dino Viehland <dinoviehland at gmail.com> added the comment:

Sorry, publish may not necessarily be the best term.  When you do "from foo import bar" and foo is a package Python will set the bar module onto the foo module.  That leads to the common mistake of doing "import foo" and then "foo.bar.baz" and later removing the thing that do "from foo import bar" and having things blow up later.

Without additional support there's no way to patch the immutable module.  We can provide a mode where we enable the patching for testing and disable it in a production environment though.  That basically just involves passing a proxy object down to Mock.  And monkey patching the mutable module is perfectly fine.

The thing that's doing the ignoring of the assignment is the import system.  So it's now okay if the package raises an AttributeError.

There's not really a great way to work around this other than just bypassing mock's resolution of the object here - i.e. replacing mock.patch along with _get_target, _importer, and _dot_lookup and calling mock._patch directly, which isn't very nice (but is do-able).

And while this is a strange way to arrive at a module existing in sys.modules but not being on the package it is something that can happen in the normal course of imports, hence the reason why the import system handles this by checking sys.modules today.  It's also just turning what is currently an error while mocking into a success case with a simple few line change.

----------
stage: needs patch -> patch review

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39551>
_______________________________________


More information about the Python-bugs-list mailing list