Category: Technology

Technology I tried

  • Test Driven Development

    Test Driven Development

    Being just enough of a software tinkerer, I have heard about a software development practice where you don’t start by writing functional code. Instead, you start by writing tests that will only pass once the functional code works. This is called Test Driven DevelopmentTDD.

    I have actually written a few unit tests before—dabbled at a job and also for an open source project—but really, this is new to me. I want to give it a shot.

    For python, pytest seems to be the way to go for testing.

    I figured out that I can set up a simple test by putting this into a file called test_math_operations.py

    def test_addition():
        assert add(2, 3) == 5
    

    Once you have this file, type “pytest” in a terminal.

    I got an error, because I didn’t have pytest installed yet, but I went ahead and did “conda install pytest” which worked for my system. I like to use miniconda’s conda environments.

    I have also recently improved on keeping track of my dependencies by dumping them out with one of these:

    • “pip freeze > requirements.txt”
    • “conda list –explicit > environment.txt”
    • “conda env export > environment.yml”

    Note, pytest automatically detects tests to run if they are named with the prefix “test_” or the suffix _test.py” and execute the test functions defined inside them (like test_addition).

    So I have the test for addition, but I haven’t yet defined the add function, so it should fail and it did—as expected. Yay.

    Now let’s add the add function. Let’s put this into a file called math_operations.py:

    # math_operations.py
    
    def add(a, b):
        return a + b
    

    When I tried “pytest” at the command line I got an error because the test file couldn’t find the add function. I had to add an import line at the beginning:

    # test_math_operations.py
    # These are the tests to see that the math operations work
    
    from math_operations import add
    
    def test_addition():
        assert add(2, 3) == 5
    

    Now the test passes. Yay.

    Let’s change the add function so it works wrong:

    # math_operations.py
    
    def add(a, b):
        return a - b

    That failed pytest.

    As I write more complex code that can be wrong in more subtle ways, I hope I will benefit from moving in this Test Driven Development direction.