If your code raises exceptions it’s a good idea to test them to make sure they get raised properly.
Luckily unittest
provides a mechanism for this.
Exception Assertion
assertRaises(x)
– Make sure the following code raises the x exception.
Example
with assertRaises(ValueError):
int('a')
You can also use @unittest.expectedFailure
on tests that you know will fail.
Dice Example
We’re going to test a bad description
value to see if it will raise an exception as it should.
dice .py
http://ref.ghadanfar.com/2018/01/29/dice-py/
test .py
To do that, add to the bottom of the previous test.py script the following code.
import unittest
import dice
...
class DieTests(unittest.TestCase):
...
def test_bad_description(self):
with self.assertRaises(ValueError):
dice.Roll('2b6')
Anagram Example
string_fun.py
import itertools
def is_palindrome(yarn):
"""Return whether or not a string is a palindrome.
A palindrome is a word/phrase that's the same in
both directions.
"""
return yarn == yarn[::-1]
def get_anagrams(*yarn):
"""Return a list of anagrams for a string."""
# If only one letter came in, return it
if yarn:
if len(yarn[0]) == 1:
return list(yarn)
elif len(yarn[0] == 0):
raise ValueError("Must provide at least two letters")
else:
raise ValueError("Must provide at least two letters")
# Get all of the words from the dictionary
words = set([
w.strip().lower() for w in open('words.txt')
])
output = set()
for thread in yarn:
thread = thread.lower()
# Find all possible anagrams
for i in range(2, len(thread)):
fibers = set(
[''.join(w) for w in itertools.permutations(thread, i)]
)
output.update(fibers.intersection(words))
# Finally, return all of the combinations that are in the dictionary
return sorted(list(output))
test.py
import unittest
from string_fun import get_anagrams
class AnagramTestCase(unittest.TestCase):
def test_empty_string(self):
with self.assertRaises(ValueError):
get_anagrams("")
def test_no_args(self):
with self.assertRaises(ValueError):
get_anagrams()
as