Introduction to patching in Python

If you want to use it in a version earlier than python3.3, you need yo install it:

sudo pip install mock

Simple example

Code to test:

import time
def do_something():
    if time.sleep(100):
        print 'ok'
    else:
        print 'ko'

Actual test:

from mock import patch
@patch('time.sleep')
def test_do_something1(mock_sleep):
    mock_sleep.return_value = True
    do_something()

@patch('time.sleep')
def test_do_something2(mock_sleep):
    mock_sleep.return_value = False
    do_something()

Results:

>>> test_do_something1()
ok
>>> test_do_something2()
ko

Source:

Comments

Comments powered by Disqus