diff --git a/python/oneflow/mock_torch/__init__.py b/python/oneflow/mock_torch/__init__.py index c7d23af95bc..a3ae2a048c0 100644 --- a/python/oneflow/mock_torch/__init__.py +++ b/python/oneflow/mock_torch/__init__.py @@ -248,6 +248,22 @@ def __bool__(self): ) return False + def __enter__(self): + raise RuntimeError( + f'"{self.__name__}" is a dummy object, and does not support "with" statement.' + ) + + def __exit__(self, exception_type, exception_value, traceback): + raise RuntimeError( + f'"{self.__name__}" is a dummy object, and does not support "with" statement.' + ) + + def __subclasscheck__(self, subclass): + return False + + def __instancecheck__(self, instance): + return False + class enable: def __init__( diff --git a/python/oneflow/test/misc/test_mock_scope.py b/python/oneflow/test/misc/test_mock_scope.py index 0a4c66a64b9..774be056bd6 100644 --- a/python/oneflow/test/misc/test_mock_scope.py +++ b/python/oneflow/test/misc/test_mock_scope.py @@ -180,6 +180,24 @@ def test_hazard_list(test_case): test_case.assertTrue("safetensors._safetensors_rust" in sys.modules) import safetensors + def test_isinstance(test_case): + with mock.enable(lazy=True): + import torch + + test_case.assertFalse(isinstance(int, torch._six.string_class)) + + def test_with_statement(test_case): + with mock.enable(lazy=True): + with test_case.assertRaises(RuntimeError) as context: + import torch.noexist + + with torch.noexist: + pass + test_case.assertTrue( + '"oneflow.noexist" is a dummy object, and does not support "with" statement.' + in str(context.exception) + ) + # MUST use pytest to run this test def test_verbose(capsys):