Brian
Brian

Reputation: 976

python mock import in imported module

I'm trying to use unittest.mock to mock an import in a module under test.

What I'm seeing is that although my module calls sleep 5 times the mock object I'm interacting with in the test function isn't what I'm expecting.

I'm assuming I'm not doing something correctly. I did read the docs, but I'm sure I'm not doing this correctly.

"""example.py"""

import time


def mycode():
    time.sleep(10)
    time.sleep(10)
    time.sleep(10)
    time.sleep(10)
    time.sleep(10)
"""test_example.py"""

import example

from unittest.mock import patch


@patch("example.time.sleep")
def test_example(mock_time):
    example.mycode()
    assert mock_time.call_count == 5

Upvotes: 0

Views: 5719

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16855

This is what works for me:

package/time_sleep.py

import time


def do_sleep():
    time.sleep(10)
    time.sleep(10)
    time.sleep(10)
    time.sleep(10)
    time.sleep(10)

test_time_sleep.py

from unittest.mock import patch

from package.time_sleep import do_sleep


@patch("package.time_sleep.time")
def test_sleep1(mock_time):
    do_sleep()
    assert mock_time.sleep.call_count == 5


@patch("package.time_sleep.time.sleep")
def test_sleep2(mock_sleep):
    do_sleep()
    assert mock_sleep.call_count == 5

This looks quite similar to your code (apart from the names).

Upvotes: 2

Related Questions