Remember that @patch sets the namespace of the module you provide so that the test function finds the @patch setted object first. This allows you to test with Mock objects and is called monkey patching.
Here's a quick example,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import urllib | |
class Worker(object): | |
def __init__(self, myurl): | |
self.myurl = myurl | |
def dowork(self): | |
resp = urllib.request.urlopen(self.myurl) | |
print(resp.read()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import nose, unittest | |
from unittest import mock | |
from unittest.mock import patch | |
from worker import Worker | |
class WorkerTest(unittest.TestCase): | |
def setUp(self): | |
self.wrkr = Worker('http://www.234234ljk.com') | |
return | |
@patch('worker.urllib.request.urlopen', auto_spec=True) | |
def dowork_test(self, urlopen): | |
myobj = mock.Mock() | |
myobj.read.return_value = "This was successfully mocked." | |
urlopen.return_value = myobj | |
self.wrkr.dowork() | |
assert True == myobj.read.called | |
if '__main__' == __name__: | |
nose.main() # nose is so cool |
run with debugging by typing,
python workter_test.py --pdb