These are articles written for New Light Technologies.

For other things I write, visit josiahulfers.com.

Last time, we built a factorial function in a test-driven style using Python’s assert statement:

def factorial(n):
if n < 0:
raise ValueError('Factorial of negative is undefined')
return n * factorial(n-1) if n else 1
assert factorial(0) == 1
assert factorial(2) == 2
assert factorial(5) == 120
try:
factorial(-1)
assert False, 'Factorial of < 0 should have raised an error'
except ValueError as e:
assert str(e) == 'Factorial of negative is undefined'

This is not, however, the way that assert statements normally appear in code; more often, they’re woven into the program as a way to validate invariants. …

There’s a best way to automate your tests: write them before you write the program. If you’ve heard “test-driven development,” that’s what it means, but if you’ve never seen such a thing before, it’s an unintuitive idea. How should you start?

A basic example

Here, we’ll develop a function that implements the factorial function in a test-driven style. We start with a stub: an empty function. This does nothing, but that’s the point: in effective automated testing, we write the tests first, only after we have a test do we write the code.

def factorial(n):
...

Traditionally, automated tests are a series of…

In part one, we started writing a factorial function in the test-driven style. We depend on the humble “assert” statement to run our tests and we ended with this:

def factorial(n):
return n * factorial(n-1) if n else 1
assert factorial(0) == 1
assert factorial(2) == 2
assert factorial(5) == 120

The code is correct, at least according to the tests we’ve written, but that doesn’t mean it’s bug-free.

>>> factorial(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "fac9.py", line 24, in factorial
return n * factorial(n-1) if n else 1…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store