The unittest library has many different assertions but some are more commonly used than others.
Let’s look at how to check for membership, what class a variable is an instance of, and a couple of others.
Membership Assertion
assertIn(x, y)
– Make sure x is a member of y (this is like the in keyword)assertNotIn(x, y)
– Make sure x is NOT a member of y (this is like the in keyword)assertIsInstance(x, y)
– Make sure x is an instance of the y class
Dice Example
dice.py
We want to test if a Die is created correctly inside the dice.py script:
http://ref.ghadanfar.com/2018/01/29/dice-py/
A Die
instance has a number of sides
, and a value
that is given to it after it is rolled by the Roll
class.
A hand roll can be described via the description
variable, where if its value is 3d6 means a hand with 3 dice all having 6 sides.
test.py
Let’s write a test for that:
import unittest
import dice
class DieTests(unittest.TestCase):
def setUp(self):
self.d6 = dice.Die(6)
self.d8 = dice.Die(8)
def test_creation(self):
self.assertEqual(self.d6.sides, 6)
self.assertIn(self.d6.value, range(1, 6))
def test_add(self):
self.assertIsInstance(self.d6+self.d8, int)
class RollTests(unittest.TestCase):
def setUp(self):
self.hand1 = dice.Roll('1d2')
self.hand3 = dice.Roll('3d6')
def test_lower(self):
self.assertGreaterEqual(int(self.hand3), 3)
def test_upper(self):
self.assertLessEqual(int(self.hand3), 18)
def test_membership(self):
test_die = dice.Die(2)
test_die.value = self.hand1.results[0].value
self.assertIn(test_die, self.hand1.results)
Run the test
python -m unittest tests.py