Skip to content

Commit

Permalink
Update mock behaviour (#10207)
Browse files Browse the repository at this point in the history
* 解决了`DummyModule`在`isinstance`因为是实例而会报错的问题
* 为其增加`__enter__`和`__exit__`的报错
* 完成以上的unittest

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
Hank0626 and mergify[bot] authored Apr 28, 2023
1 parent 06ad76d commit d1a9e41
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions python/oneflow/mock_torch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand Down
18 changes: 18 additions & 0 deletions python/oneflow/test/misc/test_mock_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit d1a9e41

Please sign in to comment.