- 
                Notifications
    
You must be signed in to change notification settings  - Fork 2
 
Open
Description
import time
from mock_examples.sleep_function import sleep_for_a_bit
def test_sleep_for_a_bit_with_mock(mocker):
    """
    Function to test sleep for a bit with mock
    :param mocker: pytest-mock fixture
    :return: None
    """
    mocker.patch("mock_examples.sleep_function.time")
    # mocker.patch("mock_examples.sleep_function.time.sleep")
    sleep_for_a_bit(duration=5)
    print(type(time), type(time.sleep))
    time.sleep.assert_called_once_with(
        5
    )  # check that time.sleep was called with the correct argument
2 changes
- I added 
print(type(time), type(time.sleep))to check which of them have been turned into a mock object. - I changed the patch from time.sleep (commented) to time (added above)
 
I can't understand why type(time.sleep) changed from
<class 'module'> <class 'unittest.mock.MagicMock'>to<class 'module'> <class 'builtin_function_or_method'>
Pytest was ran with pytest -vs tests/test_sleep.py
During mocker.patch("mock_examples.sleep_function.time"),
I expected time.sleep to become a MagicMock object too. I thought since the entire time module got patched, every attribute (eg. sleep) under time would also be patched too.
Questions
- Why is 
time.sleepa<class 'builtin_function_or_method'>(I assume it's the unpatched original) duringmocker.patch("mock_examples.sleep_function.time")? - Why is 
type(time)a<class 'module'>aftermocker.patch("mock_examples.sleep_function.time"), shouldn't it be a MagicMock? 
Improvements
I wish the article (https://pytest-with-eric.com/mocking/pytest-mocking/) explained Important Note — Mock an item where it is used, not where it came from.
- What are the implications?
 - Is this good practice or a matter of breaking the pytest-mock feature entirely?
 - What are the pitfalls, what happens when someone mocks an item where it came from?
 - Is it a problem interacting with other mechanics like python import system?
 - Do mocks work when we define both the function and the test_function in the same file so no imports?
 
Not rethoric questions, I really have no idea to the above. Hoping this issue or that article can address these.
Metadata
Metadata
Assignees
Labels
No labels