Skip to content

Commit a78e63a

Browse files
committed
Added sample unit tests.
1 parent 7f0c574 commit a78e63a

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

sampleunittests.py

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

0 commit comments

Comments
 (0)