Mocking arguments in Python

In the spirit of a recent debugging post, today I want to talk about mocking arguments.

In particular, I'm a big fan of using argparse in programs and it's often convenient to reuse some scripts almost as if I was calling them with arguments, but with some customization done programmatically.

Here are a couple of approaches on how to mock things.

Using a helper class

We can't just instantiate an object because we won't be able to set attributes on it, but it's easy if we declare a quick helper.

>>> class Object(object): pass
... 
>>> args = Object()
>>> args.query = 'select * from tables'
>>> print(args.query)
select * from tables

Using unittest.Mock

unittest.mock is available in Python3 and provides the basic functionality, if you want to use something a bit more standard than a one-off. Although if this is for a durable program, sticking in a mock might not be the cleanest thing to do, just from a readability perspective.

>>> import unittest.mock
>>> m = unittest.mock.Mock()
>>> m.foo = 'foo'
>>> print(m.foo)
foo

Happy mocking!

Tags:  debuggingpython

Home