Why I exploit Python to shim modules for testing purposes
A while back I wrote about how I monkey-patch modules for testing, but I didn't really write about why I prefer to do my testing this way instead of, say, using dependency injection in the code I'm going to test.
My ultimate reason for doing it this way is that I would rather have clean code and ugly tests than dirty code and cleaner tests. 'Testable' code that has everything it talks to injected into it as a parameter is generally ugly; specifically, it is artificially contorted from the natural way it would be written purely so that it can be tested. In some languages you don't have any choice, because you have no way of changing the behavior of low-level code. In Python you do, so I cheerfully take advantage of this to make my code clean and natural.
I maintain that clean, natural code really does matter. Such code is
easier and simpler to understand, and you can rely on all of your
accumulated knowledge of Python and its standard library of modules to
understand what it's doing and how it's doing things. You don't have to
double-check to make sure that self.socketSvcs.lookupName()
really is
socket.gethostbyname()
(or perhaps socket.getaddrinfo()
these days),
or remember how this program's mutation of it is supposed to behave.
(Besides, this way I don't have to test the code that creates all of the necessary 'with everything set up to run for real' object instances. Although I suppose those are really tested via end to end functionality tests, instead of mocked-out unit tests.)
|
|