Skip to content

Commit

Permalink
Use new way of mocking imports for tests (facebook#1574)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: facebook#1574

Instead of just mocking specific modules, mock modules and all of their children!  This saves more time and makes it harder for dependencies to sneak back in

Reviewed By: bernardbeckerman

Differential Revision: D44765973

fbshipit-source-id: d6ffd449fd3e310e824be0f3b0cb4248e3ab61c5
  • Loading branch information
Daniel Cohen authored and facebook-github-bot committed May 25, 2023
1 parent e41736b commit c320fe6
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion ax/utils/common/testutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""Support functions for tests
"""

import builtins
import contextlib
import io
import linecache
Expand Down Expand Up @@ -259,12 +260,23 @@ def _unequal_str(first: Any, second: Any) -> str: # pyre-ignore[2]


def setup_import_mocks(mocked_import_paths: List[str]) -> None:
# pyre-fixme[3]
def custom_import(name: str, *args: Any, **kwargs: Any) -> Any:
for import_path in mocked_import_paths:
if name == import_path or name.startswith(f"{import_path}."):
return MagicMock()
return original_import(name, *args, **kwargs)

for import_path in mocked_import_paths:
if import_path in sys.modules and not isinstance(
sys.modules[import_path], MagicMock
):
raise Exception(f"{import_path} has already been imported!")
sys.modules[import_path] = MagicMock()

# Replace the original import with the custom one
# pyre-fixme[61]
original_import = builtins.__import__
builtins.__import__ = custom_import


class TestCase(fake_filesystem_unittest.TestCase):
Expand Down

0 comments on commit c320fe6

Please sign in to comment.