ISBN Validation: Adding Simple Python Unit Tests

In the previous versions of the ISBN Validation Exercise, I had the “test” code embedded with the actual validator itself. For simplicity, I think this is was the easiest way for the author to present the exercise on Codementor. As a reminder, this is what the “inline” test code looked like:

    def test_isbns():
        isbn = "123"
        assert ISBNExercise.validate_isbn10(isbn) is False
        isbn = "0136091814"
        assert ISBNExercise.validate_isbn10(isbn) is True
        isbn = "1616550416"

Generally, it isn’t considered good design practice to embed testing code inside of an application, and since I’m getting a bit carried away with this example, I figured that I’d do a bit of refactoring to add a more robust series of tests using the Python unittest framework. For those of you who aren’t familiar with the concept of unit tests, or why they are helpful, there is a great post at RealPython that explains the concept, as well as how to use the unittest framework in Python.

Feeling a bit energized, I decided to do the refactoring.

  1. I created a subdirectory called “tests” in my project.
  2. I created a file called to hold the test cases for the small exercises that I’m doing for practice.
  3. I built a class in the file called TestISBNValidator that subclasses the unittest.TestCase class
  4. I implemented a method to test the ISBN-10 validation logic that I built.

All in all, this is what the test class ended up looking like:

from unittest import TestCase
from small_exercises import ISBNValidator

class TestISBNValidator(TestCase):
    test_data_isbn10 = {
        "123": False,
        "0136091814": True,
        "1616550416": False,
        "0553418025": True,
        "3859574859": False,
        "155404295X": True,
        "1-55404-295-X": True,
        "1-55404-294-X": False

    def test_validate_isbn10(self):
        for (code_string, valid) in TestISBNValidator.test_data_isbn10.items():
            result = ISBNValidator.validate_isbn10(code_string=code_string)
            self.assertEqual(result, valid)

Then, I was able to run it from the command line using the python -m unittest command which allows you to execute a module directly as python starts.

$ python -m unittest tests.test_small_exercises.TestISBNValidator
Ran 1 test in 0.000s


The “OK” response indicates that all tests have passed, so we are good to go!

Next, I’m going to expand the exercise to handle ISBN-13 validation.

  1. Practicing Python: Quick ISBN-10 Validation
  2. Basic ISBN-10 Validation in Python: Part 2
  3. ISBN Validation: Adding Simple Python Unit Tests
  4. Reliable ISBN-13 Validation
  5. ISBN Validator: Making it General Purpose
  6. Simple ISBN-10 to ISBN-13 Conversion
  7. Testing Exceptions in Python with unittest
  8. Using Simple Code Coverage in Python

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top