I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.
What is the best way to control what urllib.urlopen returns?
Best Solution
Another simple approach is to have your test override urllib's
urlopen()
function. For example, if your module hasYou could define your test like this:
Then, when your tests invoke functions in
mymodule
,dummy_urlopen()
will be called instead of the realurlopen()
. Dynamic languages like Python make it super easy to stub out methods and classes for testing.See my blog posts at http://softwarecorner.wordpress.com/ for more information about stubbing out dependencies for tests.