Philosophy

Learn about the philosophy of testing in Python.

Test framework advantages

Using proper test framework has a large number of advantages, including:

  • The code is much more likely to be correct.
  • The code typically takes less time to write, because debugging time is reduced.
  • Functions written to be tested tend to be much smaller and single purpose.
  • Functions written to be tested provide a clean separation between computation and I/O.
  • The existence of a test suite makes it easier and safer to modify the code at some later date.

A good test framework allows the programmer to run the tests quickly, usually with a single button click, and see in a glance if there are any errors. Any tests that require more than this will be run in frequently, if at all, thus negating the value of having them.

How to write testable code

In order to write testable code, the following things needs to be done:

  • Write many small functions that each do one thing, rather than a few large functions that do a lot of things.
  • Write the tests as you write the code, not afterwards. Many experts even recommend writing the tests before writing the code, because this helps clarify what the code is supposed to do.

    It can be difficult or impossible to write tests for pre-existing or legacy code.

  • Minimize the use of global variables and avoid them entirely if you can. Functions whose values depend only on their arguments are much easier to test in isolation.
  • Strictly separate functions that do computation from computations that do input or output, and test only the former.

    Functions that do I/O involve the programmer, so they prevent the use of single-click testing. While there are techniques for testing these functions, those are advanced techniques not covered here.

Get hands-on with 1200+ tech skills courses.