How can one mock/stub python module like urllib

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

    In case you don't want to even load the module:

    import sys,types
    class MockCallable():
      """ Mocks a function, can be enquired on how many calls it received """
      def __init__(self, result):
        self.result  = result
        self._calls  = []
    
      def __call__(self, *arguments):
        """Mock callable"""
        self._calls.append(arguments)
        return self.result
    
      def called(self):
        """docstring for called"""
        return self._calls
    
    class StubModule(types.ModuleType, object):
      """ Uses a stub instead of loading libraries """
    
      def __init__(self, moduleName):
        self.__name__ = moduleName
        sys.modules[moduleName] = self
    
      def __repr__(self):
        name  = self.__name__
        mocks = ', '.join(set(dir(self)) - set(['__name__']))
        return "" % locals()
    
    class StubObject(object):
      pass
    

    And then:

    >>> urllib = StubModule("urllib")
    >>> import urllib # won't actually load urllib
    
    >>> urls.urlopen = MockCallable(StubObject())
    
    >>> example = urllib.urlopen('http://example.com')
    >>> example.read = MockCallable('foo')
    
    >>> print(example.read())
    'foo'
    

提交回复
热议问题