[Tutor] How to test a function which runs a passed in function twice?
Steven D'Aprano
steve at pearwood.info
Sun Oct 2 19:00:02 EDT 2016
On Sun, Oct 02, 2016 at 05:47:51PM -0500, 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? Should I create
> a variety of arbitrary functions in my test file, call the do_twice
> function with each of these made up functions and see if I get the
> expected results?
Probably not need to use a variety of functions. Just one is sufficient.
def test_dotwice(self):
storage = []
def f():
storage.append(1)
assert storage == []
do_twice(demo)
self.assertEqual(storage, [1, 1])
Why do I use `assert` the first time, and `assertEqual` the second?
The actual unit test is the assertEqual. That allows the unittest module
to track errors, etc.
But the first test, `assert storage == []`, is not testing the do_twice
function. It is testing the internal logic of the test_dotwice code: it
acts as a checked comment to the reader: storage must be an empty list,
not just any old list, if it isn't, it will fail. As such, if it
fails, it is inappropriate to count it as an failure of do_twice. It
should count as an error in the test itself. Making it an assert makes
that clear.
--
Steve
More information about the Tutor
mailing list