Skip to content

unittest.mock's patch.multiple being interpreted as fixtures #8748

@jamesbraza

Description

@jamesbraza

From pytest's docs on unittest.TestCase support:

pytest supports running Python unittest-based tests out of the box.

However, I think I have a case where TestCase is not properly supported: unittest.mock's patch.multiple.

From the unittest.mock's docs on patch.multiple:

@patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
def test_function(thing, other):

You can break out the patches into args for a test function. However, this doesn't seem to work with pytest, as it interprets thing and other as fixtures.

Minimal Repro

from unittest import TestCase
from unittest.mock import DEFAULT, MagicMock, patch

class Foo:
    def bar(self) -> None:
        pass

class TestFoo1(TestCase):
    @patch.multiple(Foo, bar=DEFAULT)
    def test_patch_multiple(self, bar: MagicMock) -> None:
        """Works when subclassing TestCase."""

class TestFoo2:
    @patch.multiple(Foo, bar=DEFAULT)
    def test_patch_multiple(self, bar: MagicMock) -> None:
        """Fails when not subclassing TestCase."""

Here is the output when running pytest

patch_multiple.py::TestFoo2::test_patch_multiple ERROR                   [100%]
test setup failed
file /path/to/patch_multiple.py, line 14
      @patch.multiple(Foo, bar=DEFAULT)
      def test_patch_multiple(self, bar: MagicMock) -> None:
E       fixture 'bar' not found

By subclassing TestCase, pytest doesn't interpret bar as a fixture, and the test runs. Are there any known workarounds to stop pytest from interpreting bar as a fixture?

Versions

I am using macOS Catalina version 10.15.7.

Python==3.7.7
pytest==6.2.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: unittestrelated to the unittest integration builtin plugintopic: fixturesanything involving fixtures directly or indirectly

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions