Thursday, December 11, 2014

Brief Python Nose/Mock Snipppet

I've been using Nose and Mock recently for unit and integration testing. It's been quite fun.

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,

#!/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())
view raw worker.py hosted with ❤ by GitHub
#!/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
view raw worker_test.py hosted with ❤ by GitHub

run with debugging by typing,

python workter_test.py --pdb

No comments:

Post a Comment