On Sun, Oct 2, 2016 at 6:00 PM, Steven D'Aprano <st...@pearwood.info> wrote: > 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.
Would you mind on elaborating on why one would be sufficient? I suppose I am overthinking this. It is just that I can imagine all kinds of gnarly, over-convoluted functions. Perhaps one of such theoretical monstrosities would break the function to be tested? But then again, it seems more like do_twice(f) is just exercising Python's well-tested function-calling facility, so I probably don't need to get over-excited about testing do_twice. Have I answered my own question yet? > > 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. This brings to mind something else that I had meant to ask about. I watched a video of Ned Batchelder giving a talk on unit testing last week. In passing, at one point, he mentioned that one might need to test one's test code. And you are providing a little test of your example test code. When should one test test code? When it stops being *obviously* straightforward? After all, testing test code can get recursively ridiculous! -- boB _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor