Skip to content

Commit edb4631

Browse files
committed
adding support for patch.object
1 parent f7080a3 commit edb4631

File tree

1 file changed

+39
-13
lines changed

1 file changed

+39
-13
lines changed

test_pytest_mock.py

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,35 @@ class MockFixture(object):
77

88
def __init__(self):
99
self._patches = []
10-
self.patch = self._PatchWrapper(self._patches)
10+
self.patch = self._Patcher(self._patches)
1111

1212
def stopall(self):
1313
for p in self._patches:
1414
p.stop()
1515
self._patches[:] = []
1616

17-
class _PatchWrapper(object):
18-
17+
class _Patcher(object):
1918
def __init__(self, patches):
2019
self._patches = patches
2120

2221
def object(self, *args, **kwargs):
2322
import mock
23+
2424
p = mock.patch.object(*args, **kwargs)
2525
mocked = p.start()
2626
self._patches.append(p)
2727
return mocked
2828

2929

30+
def __call__(self, *args, **kwargs):
31+
import mock
32+
33+
p = mock.patch(*args, **kwargs)
34+
mocked = p.start()
35+
self._patches.append(p)
36+
return mocked
37+
38+
3039
@pytest.yield_fixture
3140
def mock():
3241
result = MockFixture()
@@ -35,7 +44,6 @@ def mock():
3544

3645

3746
class UnixFS(object):
38-
3947
@classmethod
4048
def rm(cls, filename):
4149
os.remove(filename)
@@ -45,12 +53,30 @@ def ls(cls, path):
4553
return os.listdir(path)
4654

4755

48-
def test_fixture(mock, tmpdir):
49-
mock.patch.object(os, 'remove')
50-
(tmpdir / 'foo.txt').ensure()
51-
UnixFS.rm(tmpdir / 'foo.txt')
52-
os.remove.assert_called_once_with(tmpdir / 'foo.txt')
53-
assert os.path.isfile(str(tmpdir / 'foo.txt'))
54-
mock.stopall()
55-
UnixFS.rm(str(tmpdir / 'foo.txt'))
56-
assert not os.path.isfile(str(tmpdir / 'foo.txt'))
56+
@pytest.fixture
57+
def check_unix_fs_mocked(tmpdir, mock):
58+
def check(mocked_rm):
59+
(tmpdir / 'foo.txt').ensure()
60+
UnixFS.rm(tmpdir / 'foo.txt')
61+
os.remove.assert_called_once_with(tmpdir / 'foo.txt')
62+
mocked_rm.assert_called_once_with(tmpdir / 'foo.txt')
63+
assert os.path.isfile(str(tmpdir / 'foo.txt'))
64+
mock.stopall()
65+
UnixFS.rm(str(tmpdir / 'foo.txt'))
66+
assert not os.path.isfile(str(tmpdir / 'foo.txt'))
67+
68+
return check
69+
70+
71+
def mock_using_patch_object(mock):
72+
return mock.patch.object(os, 'remove')
73+
74+
def mock_using_patch(mock):
75+
return mock.patch('os.remove')
76+
77+
@pytest.mark.parametrize('mock_fs', [mock_using_patch_object, mock_using_patch],
78+
)
79+
def test_fixture(mock_fs, mock, check_unix_fs_mocked):
80+
mocked_rm = mock_fs(mock)
81+
#mocked_rm = mock.patch(os, 'remove')
82+
check_unix_fs_mocked(mocked_rm)

0 commit comments

Comments
 (0)