jeudi 16 mai 2019

Mocking function imported at the top of the file

I am trying to do a test in a project, and I am having an weird error.

I reproduced the very similar situation with the toy example below:

This is the file structure:

.
├── some_package
│   ├── __init__.py
│   └── some_file.py
└── test_mock_patch.py

"""some_package/some_file.py"""

# when I import here, the test fails
from math import floor


def some_func(a, b):
    # if I import here, the test passes
    # from math import floor
    return floor(a + b)

"""test_mock_patch.py"""

import pytest
from unittest import mock
from some_package.some_file import some_func


@pytest.fixture
def mock_floor():
    with mock.patch('math.floor', autospec=True) as m:
        yield m


def test_some_func(mock_floor):
    some_func(1.1, 1)
    assert mock_floor.call_count == 1

Command used: pytest -v -s test_mock_patch.py

The error:

enter image description here

Why when I import inside the function the test_some_func passes and when I import at the top the test fails?

Thank you in advance for any help to explain this behaviour of mock.patch

Aucun commentaire:

Enregistrer un commentaire