How can one mock/stub python module like urllib

后端 未结 8 2073
情深已故
情深已故 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:27

    Did you give Mox a look? It should do everything you need. Here is a simple interactive session illustrating the solution you need:

    >>> import urllib
    >>> # check that it works
    >>> urllib.urlopen('http://www.google.com/')
    
    >>> # check what happens when it doesn't
    >>> urllib.urlopen('http://hopefully.doesnotexist.com/')
    #-- snip --
    IOError: [Errno socket error] (-2, 'Name or service not known')
    
    >>> # OK, let's mock it up
    >>> import mox
    >>> m = mox.Mox()
    >>> m.StubOutWithMock(urllib, 'urlopen')
    >>> # We can be verbose if we want to :)
    >>> urllib.urlopen(mox.IgnoreArg()).AndRaise(
    ...   IOError('socket error', (-2, 'Name or service not known')))
    
    >>> # Let's check if it works
    >>> m.ReplayAll()
    >>> urllib.urlopen('http://www.google.com/')
    Traceback (most recent call last):
      File "", line 1, in 
      File "/usr/lib/python2.5/site-packages/mox.py", line 568, in __call__
        raise expected_method._exception
    IOError: [Errno socket error] (-2, 'Name or service not known')
    
    >>> # yay! now unset everything
    >>> m.UnsetStubs()
    >>> m.VerifyAll()
    >>> # and check that it still works
    >>> urllib.urlopen('http://www.google.com/')
    
    

提交回复
热议问题