How can one mock/stub python module like urllib

后端 未结 8 2077
情深已故
情深已故 2020-11-28 20:47

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 cha

8条回答
  •  一整个雨季
    2020-11-28 21:23

    Another simple approach is to have your test override urllib's urlopen() function. For example, if your module has

    import urllib
    
    def some_function_that_uses_urllib():
        ...
        urllib.urlopen()
        ...
    

    You could define your test like this:

    import mymodule
    
    def dummy_urlopen(url):
        ...
    
    mymodule.urllib.urlopen = dummy_urlopen
    

    Then, when your tests invoke functions in mymodule, dummy_urlopen() will be called instead of the real urlopen(). 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.

提交回复
热议问题