|
| 1 | +# pip install mock |
| 2 | +# python sampleunittests.py |
| 3 | + |
| 4 | +from unittest import TestCase, main |
| 5 | +from mock import patch |
| 6 | + |
| 7 | + |
| 8 | +# Test Functions and Classes |
| 9 | +def _mock_test_func(value): |
| 10 | + return value + 2 |
| 11 | + |
| 12 | + |
| 13 | +def _test_func_one(value): |
| 14 | + return value + 1 |
| 15 | + |
| 16 | + |
| 17 | +def _test_func_two(value): |
| 18 | + return value * 2 |
| 19 | + |
| 20 | + |
| 21 | +class TestClass(object): |
| 22 | + def __init__(self): |
| 23 | + self.number = 0 |
| 24 | + |
| 25 | + |
| 26 | +# Sample Tests |
| 27 | +class SampleTests(TestCase): |
| 28 | + """ |
| 29 | + Basic Example Tests |
| 30 | + """ |
| 31 | + |
| 32 | + def setUp(self): |
| 33 | + """ Common Setup For All Tests - Runs before each test """ |
| 34 | + self.obj1 = TestClass() |
| 35 | + self.obj2 = TestClass() |
| 36 | + |
| 37 | + # Not used in this example |
| 38 | + # def tearDown(self): |
| 39 | + # """ Common Tear Down For All Tests - Runs after each test """ |
| 40 | + |
| 41 | + def test_basic_asserts(self): |
| 42 | + """ Demonstrates how to use basic asserts """ |
| 43 | + self.assertEqual(1, 1) |
| 44 | + self.assertNotEqual(1, 2) |
| 45 | + self.assertTrue(True) |
| 46 | + self.assertFalse(False) |
| 47 | + self.assertIs(self.obj1, self.obj1) |
| 48 | + self.assertIsNot(self.obj1, self.obj2) |
| 49 | + self.assertIsNone(None) |
| 50 | + self.assertIsNotNone(1) |
| 51 | + self.assertIn(1, [1, 2]) |
| 52 | + self.assertNotIn(1, [2, 3]) |
| 53 | + self.assertIsInstance('1', str) |
| 54 | + self.assertNotIsInstance(1, str) |
| 55 | + |
| 56 | + def test_exception(self): |
| 57 | + """ Demonstrates how to test exceptions """ |
| 58 | + # Test an exception is raised |
| 59 | + with self.assertRaises(Exception): |
| 60 | + raise Exception |
| 61 | + |
| 62 | + # Test that an exception is not raised |
| 63 | + try: |
| 64 | + a = 1 + 1 |
| 65 | + except Exception as e: |
| 66 | + self.fail("Test failed due to exception %s" % str(e)) |
| 67 | + |
| 68 | + |
| 69 | + @patch('__main__._test_func_two', _mock_test_func) |
| 70 | + @patch('__main__._test_func_one') |
| 71 | + def test_mock(self, mock1): |
| 72 | + """ Demonstrates how basic mocking works """ |
| 73 | + _test_func_one(1) |
| 74 | + _test_func_one(3) |
| 75 | + |
| 76 | + self.assertTrue(mock1.called) |
| 77 | + self.assertEqual(mock1.call_count, 2) |
| 78 | + |
| 79 | + # Uses the mocked function (would equal 2 otherwise) |
| 80 | + response = _test_func_two(1) |
| 81 | + self.assertEqual(response, 3) |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == '__main__': |
| 85 | + main() |
0 commit comments