[TIP] Dilemma with using mock objects

Tu Ted 999iscool at gmail.com
Mon Apr 23 15:24:49 PDT 2012

Please bear with me. Suppose I want to assert that result is in a
particular format, I might set the return value to something as (True,

Sample code: http://pastebin.com/VraxaKjL

def batch_move(self, *args, **kwargs):
  Move a batch of files to its respective destinations.
  Return type: tuple (boolean, message)
                      T/F    , 'string' / str(exception)

  srcs= kwargs.get('srcs', None)
  dests = kwargs.get('dests', None)

    if srcs and dests:
       # map srcs and dests into dictionary (srcs --> keys, dests -->
       src_dest= dict(zip(srcs, dests))

       for src, dest in src_dest:
         if os.path.exists(src):
           if os.path.exists(dest):
           shutil.move(src, dest)   # either way we will proceed to move
           return (False, '%s does not exist!' % src)
       return (True, 'Success!')

       return (False, 'Something gone wrong with those kwargs...')
  except Exception as e:
    return (False, e)

In order to get to return (True, 'Success!'), I have

1. patch os.path.exists with True as return value. But in one unittest I
want to skip this, how do I patch that os.path.exists?
        if os.path.exists(dest):  # I want to skip this

2. How do I patch shutil.move(src, dest)? Do I just give True so it doesn't
generate error? What if I want the case it fails and caught an exception?
How do I simulate that? (I wouldn't always know which exception to catch,
the primarily reason to use Exception as e).

3. If I actually pass the function, does it really mean no exception caught
and it went through every single line? Or is it because I set
`mock_object.return_value = (True, 'Success!')?

4. I am only using two dependencies here, do I need to patch out all the
external dependencies such as (os, sys, math, datetime) all in one? Or if
my function is using other functions (which are refactored)

 def f1(*args, **kwargs):
    f2(..)   # use math, plot, datetime
    f3(..)   # use math and datetime
    f4(..)   # use datetime

Thanks. Sorry for the long questions. I really want to be good at writing

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120423/074d41b4/attachment.htm>

More information about the testing-in-python mailing list