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