Assertions test a condition in your code that must be met.
A lot of the assertions you’ll write in your tests have to do with values.
You’ll want to assert that something is bigger than 5 or has less than 3 items.
Boolean Tests
Using the method is_palindrome()
.
The following assertion methods are used for Boolean tests.
assertTrue(x)
– Make sure x is TrueassertFalse(x)
– Make sure x False
import unittest
from string_fun import is_palindrome
class PalindromeTestCase(unittest.TestCase):
def test_good_palindrome(self):
self.assertTrue(is_palindrome("KLFIFLK"))
def test_bad_palindrome(self):
self.assertFalse(is_palindrome('KLFIFLK1'
Equality Tests
The following assertion methods are used as equality and comparison tests.
assertEqual(x, y)
– Make sure x and y are equalassertNotEqual(x, y)
– Make sure x and y are not equalassertGreater(x, y)
– Make sure x is greater than yassertLess(x, y)
– Make sure x is less than yassertGreaterEqual(x, y)
– Make sure x is greater than or equal to yassertLessEqual(x, y)
– Make sure x is less than or equal to y
Rock-Paper-Scissors Example
We’re going to test the script moves.py
and in it there are Rock, Paper, and Scissors classes that we can create objects from that have better_than
and worse_than
attributes.
import unittest
import moves
class MoveTests(unittest.TestCase):
def setUp(self):
self.rock = moves.Rock()
self.paper = moves.Paper()
self.scissors = moves.Scissors()
def test_equal(self):
self.assertEqual(self.rock, moves.Rock())
def test_not_equal(self):
self.assertNotEqual(self.rock, self.paper)
def test_rock_better_than_scissors(self):
self.assertGreater(self.rock, self.scissors)
def test_paper_worse_than_scissors(self):
self.assertLess(self.paper, self.scissors)
if __name__ == '__main__':
unittest.main()
setUp()
Method that is run before each test. Use this to set up state for the tests.
Run Test
python test.py