Python Testing NotesΒΆ
Create a test_projectName.py file in the same directory
#assume project name is calc.py
# the project has add, subtract, multiply, and divide functions
#test_calc.py
import unittest
import calc
class TestCalc(unittest.TestCase):
def test_add(self):
result = calc.add(10,5)
self.assertEqual(result, 15)
python -m unittest test_calc.py
Lets setup an easier way to run the test_add
#test_calc.py
# makes python3 test_calc.py work
if __name__ == "__main__":
unittest.main()
#test_calc.py
#more testing
import unittest
import calc
class TestCalc(unittest.TestCase):
def test_add(self): #add enough test methods to make the test worth it
self.assertEqual(calc.add(10,5), 15)
self.assertEqual(calc.add(-1,1), 0)
self.assertEqual(calc.add(-1,-1), -2)
def test_subtract(self): #add enough test methods to make the test worth it
self.assertEqual(calc.add(10,5), 5)
self.assertEqual(calc.add(-1,1), -2)
self.assertEqual(calc.add(-1,-1), 0)
def test_multiply(self): #add enough test methods to make the test worth it
self.assertEqual(calc.add(10,5), 50)
self.assertEqual(calc.add(-1,1), -1)
self.assertEqual(calc.add(-1,-1), 1)
def test_divide(self): #add enough test methods to make the test worth it
self.assertEqual(calc.add(10,5), 2)
self.assertEqual(calc.add(-1,1), -1)
self.assertEqual(calc.add(-1,-1), 1)
# 4 tests
Find yourself repeating code?
import unittest
class TestEmployee(unitest.TestCase):
def setUp(self):
pass
self.emp_1 = Employee ("Corey", "Shaefer", 500000) # the repeated code
def tearDown(self):
pass