How can one mock/stub python module like urllib

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

    Adding onto Clint Miller's answer, to do this I had to create a fake class that implements a read method like this:

    class FakeURL:
        def read(foo):
            return '{"some":"json_text"}'
    

    Then to stub out urllib2.open:

    # Stub out urllib2.open.
    def dummy_urlopen(foo, bar, baz):
      return FakeURL()
    urllib2.urlopen = dummy_urlopen
    

提交回复
热议问题