0

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
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
Brian
  • 848
  • 10
  • 32
  • 1
    Looks like a typo. You need `assert mock_time.sleep.call_count == 5` (you used `get` instead of `sleep`). – MrBean Bremen Apr 23 '20 at 17:45
  • good catch but same error ```Expected :5 Actual :0 ``` – Brian Apr 24 '20 at 00:11
  • I changed the question to fix the error by refactoring and just mocking the sleep method. Can I mock the whole time object? – Brian Apr 24 '20 at 00:19
  • Yes - I just tried it with your first version (with the correction), and it works fine for me. – MrBean Bremen Apr 24 '20 at 04:40
  • tried it with @patch("example.time") ? not time.sleep? that doesn't seem to work for me and it doesn't mock time. can you show me what your running if you its working for you. – Brian Apr 24 '20 at 10:47
  • I put my working test code into an answer - please check if you do the same. – MrBean Bremen Apr 24 '20 at 11:50

1 Answers1

2

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).

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46