At the last ChiPy meeting there was a
presentation by Fawad Halim on the python-mock mock object library.
While I usually abhor complex mock libraries, that one actually looked
quite good and sufficiently simple. But I also thought it could be a
lot simpler using doctest.
So after the meeting I whipped up minimock. Here's
what a test looks like; first some setup:
>>> smtplib.SMTP = Mock('smtplib.SMTP')
>>> smtplib.SMTP.mock_returns = Mock('smtp_connection')
Then the test:
>>> send_email('ianb@colorstudy.com', 'joe@example.com',
... 'Hi there!', 'How is it going?')
Called smtplib.SMTP('localhost')
Called smtp_connection.sendmail(
'ianb@colorstudy.com',
['joe@example.com'],
'To: joe@example.com\nFrom: ianb@colorstudy.com\nSubject: Hi there!\n\nHow is it going?')
Called smtp_connection.quit()
It's about 25 lines of actual code and I believe supports all the
patterns that python-mock supports. Almost all features are actually
implicit features of doctest. You really want to set the ELLIPSIS
option
(which I prefer to use in all my doctests).
Why people don't implement doctest in other language, I have no idea.
It's totally translatable and it's so damn
simple. You don't have to understand all sorts of ideas; the ideas
just fall out of doctest (like this mocking). Maybe it's too simple for anyone to feel
proud of porting it. It's not a whole new concept in testing (*coughyagnicough*).
It's just a simple idea that, once you figure it out, feels like it should have been obvious all along.