Skip to content

Instantly share code, notes, and snippets.

@nicoddemus
Created February 7, 2014 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicoddemus/d100e3659db7fdddf691 to your computer and use it in GitHub Desktop.
Save nicoddemus/d100e3659db7fdddf691 to your computer and use it in GitHub Desktop.
Sample usage of the `mock` module
============================= test session starts =============================
platform win32 -- Python 2.7.6 -- pytest-2.5.1 -- D:\Programming\Python27\python.exe
plugins: xdist
collected 2 items
test_twitter.py:5: test_twitter PASSED
test_twitter.py:10: test_task_utils FAILED
================================== FAILURES ===================================
_______________________________ test_task_utils _______________________________
def test_task_utils():
with mock.patch('task_utils.mechanize_url') as mech:
mech.return_value = 'MOCKED'
> assert twitter.api() == 'MOCKED'
E assert 'ORIGINAL' == 'MOCKED'
E - ORIGINAL
E + MOCKED
test_twitter.py:13: AssertionError
===================== 1 failed, 1 passed in 0.02 seconds ======================
def mechanize_url():
return 'ORIGINAL'
import mock
import twitter
import task_utils
def test_twitter():
with mock.patch('twitter.mechanize_url') as mech:
mech.return_value = 'MOCKED'
assert twitter.api() == 'MOCKED'
def test_task_utils():
with mock.patch('task_utils.mechanize_url') as mech:
mech.return_value = 'MOCKED'
assert twitter.api() == 'MOCKED'
from task_utils import mechanize_url
def api():
return mechanize_url()
@nicoddemus
Copy link
Author

Changing twitter.py to:

import task_utils

def api():
    return task_utils.mechanize_url()  

Causes test_twitter to fail and test_task_utils to pass:

============================= test session starts =============================
platform win32 -- Python 2.7.6 -- pytest-2.5.1 -- D:\Programming\Python27\python.exe
plugins: xdist
collected 2 items

test_twitter.py:5: test_twitter FAILED
test_twitter.py:10: test_task_utils PASSED

================================== FAILURES ===================================
________________________________ test_twitter _________________________________

@nicoddemus
Copy link
Author

Here is the version of the mock module I'm using:

>>> import mock
>>> mock.__version__
'1.0.1'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment