Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As a follow up to Reef's answer, I took a liberty of coding up an example using <a href="http://code.google.com/p/pymox/" rel="nofollow noreferrer">pymox</a>. It introduces some extra helper functions that make it easier to stub functions and methods.</p> <pre><code>import logging # Code under test: class Server(object): def __init__(self): self._payload_count = 0 def do_costly_work(self, payload): # resource intensive logic elided... pass def process(self, payload): self.do_costly_work(payload) self._payload_count += 1 logging.info("processed payload: %s", payload) logging.debug("payloads served: %d", self._payload_count) # Here are some helper functions # that are useful if you do a lot # of pymox-y work. import mox import inspect import contextlib import unittest def stub_all(self, *targets): for target in targets: if inspect.isfunction(target): module = inspect.getmodule(target) self.StubOutWithMock(module, target.__name__) elif inspect.ismethod(target): self.StubOutWithMock(target.im_self or target.im_class, target.__name__) else: raise NotImplementedError("I don't know how to stub %s" % repr(target)) # Monkey-patch Mox class with our helper 'StubAll' method. # Yucky pymox naming convention observed. setattr(mox.Mox, 'StubAll', stub_all) @contextlib.contextmanager def mocking(): mocks = mox.Mox() try: yield mocks finally: mocks.UnsetStubs() # Important! mocks.VerifyAll() # The test case example: class ServerTests(unittest.TestCase): def test_logging(self): s = Server() with mocking() as m: m.StubAll(s.do_costly_work, logging.info, logging.debug) # expectations s.do_costly_work(mox.IgnoreArg()) # don't care, we test logging here. logging.info("processed payload: %s", 'hello') logging.debug("payloads served: %d", 1) # verified execution m.ReplayAll() s.process('hello') if __name__ == '__main__': unittest.main() </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload