Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Patch decorator is not compatible with pytest fixture

I have encountered something mysterious, when using patch decorator from mock package integrated with pytest fixture.

I have two modules:

    -----test folder           -------func.py           -------test_test.py 

in func.py:

    def a():         return 1      def b():         return a()      

in test_test.py:

    import pytest     from func import a,b     from mock import patch,Mock      @pytest.fixture(scope="module")     def brands():         return 1       mock_b=Mock()      @patch('test_test.b',mock_b)     def test_compute_scores(brands):                           a() 

It seems that patch decorate is not compatible with pytest fixture. Does anyone have a insight on that? Thanks

like image 721
Hello lad Avatar asked Jul 31 '14 11:07

Hello lad


People also ask

Is Pytest fixture a decorator?

pytest. fixture decorator makes it possible to inject the return value in the test functions whose have in their signature the decorated function name. Easy, isn't it? You can potentially generate and create everything you need in these fixture-functions and then use it in all the tests you need.

Can you import a Pytest fixture?

Use Pytest Fixtures Across Multiple Test Files With conftest.py. To make it easier on ourselves, we can define a fixture to use across multiple test files. These fixtures are defined by creating a file called conftest.py. Additionally, we can call separate files that also import the fixture from our configuration file.

What is mock Pytest?

In pytest , mocking can replace the return value of a function within a function. This is useful for testing the desired function and replacing the return value of a nested function within that desired function we are testing.


1 Answers

When using pytest fixture with mock.patch, test parameter order is crucial.

If you place a fixture parameter before a mocked one:

from unittest import mock  @mock.patch('my.module.my.class') def test_my_code(my_fixture, mocked_class): 

then the mock object will be in my_fixture and mocked_class will be search as a fixture:

fixture 'mocked_class' not found 

But, if you reverse the order, placing the fixture parameter at the end:

from unittest import mock  @mock.patch('my.module.my.class') def test_my_code(mocked_class, my_fixture): 

then all will be fine.

like image 59
bux Avatar answered Sep 21 '22 23:09

bux