[Tutor] How to test a function which runs a passed in function twice?

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 2 19:15:04 EDT 2016


On 02/10/16 23:47, boB Stepp wrote:
> In exercise 3.2 of Downey's "Think Python 2" he has a function:
> 
> def do_twice(f):
>     f()
>     f()
> 
> As you know, I am trying to learn testing/TDD while doing these
> exercises.  How do I test such a *general* function? 

You are testing do_twice() not f.
So you do not care at this point whether f() is correct,
you are only interested in proving that do_twice() works.
You can use a mocking framework or simply define an
"empty" function that merely records it's being called.

You could define the function to increment a global,
for example, and then at the end of the test the
global should be incremented by two.

Of course the actual functions that you will pass
in will have been unit tested too and, if they are
stateful,  you may wish to test what happens when
they are called multiple times - does the state
correctly reflect the number of calls. But that is
a separate issue to testing this function.

> I can see doing this, but since the function to be tested is so
> general in nature, I do not see how I can feel confident that I am
> adequately testing it.

The function as written is trivial in its nature and
therefore trivial to test. The concerns you have are,
I suspect, more to do with integration testing than
with unit testing. At that point you have indeed got
a whole new can of worms to contend with. But unit
testing should be done first.

> I cannot even conceive of what might be edge
> cases for this function.

functions that under some cases raise exceptions, or
even exit the program? Functions that request user input?
functions that contain infinite loops. Functions that
are stateful and are at their boundary states. etc...
But these are all integration issues not unit test ones.

Of course any real world function is likely to be less
trivial - it may well have exception handlers for
example and probably return some kind of value.
Or make the calls conditional on some other parameter
so that the function becomes do_zero_to_twice()...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list