Chapter 7. Testing Your Code

Writing tests is an important skill in learning to write good code. A test is code that calls a function and checks that it does what it is supposed to do. It gives you evidence and confidence that your code is working correctly. Similar to logging in the previous chapter, tests take some effort to set up at first, but that effort pays off as your project grows.

If your code is truly a tiny one-off experiment, tests may be less important. But what if your code is part of a larger system? What if other people are changing your code? What if other code depends on your code to return a certain result? Testing gives you some guarantees that your code is working, and you’ll know if a change that you or someone else makes breaks your code.

Tests are also important when you are the only one working on your code. They’re a safety net that will help ensure that your code keeps working when you change it, rather than needing to rely on your memory. They also give you examples of how your code should work, and this makes your code easier to read and maintain.

It may seem challenging to get started with testing, because some experience in knowing what might go wrong is helpful. But you can start by testing that your code is doing what you think it is doing, as I’ll describe in “A Basic Test”. Then you can add more tests as you find occasions when your code doesn’t work.

There are two major types of testing in building software: automated code testing and user ...

Get Software Engineering for Data Scientists now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.