pytest-mock is a thin wrapper around mock.
mock is since python 3.3. actually the same as unittest.mock.
I don't know if mocker is another library, I only know it as the name of the fixture provided by pytest-mock to get mocking done in your tests.
I personally use pytest and pytest-mock for my tests, which allows you to write very concise tests like
from pytest_mock import MockerFixture
@pytest.fixture(autouse=True)
def something_to_be_mocked_everywhere(mocker):
mocker.patch()
def tests_this(mocker: MockerFixture):
mocker.patch ...
a_mock = mocker.Mock() ...
...
But this is mainly due to using fixtures, which is already pointed out is what pytest-mock offers.
Answer from Simon Hawe on Stack Overflowpython - What are the differences between unittest.mock, mock, mocker and pytest-mock? - Stack Overflow
pytest-mock : Mocking in pytest - Test & Code
pytest mock doesn't work as I expected
pytest mock
pytest-mock is a thin wrapper around mock.
mock is since python 3.3. actually the same as unittest.mock.
I don't know if mocker is another library, I only know it as the name of the fixture provided by pytest-mock to get mocking done in your tests.
I personally use pytest and pytest-mock for my tests, which allows you to write very concise tests like
from pytest_mock import MockerFixture
@pytest.fixture(autouse=True)
def something_to_be_mocked_everywhere(mocker):
mocker.patch()
def tests_this(mocker: MockerFixture):
mocker.patch ...
a_mock = mocker.Mock() ...
...
But this is mainly due to using fixtures, which is already pointed out is what pytest-mock offers.
@NelsonGon you can use the unittest mocks with pytest, e.g.
def test_app_uses_correct_transformer(monkeypatch):
mock_transformer = MagicMock()
mock_transformer.return_value = None
monkeypatch.setattr("app.transformer", mock_transformer)
https://testandcode.com/episodes/pytest-mock
pytest-mock is currently the #3 pytest plugin.
-
Why the pytest-mock plugin is awesome
-
What is mocking, patching, and monkey patching
-
What, if any, is the difference between mock, fake, spy, stub.
-
Why we might need these in testing
-
Some history of mock in Python and how mock became unittest.mock
-
Using mocker.patch, mocker.spy, and mocker.stub
-
Why pytest-mock is awesome and why you might want to use it over straight unittest.mock
Hi everyone, I am trying to mock a return value of a function using pytest mock. I have the following files:
# foo_bar.py
def foo():
return 5
def bar():
return foo()
# test_foo_bar.py
from pytest_mock import MockFixture
from foo_bar import bar, foo
def test_foo(mocker: MockFixture):
assert foo() == 5
mocker.patch("foo_bar.foo", return_value=10)
assert foo() == 10
def test_bar(mocker: MockFixture):
assert bar() == 5
mocker.patch("foo_bar.foo", return_value=10)
assert bar() == 10
When I run the above test, test_bar passes, but test_foo fails on assert foo() == 10
Why is it so? Thanks