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.
- I created a subdirectory called “tests” in my project.
- I created a file called test_small_exercises.py to hold the test cases for the small exercises that I’m doing for practice.
- I built a class in the file called TestISBNValidator that subclasses the unittest.TestCase class
- 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 OK
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.