pytest-mock: xxx() missing 1 required positional argument: 'mocker'

I’m using pytest 5.3.0 with pytest-mock 1.12.1, and in a pytest class I want to temporarily mock a function of an object returned by some other module function. When I use test_calls_operation(mocker) outside a test class, then the mocker arg gets filled in by pytest-mock as expected. However, when I declare the test as shown below, I get test_calls_operation() missing 1 required positional argument: 'mocker'. What am I doing wrong? I sifted through the documentation and especially StackOverflow, but I seem to miss the knack of getting the mocker arg` automatically set as needed.

class KeysModuleTests(TestCase):
    def test_calls_operation(self, mocker):
        keys = mnt.keys.end()
        mocker.spy(keys, 'op_end')
        # ...

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 17 (7 by maintainers)

Commits related to this issue

Most upvoted comments

@TheDiveO

pytest fixtures cannot be used in unittest.TestCase test methods. The unittest integration in pytest uses the unittest Runner to actually run the tests, and the unittest runner doesn’t know about fixtures (this applies to any fixture, not only mocker).

One workaround is to use an autouse fixture (which work un unittest.TestCase subclasses) to obtain the fixture you are interested in, then use it later. Example:


class KeysModuleTests(TestCase):

    @pytest.fixture(autouse=True)
    def __inject_fixtures(self, mocker):
        self.mocker = mocker

    def test_calls_operation(self):
        keys = mnt.keys.end()
        self.mocker.spy(keys, 'op_end')
        # ...

Closing for now but feel free to follow up with further questions.

It returns missing 1 required positional argument 😔

Just in case others find this issue, I’ve wrapped your workaround slightly differently in a simple fixture, so I can either use it on a class or a single method using @pytest.mark.usefixtures('mocka'):

@pytest.fixture(scope='function')
def mocka(request, mocker):
    """Exposes pytest-mock's "mocker" as "self.mocker" in
    unittest.TestCase-based tests.
    """
    request.instance.mocker = mocker

Thank you again for setting me on the right track!