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 
6
  • 1
    Looks like a typo. You need assert mock_time.sleep.call_count == 5 (you used get instead of sleep). Commented Apr 23, 2020 at 17:45
  • good catch but same error Expected :5 Actual :0 Commented Apr 24, 2020 at 0:11
  • I changed the question to fix the error by refactoring and just mocking the sleep method. Can I mock the whole time object? Commented Apr 24, 2020 at 0:19
  • Yes - I just tried it with your first version (with the correction), and it works fine for me. Commented Apr 24, 2020 at 4: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. Commented Apr 24, 2020 at 10:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.