Why test?
Why test?
Test Driven Development
Red, Green, Refactor
Assertions
Assertions
assert keyword
            assert accepts an expression
            None if the expression is truthy
            AssertionError if the expression is falsy
            Assertions Example
def add_positive_numbers(x, y):
    assert x > 0 and y > 0, "Both numbers must be positive!"
    return x + y
add_positive_numbers(1, 1) # 2
add_positive_numbers(1, -1) # AssertionError: Both numbers must be positive!Assertions Warning
If a Python file is run with the -O flag, assertions will not be evaluated!
# Don't write code like this!
def do_something_bad(user):
    assert user.is_admin, "Only admins can do bad things!"
    destroy_a_bunch_of_stuff()
    return "Mua ha ha ha!"doctests
doctests
doctests Example
def add(x, y):
    """add together x and y
    >>> add(1, 2)
    3
    >>> add(8, "hi")
    Traceback (most recent call last):
        ...
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    """
    Run these tests with:
python3 -m doctest -v YOUR_FILE_NAME.py
Test should fail at first - remember "Red, Green, Refactor"
Issues with doctests
Introduction to 
            unittest
        
Unit testing
            unittest
        
unittest
            unittest.TestCase
            unittest.main()
            
            unittest Example
        
import unittest
from activities import eat, nap
class ActivityTests(unittest.TestCase):
    pass
if __name__ == "__main__":
    unittest.main()tests.py
def eat(food, is_healthy):
    pass
def nap(num_hours):
    passactivities.py
Commenting Tests
tests.py
class SomeTests(unittest.TestCase):
    def first_test(self):
        """testing a thing"""
        self.assertEqual(thing(), "something")
    def second_test(self):
        """testing another thing"""
        self.assertEqual(another_thing(), "something else")To see comments, run
python NAME_OF_TEST_FILE.py -v
self.assertEqual(x, y)
self.assertNotEqual(x, y)
self.assertTrue(x)
self.assertFalse(x)
self.assertIsNone(x)
self.assertIsNotNone(x)
self.assertIn(x, y)
self.assertNotIn(x, y)
Types of Assertions
class SomeTests(unittest.TestCase):
    def testing_for_error(self):
        """testing for an error"""
        with self.assertRaises(IndexError):
            l = [1,2,3]
            l[100]Testing for Errors
Before and After Hooks
setUp and tearDown
Example
class SomeTests(unittest.TestCase):
    def setUp(self):
        # do setup here
        pass
    def test_first(self):
        # setUp runs before
        # tearDown runs after
        pass
    def test_second(self):
        # setUp runs before
        # tearDown runs after
        pass
    def tearDown(self):
        # do teardown here
        passRecap
assert
            unittest is a feature-rich, OOP style testing library in Python