Skip to content

Commit 371eb8c

Browse files
authored
Merge pull request #3206 from mbachry/fix-unittest-mock
Fix mock patchings detection when both mock and unittest.mock are present
2 parents e7bcc85 + b6166dc commit 371eb8c

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

_pytest/compat.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,11 @@ def num_mock_patch_args(function):
7979
patchings = getattr(function, "patchings", None)
8080
if not patchings:
8181
return 0
82-
mock = sys.modules.get("mock", sys.modules.get("unittest.mock", None))
83-
if mock is not None:
82+
mock_modules = [sys.modules.get("mock"), sys.modules.get("unittest.mock")]
83+
if any(mock_modules):
84+
sentinels = [m.DEFAULT for m in mock_modules if m is not None]
8485
return len([p for p in patchings
85-
if not p.attribute_name and p.new is mock.DEFAULT])
86+
if not p.attribute_name and p.new in sentinels])
8687
return len(patchings)
8788

8889

changelog/3206.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Detect arguments injected by ``unittest.mock.patch`` decorator correctly when pypi ``mock.patch`` is installed and imported.

testing/python/integration.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,28 @@ def test_hello(inject_me):
147147
reprec = testdir.inline_run()
148148
reprec.assertoutcome(passed=1)
149149

150+
def test_unittest_mock_and_pypi_mock(self, testdir):
151+
pytest.importorskip("unittest.mock")
152+
pytest.importorskip("mock", "1.0.1")
153+
testdir.makepyfile("""
154+
import mock
155+
import unittest.mock
156+
class TestBoth(object):
157+
@unittest.mock.patch("os.path.abspath")
158+
def test_hello(self, abspath):
159+
import os
160+
os.path.abspath("hello")
161+
abspath.assert_any_call("hello")
162+
163+
@mock.patch("os.path.abspath")
164+
def test_hello_mock(self, abspath):
165+
import os
166+
os.path.abspath("hello")
167+
abspath.assert_any_call("hello")
168+
""")
169+
reprec = testdir.inline_run()
170+
reprec.assertoutcome(passed=2)
171+
150172
def test_mock(self, testdir):
151173
pytest.importorskip("mock", "1.0.1")
152174
testdir.makepyfile("""

0 commit comments

Comments
 (0)