Skip to content

Commit

Permalink
Merge pull request #3206 from mbachry/fix-unittest-mock
Browse files Browse the repository at this point in the history
Fix mock patchings detection when both mock and unittest.mock are present
  • Loading branch information
nicoddemus committed Feb 15, 2018
2 parents e7bcc85 + b6166dc commit 371eb8c
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
7 changes: 4 additions & 3 deletions _pytest/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,11 @@ def num_mock_patch_args(function):
patchings = getattr(function, "patchings", None)
if not patchings:
return 0
mock = sys.modules.get("mock", sys.modules.get("unittest.mock", None))
if mock is not None:
mock_modules = [sys.modules.get("mock"), sys.modules.get("unittest.mock")]
if any(mock_modules):
sentinels = [m.DEFAULT for m in mock_modules if m is not None]
return len([p for p in patchings
if not p.attribute_name and p.new is mock.DEFAULT])
if not p.attribute_name and p.new in sentinels])
return len(patchings)


Expand Down
1 change: 1 addition & 0 deletions changelog/3206.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Detect arguments injected by ``unittest.mock.patch`` decorator correctly when pypi ``mock.patch`` is installed and imported.
22 changes: 22 additions & 0 deletions testing/python/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,28 @@ def test_hello(inject_me):
reprec = testdir.inline_run()
reprec.assertoutcome(passed=1)

def test_unittest_mock_and_pypi_mock(self, testdir):
pytest.importorskip("unittest.mock")
pytest.importorskip("mock", "1.0.1")
testdir.makepyfile("""
import mock
import unittest.mock
class TestBoth(object):
@unittest.mock.patch("os.path.abspath")
def test_hello(self, abspath):
import os
os.path.abspath("hello")
abspath.assert_any_call("hello")
@mock.patch("os.path.abspath")
def test_hello_mock(self, abspath):
import os
os.path.abspath("hello")
abspath.assert_any_call("hello")
""")
reprec = testdir.inline_run()
reprec.assertoutcome(passed=2)

def test_mock(self, testdir):
pytest.importorskip("mock", "1.0.1")
testdir.makepyfile("""
Expand Down

0 comments on commit 371eb8c

Please sign in to comment.