[Baypiggies] Unittest magic -- how to get into that exception handler?

Alexandre Conrad alexandre.conrad at gmail.com
Tue Mar 29 02:26:57 CEST 2011


Hi Tung,

2011/3/28 Tung Wai Yip <tungwaiyip at yahoo.com>:
> def myfunc():
>    result = my_processing()
>    if len(result) != 2:
>        raise RuntimeException("Result not right, len=%s" % len(result))
>
>    # verified result is a sequence of len 2 as documented
>    ...

I use "mock.patch": http://www.voidspace.org.uk/python/mock/patch.html

You can use mock.patch as a decorator or as a "with" statement. The
idea is to tell mock.patch what python method/function you want to
patch and it will be replaced it with a function that will return
(un)expected data, such as:

---------- test ------------
def my_processing_1():
    return ["foo"]

def my_processing_3():
    return ["foo", "bar", "baz"]

# the ``my_processing`` function will be patched/replaced with the
function you pass as 2nd argument to patch
with patch('path.to.function.my_processing', my_processing_1):
    self.assertRaises(RuntimeError, myfunc)

# Outside the context manager, ``my_processing`` will be unpatched as
if nothing ever happened.
assert myfunc() == expected_result

# Patch again and expect 3 items
with patch('path.to.function.my_processing', my_processing_3):
    self.assertRaises(RuntimeError, myfunc)
------------------------------

I hope this answers your question.

Best,
-- 
Alex | twitter.com/alexconrad


More information about the Baypiggies mailing list