Is it possible to write a doctest unit test that will check that an exception is raised?

For example, if I have a function factorial(x) that is supposed to raise an exception if x<0, how would I write the doctest for that?

Login

0 votes

Yes you can do this and here is the answer to your question:-

- The
**doctest**module searches for pieces of text that look like interactive Python sessions and then executes those sessions to verify that they work exactly as shown.

factorial(n):

It returns the factorial of n an exact integer>=0

But when we have a negative number then it will throw a valueError that n is negative

def factorial(n):

import math

if not n >= 0:

raise ValueError("n must be >= 0")

if math.floor(n) != n:

raise ValueError("n must be exact integer")

if n+1 == n: # catch a value like 1e300

raise OverflowError("n too large")

result = 1

factor = 2

while factor <= n:

result *= factor

factor += 1

return result

if __name__ == "__main__":

import doctest

doctest.testmod()

If you run above code directly from the command line, doctest performs its magic:

python example.py -v // Pass -v to the script, and doctest prints a detailed log of what it’s trying, and prints a summary at the end:

Trying:

factorial(5)

Expecting:

120

ok

Trying:

[factorial(n) for n in range(6)]

Expecting:

[1, 1, 2, 6, 24, 120]

ok

Trying:

[factorial(long(n)) for n in range(6)]

Expecting:

[1, 1, 2, 6, 24, 120]

Ok

Trying:

factorial(-1)

Expecting:

Traceback (most recent call last):

valueError: n too large

ok

I guess this is enough to understand and start working with **doctest.**