Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: pytest-dev/pytest-mock
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v3.11.1
Choose a base ref
...
head repository: pytest-dev/pytest-mock
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v3.12.0
Choose a head ref

Commits on Jun 16, 2023

  1. Fix gen-release-notes.py script

    Something changed in the RST->md conversion since the script was written,
    so fixed the script by trimming the releases based on the RST file instead,
    which we control.
    nicoddemus committed Jun 16, 2023
    Copy the full SHA
    b8ca8a6 View commit details
  2. Merge pull request #367 from pytest-dev/release-3.11.0

    Release 3.11.0
    nicoddemus authored Jun 16, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f8b85bf View commit details
  3. Add 3.11.0 manually to CHANGELOG

    Fix #368
    nicoddemus authored Jun 16, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f1f2c49 View commit details
  4. Merge pull request #369 from pytest-dev/test-me-3.11.0-changelog

    Add 3.11.0 manually to CHANGELOG
    nicoddemus authored Jun 16, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    4395c2b View commit details

Commits on Jun 20, 2023

  1. [pre-commit.ci] pre-commit autoupdate (#370)

    updates:
    - [github.com/asottile/reorder-python-imports: v3.9.0 → v3.10.0](asottile/reorder-python-imports@v3.9.0...v3.10.0)
    
    Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
    pre-commit-ci[bot] authored Jun 20, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    bc7644d View commit details

Commits on Jun 27, 2023

  1. [pre-commit.ci] pre-commit autoupdate (#371)

    updates:
    - [github.com/pre-commit/mirrors-mypy: v1.3.0 → v1.4.1](pre-commit/mirrors-mypy@v1.3.0...v1.4.1)
    
    Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
    pre-commit-ci[bot] authored Jun 27, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    2d4fb6b View commit details

Commits on Jul 11, 2023

  1. [pre-commit.ci] pre-commit autoupdate (#373)

    updates:
    - [github.com/psf/black: 23.3.0 → 23.7.0](psf/black@23.3.0...23.7.0)
    
    Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
    pre-commit-ci[bot] authored Jul 11, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    d5243b0 View commit details

Commits on Aug 15, 2023

  1. [pre-commit.ci] pre-commit autoupdate (#377)

    updates:
    - [github.com/pre-commit/mirrors-mypy: v1.4.1 → v1.5.0](pre-commit/mirrors-mypy@v1.4.1...v1.5.0)
    
    Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
    pre-commit-ci[bot] authored Aug 15, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    234e167 View commit details

Commits on Aug 25, 2023

  1. [pre-commit.ci] pre-commit autoupdate (#379)

    updates:
    - [github.com/pre-commit/mirrors-mypy: v1.5.0 → v1.5.1](pre-commit/mirrors-mypy@v1.5.0...v1.5.1)
    
    Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
    pre-commit-ci[bot] authored Aug 25, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f59c72a View commit details

Commits on Sep 12, 2023

  1. [pre-commit.ci] pre-commit autoupdate (#381)

    updates:
    - [github.com/psf/black: 23.7.0 → 23.9.1](psf/black@23.7.0...23.9.1)
    
    Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
    pre-commit-ci[bot] authored Sep 12, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    4118e33 View commit details

Commits on Sep 13, 2023

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    0c35b65 View commit details

Commits on Sep 19, 2023

  1. [pre-commit.ci] pre-commit autoupdate (#384)

    updates:
    - [github.com/asottile/reorder-python-imports: v3.10.0 → v3.11.0](asottile/reorder-python-imports@v3.10.0...v3.11.0)
    
    Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
    pre-commit-ci[bot] authored Sep 19, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    9a9f2b6 View commit details

Commits on Oct 3, 2023

  1. [pre-commit.ci] pre-commit autoupdate

    updates:
    - [github.com/asottile/reorder-python-imports: v3.11.0 → v3.12.0](asottile/reorder-python-imports@v3.11.0...v3.12.0)
    pre-commit-ci[bot] authored Oct 3, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    93bb304 View commit details
  2. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    2779825 View commit details
  3. Merge pull request #385 from pytest-dev/pre-commit-ci-update-config

    [pre-commit.ci] pre-commit autoupdate
    nicoddemus authored Oct 3, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    91229f9 View commit details

Commits on Oct 6, 2023

  1. Add "where to patch" link to the docs

    As #386 shows, this is a common problem, so add a link to the docs to help users.
    nicoddemus authored Oct 6, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    ea1d0a6 View commit details
  2. Update usage.rst

    nicoddemus authored Oct 6, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    53cc0a5 View commit details

Commits on Oct 7, 2023

  1. Update usage.rst

    nicoddemus authored Oct 7, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    cec59a0 View commit details

Commits on Oct 9, 2023

  1. [pre-commit.ci] pre-commit autoupdate

    updates:
    - [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.5.0](pre-commit/pre-commit-hooks@v4.4.0...v4.5.0)
    pre-commit-ci[bot] authored Oct 9, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f55f17e View commit details

Commits on Oct 10, 2023

  1. Merge pull request #388 from pytest-dev/pre-commit-ci-update-config

    [pre-commit.ci] pre-commit autoupdate
    nicoddemus authored Oct 10, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    09f1814 View commit details

Commits on Oct 13, 2023

  1. Merge pull request #387 from pytest-dev/where-to-patch-link

    Add "where to patch" link to the docs
    nicoddemus authored Oct 13, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f019696 View commit details

Commits on Oct 16, 2023

  1. [pre-commit.ci] pre-commit autoupdate

    updates:
    - [github.com/pre-commit/mirrors-mypy: v1.5.1 → v1.6.0](pre-commit/mirrors-mypy@v1.5.1...v1.6.0)
    pre-commit-ci[bot] authored Oct 16, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    e037221 View commit details

Commits on Oct 17, 2023

  1. Merge pull request #391 from pytest-dev/pre-commit-ci-update-config

    [pre-commit.ci] pre-commit autoupdate
    nicoddemus authored Oct 17, 2023

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    e84f885 View commit details

Commits on Oct 19, 2023

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    2a71a0d View commit details
  2. Copy the full SHA
    b905823 View commit details
  3. Re-add norewrite tests

    nicoddemus committed Oct 19, 2023
    Copy the full SHA
    69adc6f View commit details
Showing with 145 additions and 62 deletions.
  1. +8 −11 .github/workflows/test.yml
  2. +4 −4 .pre-commit-config.yaml
  3. +15 −0 .readthedocs.yml
  4. +21 −0 CHANGELOG.rst
  5. +0 −20 docs/remarks.rst
  6. +30 −0 docs/usage.rst
  7. +30 −19 scripts/gen-release-notes.py
  8. +2 −2 setup.py
  9. +11 −2 src/pytest_mock/plugin.py
  10. +21 −1 tests/test_pytest_mock.py
  11. +3 −3 tox.ini
19 changes: 8 additions & 11 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -31,19 +31,16 @@ jobs:
strategy:
fail-fast: false
matrix:
python: ["3.7", "3.8", "3.9", "3.10", "3.11"]
python: ["3.8", "3.9", "3.10", "3.11", "3.12"]
os: [ubuntu-latest, windows-latest]
tox_env: ["py"]
include:
- python: "3.7"
tox_env: "py37"
- python: "3.8"
tox_env: "py38"
- python: "3.9"
tox_env: "py39"
- python: "3.10"
tox_env: "py310"
- python: "3.11"
tox_env: "py311"
- python: "3.12"
os: ubuntu-latest
tox_env: "norewrite"
- python: "3.12"
os: windows-latest
tox_env: "norewrite"

steps:
- uses: actions/checkout@v3
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
exclude: '^($|.*\.bin)'
repos:
- repo: https://github.com/psf/black
rev: 23.3.0
rev: 23.9.1
hooks:
- id: black
args: [--safe, --quiet]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
@@ -19,12 +19,12 @@ repos:
language: python
additional_dependencies: [pygments, restructuredtext_lint]
- repo: https://github.com/asottile/reorder-python-imports
rev: v3.9.0
rev: v3.12.0
hooks:
- id: reorder-python-imports
args: ['--application-directories=.:src']
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.3.0 # NOTE: keep this in sync with tox.ini
rev: v1.6.0 # NOTE: keep this in sync with tox.ini
hooks:
- id: mypy
files: ^(src|tests)
15 changes: 15 additions & 0 deletions .readthedocs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
version: 2

build:
os: ubuntu-22.04
tools:
python: "3.11"

sphinx:
configuration: docs/conf.py
fail_on_warning: true

python:
install:
- requirements: docs/requirements.txt
- path: .
21 changes: 21 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,9 +1,30 @@
Releases
========

3.12.0 (2023-10-19)
-------------------

* Added support for Python 3.12.
* Dropped support for EOL Python 3.7.
* ``mocker.resetall()`` now also resets mocks created by ``mocker.create_autospec`` (`#390`_).

.. _#390: https://github.com/pytest-dev/pytest-mock/pull/390

3.11.1 (2023-06-15)
-------------------

(This release source code is identical to ``3.11.0`` except a small internal fix to deployment/CI)

* Fixed introspection for failed ``assert_has_calls`` (`#365`_).

* Updated type annotations for ``mocker.patch`` and ``mocker.spy`` (`#364`_).

.. _#365: https://github.com/pytest-dev/pytest-mock/pull/365
.. _#364: https://github.com/pytest-dev/pytest-mock/pull/364

3.11.0 (2023-06-15)
-------------------

* Fixed introspection for failed ``assert_has_calls`` (`#365`_).

* Updated type annotations for ``mocker.patch`` and ``mocker.spy`` (`#364`_).
20 changes: 0 additions & 20 deletions docs/remarks.rst
Original file line number Diff line number Diff line change
@@ -100,23 +100,3 @@ to improve the flow of the test:
# ...
But this is arguably a little more complex than using ``pytest-mock``.

Usage as context manager
------------------------

Although mocker's API is intentionally the same as ``mock.patch``'s, its use
as context manager and function decorator is **not** supported through the
fixture:

.. code-block:: python
def test_context_manager(mocker):
a = A()
with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): # DO NOT DO THIS
assert a.doIt() == True
The purpose of this plugin is to make the use of context managers and
function decorators for mocking unnecessary, so it will emit a warning when used as such.

If you really intend to mock a context manager, ``mocker.patch.context_manager`` exists
which won't issue the above warning.
30 changes: 30 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
@@ -136,3 +136,33 @@ It may receive an optional name that is shown in its ``repr``, useful for debugg
.. seealso::

``async_stub`` method, which actually the same as ``stub`` but makes async stub.


Usage as context manager
------------------------

Although mocker's API is intentionally the same as ``mock.patch``'s, its use
as context manager and function decorator is **not** supported through the
fixture:

.. code-block:: python
def test_context_manager(mocker):
a = A()
with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): # DO NOT DO THIS
assert a.doIt() == True
The purpose of this plugin is to make the use of context managers and
function decorators for mocking unnecessary, so it will emit a warning when used as such.

If you really intend to mock a context manager, ``mocker.patch.context_manager`` exists
which won't issue the above warning.

Where to patch
--------------

A common issue where mocking appears not to be working is patching in the wrong place.

See this `section in the unittest docs <https://docs.python.org/3/library/unittest.mock.html#where-to-patch>`__ which provides a comprehensive explanation.

Also see this excellent blog post: `Why your mock doesn't work <https://nedbatchelder.com/blog/201908/why_your_mock_doesnt_work.html>`__.
49 changes: 30 additions & 19 deletions scripts/gen-release-notes.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,47 @@
"""
Generates the release notes for the latest release, in Markdown.
Convert CHANGELOG.rst to Markdown, and extracts just the latest release.
Writes to ``scripts/latest-release-notes.md``, which can be
used with https://github.com/softprops/action-gh-release.
1. Extracts the latest release from the CHANGELOG.rst file.
2. Converts it to Markdown using pypandoc.
3. Writes to ``scripts/latest-release-notes.md``, which can be
used with https://github.com/softprops/action-gh-release.
"""
from pathlib import Path

import pypandoc

this_dir = Path(__file__).parent
rst_text = (this_dir.parent / "CHANGELOG.rst").read_text(encoding="UTF-8")
md_text = pypandoc.convert_text(
rst_text, "md", format="rst", extra_args=["--wrap=preserve"]
)

output_lines = []
first_heading_found = False
for line in md_text.splitlines():
if line.startswith("# "):
# Skip the first section (normally # Releases).
pass
elif line.startswith("## "):
# First second-level section, note it and skip the text,
# as we are only interested in the individual release items.
if first_heading_found:
capture = False
for line in rst_text.splitlines():
# Only start capturing after the latest release section.
if line.startswith("-------"):
capture = not capture
if not capture:
# We only need to capture the latest release, so stop.
break
first_heading_found = True
else:
continue

if capture:
output_lines.append(line)

# Drop last line, as it contains the previous release section title.
del output_lines[-1]

trimmed_rst = "\n".join(output_lines).strip()
print(">>Trimmed RST follows:")
print(trimmed_rst)
print(">>Trimmed RST ends")

md_text = pypandoc.convert_text(
trimmed_rst, "md", format="rst", extra_args=["--wrap=preserve"]
)
print(">>Converted Markdown follows:")
print(md_text)
print(">>Converted Markdown ends")

output_fn = this_dir / "latest-release-notes.md"
output_fn.write_text("\n".join(output_lines), encoding="UTF-8")
output_fn.write_text(md_text, encoding="UTF-8")
print(output_fn, "generated.")
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@
package_data={
"pytest_mock": ["py.typed"],
},
python_requires=">=3.7",
python_requires=">=3.8",
install_requires=["pytest>=5.0"],
use_scm_version={"write_to": "src/pytest_mock/_version.py"},
setup_requires=["setuptools_scm"],
@@ -30,11 +30,11 @@
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Software Development :: Testing",
],
13 changes: 11 additions & 2 deletions src/pytest_mock/plugin.py
Original file line number Diff line number Diff line change
@@ -66,12 +66,20 @@ def __init__(self, config: Any) -> None:
self.call = mock_module.call
self.ANY = mock_module.ANY
self.DEFAULT = mock_module.DEFAULT
self.create_autospec = mock_module.create_autospec
self.sentinel = mock_module.sentinel
self.mock_open = mock_module.mock_open
if hasattr(mock_module, "seal"):
self.seal = mock_module.seal

def create_autospec(
self, spec: Any, spec_set: bool = False, instance: bool = False, **kwargs: Any
) -> MockType:
m: MockType = self.mock_module.create_autospec(
spec, spec_set, instance, **kwargs
)
self._patches_and_mocks.append((None, m))
return m

def resetall(
self, *, return_value: bool = False, side_effect: bool = False
) -> None:
@@ -102,7 +110,8 @@ def stopall(self) -> None:
times.
"""
for p, m in reversed(self._patches_and_mocks):
p.stop()
if p is not None:
p.stop()
self._patches_and_mocks.clear()

def stop(self, mock: unittest.mock.MagicMock) -> None:
22 changes: 21 additions & 1 deletion tests/test_pytest_mock.py
Original file line number Diff line number Diff line change
@@ -60,6 +60,15 @@ def ls(cls, path):
return os.listdir(path)


class TestObject:
"""
Class that is used for testing create_autospec with child mocks
"""

def run(self) -> str:
return "not mocked"


@pytest.fixture
def check_unix_fs_mocked(
tmpdir: Any, mocker: MockerFixture
@@ -156,7 +165,6 @@ def test_mock_patch_dict_resetall(mocker: MockerFixture) -> None:
[
"ANY",
"call",
"create_autospec",
"MagicMock",
"Mock",
"mock_open",
@@ -185,23 +193,35 @@ def test_mocker_resetall(mocker: MockerFixture) -> None:
listdir = mocker.patch("os.listdir", return_value="foo")
open = mocker.patch("os.open", side_effect=["bar", "baz"])

mocked_object = mocker.create_autospec(TestObject)
mocked_object.run.return_value = "mocked"

assert listdir("/tmp") == "foo"
assert open("/tmp/foo.txt") == "bar"
assert mocked_object.run() == "mocked"
listdir.assert_called_once_with("/tmp")
open.assert_called_once_with("/tmp/foo.txt")
mocked_object.run.assert_called_once()

mocker.resetall()

assert not listdir.called
assert not open.called
assert not mocked_object.called
assert listdir.return_value == "foo"
assert list(open.side_effect) == ["baz"]
assert mocked_object.run.return_value == "mocked"

mocker.resetall(return_value=True, side_effect=True)

assert isinstance(listdir.return_value, mocker.Mock)
assert open.side_effect is None

if sys.version_info >= (3, 9):
# The reset on child mocks have been implemented in 3.9
# https://bugs.python.org/issue38932
assert mocked_object.run.return_value != "mocked"


class TestMockerStub:
def test_call(self, mocker: MockerFixture) -> None:
6 changes: 3 additions & 3 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
[tox]
minversion = 3.5.3
envlist = py{37,38,39,310,311}, norewrite
envlist = py{38,39,310,311,312}, norewrite

[testenv]
deps =
coverage
mock
pytest-asyncio
commands =
coverage run --append --source={envsitepackagesdir}/pytest_mock -m pytest tests
coverage run --append --source={envsitepackagesdir}/pytest_mock -m pytest tests --color=yes

[testenv:norewrite]
commands =
pytest tests --assert=plain
pytest tests --assert=plain --color=yes

[pytest]
addopts = -r a