Skip to content

What's the difference between mocking a module (time) and mocking a function in the module? (time.sleep) #2

@gitgithan

Description

@gitgithan
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

  1. I added print(type(time), type(time.sleep)) to check which of them have been turned into a mock object.
  2. 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

  1. Why is time.sleep a <class 'builtin_function_or_method'> (I assume it's the unpatched original) during mocker.patch("mock_examples.sleep_function.time")?
  2. Why is type(time) a <class 'module'> after mocker.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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions