What is the EASIEST Python code to test?
Because writing unit tests is a superpower. It's great. Completely changes what you are capable of as a developer.
Think of the last time you wrote an incredible piece of software... Literally surprising yourself with the beauty, the power, the sheer awesomeness of what you created.
Writing unit tests make that feeling COMMON. You want to live that life.
And part of using them effectively is learning how to make your code easily testable. Out of the bulging universe of different choices for how to organize your code, choosing a way that makes high-impact, high-value tests easiest to write.
In other words, working smarter, not harder.
And while easy-to-test code is not always practical... It often is. You want to learn how to discern.
The easiest code to test is what I call "prime testable" code, which has these two qualities:
The code has no side effects, and
The code is deterministic.
I'll explain:
"No side effects" means that the code does some calculation or look-up, and returns a value... and that's it.
It does NOT write to a database, create a file, or open your garage door. Those are all side effects.
"Deterministic" means that it ALWAYS returns the same outputs, when you feed it the same inputs.
Calculating the 217th prime number, or splitting a string into a list of words, or sorting a sequence - these are all deterministic.
Fetching the number of visitors to your website in the past hour? Not deterministic at all.
If a function or method you write has these two qualities, it is prime testable. And it is the easiest thing in the world to quickly write powerful tests for.
Which means you will write more tests for it. Which means your life is BETTER.
Often, if you have some code that must be non-deterministic or must have side effects - and every real program has code like that - then you can spin out the prime-testable part in a separate function, method or class.
Shove as much of your program's error-prone complexity as you can into that spun-out component. Test the heck out of it. Then any code using it will be reliable and solid.
If you are struggling to write a test, step back and see if you can organize your application code differently. The more of your code you stuff into prime-testable methods and functions, the easier the tests will flow.
If you liked this, you will enjoy the Powerful Python Newsletter.
Top comments (0)