Back
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?
Yes you can do this and here is the answer to your question:-
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 mathif 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 1e300raise OverflowError("n too large")result = 1factor = 2while factor <= n:result *= factorfactor += 1return resultif __name__ == "__main__":import doctestdoctest.testmod()
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: 120okTrying: [factorial(n) for n in range(6)]Expecting: [1, 1, 2, 6, 24, 120]okTrying: [factorial(long(n)) for n in range(6)]Expecting: [1, 1, 2, 6, 24, 120]OkTrying: factorial(-1)Expecting: Traceback (most recent call last): valueError: n too largeok
Trying:
factorial(5)
Expecting:
120
ok
[factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
[factorial(long(n)) for n in range(6)]
Ok
factorial(-1)
Traceback (most recent call last):
valueError: n too large
I guess this is enough to understand and start working with doctest.
If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.
31k questions
32.8k answers
501 comments
693 users