]> Repositories - Adafruit_Blinka-hackapet.git/blob - python/unittest.py
More consistent naming of board,microcontroller,implementation
[Adafruit_Blinka-hackapet.git] / python / unittest.py
1 """Copied from https://raw.githubusercontent.com/micropython/micropython-lib/cfa1b9cce0c93a3115bbff3886c9bbcddd9e8047/unittest/unittest.py """
2 class SkipTest(Exception):
3     pass
4
5
6 class AssertRaisesContext:
7
8     def __init__(self, exc):
9         self.expected = exc
10
11     def __enter__(self):
12         return self
13
14     def __exit__(self, exc_type, exc_value, tb):
15         if exc_type is None:
16             assert False, "%r not raised" % self.expected
17         if issubclass(exc_type, self.expected):
18             return True
19         return False
20
21
22 class TestCase:
23
24     def fail(self, msg=''):
25         assert False, msg
26
27     def assertEqual(self, x, y, msg=''):
28         if not msg:
29             msg = "%r vs (expected) %r" % (x, y)
30         assert x == y, msg
31
32     def assertNotEqual(self, x, y, msg=''):
33         if not msg:
34             msg = "%r not expected to be equal %r" % (x, y)
35         assert x != y, msg
36
37     def assertAlmostEqual(self, x, y, places=None, msg='', delta=None):
38         if x == y:
39             return
40         if delta is not None and places is not None:
41             raise TypeError("specify delta or places not both")
42
43         if delta is not None:
44             if abs(x - y) <= delta:
45                 return
46             if not msg:
47                 msg = '%r != %r within %r delta' % (x, y, delta)
48         else:
49             if places is None:
50                 places = 7
51             if round(abs(y-x), places) == 0:
52                 return
53             if not msg:
54                 msg = '%r != %r within %r places' % (x, y, places)
55
56         assert False, msg
57
58     def assertNotAlmostEqual(self, x, y, places=None, msg='', delta=None):
59         if delta is not None and places is not None:
60             raise TypeError("specify delta or places not both")
61
62         if delta is not None:
63             if not (x == y) and abs(x - y) > delta:
64                 return
65             if not msg:
66                 msg = '%r == %r within %r delta' % (x, y, delta)
67         else:
68             if places is None:
69                 places = 7
70             if not (x == y) and round(abs(y-x), places) != 0:
71                 return
72             if not msg:
73                 msg = '%r == %r within %r places' % (x, y, places)
74
75         assert False, msg
76
77     def assertIs(self, x, y, msg=''):
78         if not msg:
79             msg = "%r is not %r" % (x, y)
80         assert x is y, msg
81
82     def assertIsNot(self, x, y, msg=''):
83         if not msg:
84             msg = "%r is %r" % (x, y)
85         assert x is not y, msg
86
87     def assertIsNone(self, x, msg=''):
88         if not msg:
89             msg = "%r is not None" % x
90         assert x is None, msg
91
92     def assertIsNotNone(self, x, msg=''):
93         if not msg:
94             msg = "%r is None" % x
95         assert x is not None, msg
96
97     def assertTrue(self, x, msg=''):
98         if not msg:
99             msg = "Expected %r to be True" % x
100         assert x, msg
101
102     def assertFalse(self, x, msg=''):
103         if not msg:
104             msg = "Expected %r to be False" % x
105         assert not x, msg
106
107     def assertIn(self, x, y, msg=''):
108         if not msg:
109             msg = "Expected %r to be in %r" % (x, y)
110         assert x in y, msg
111
112     def assertIsInstance(self, x, y, msg=''):
113         assert isinstance(x, y), msg
114
115     def assertRaises(self, exc, func=None, *args, **kwargs):
116         if func is None:
117             return AssertRaisesContext(exc)
118
119         try:
120             func(*args, **kwargs)
121             assert False, "%r not raised" % exc
122         except Exception as e:
123             if isinstance(e, exc):
124                 return
125             raise
126
127
128
129 def skip(msg):
130     def _decor(fun):
131         # We just replace original fun with _inner
132         def _inner(self):
133             raise SkipTest(msg)
134         return _inner
135     return _decor
136
137 def skipIf(cond, msg):
138     if not cond:
139         return lambda x: x
140     return skip(msg)
141
142 def skipUnless(cond, msg):
143     if cond:
144         return lambda x: x
145     return skip(msg)
146
147
148 class TestSuite:
149     def __init__(self):
150         self.tests = []
151     def addTest(self, cls):
152         self.tests.append(cls)
153
154 class TestRunner:
155     def run(self, suite):
156         res = TestResult()
157         for c in suite.tests:
158             run_class(c, res)
159
160         print("Ran %d tests\n" % res.testsRun)
161         if res.failuresNum > 0 or res.errorsNum > 0:
162             print("FAILED (failures=%d, errors=%d)" % (res.failuresNum, res.errorsNum))
163         else:
164             msg = "OK"
165             if res.skippedNum > 0:
166                 msg += " (%d skipped)" % res.skippedNum
167             print(msg)
168
169         return res
170
171 class TestResult:
172     def __init__(self):
173         self.errorsNum = 0
174         self.failuresNum = 0
175         self.skippedNum = 0
176         self.testsRun = 0
177
178     def wasSuccessful(self):
179         return self.errorsNum == 0 and self.failuresNum == 0
180
181 # TODO: Uncompliant
182 def run_class(c, test_result):
183     o = c()
184     set_up = getattr(o, "setUp", lambda: None)
185     tear_down = getattr(o, "tearDown", lambda: None)
186     for name in dir(o):
187         if name.startswith("test"):
188             print("%s (%s) ..." % (name, c.__qualname__), end="")
189             m = getattr(o, name)
190             set_up()
191             try:
192                 test_result.testsRun += 1
193                 m()
194                 print(" ok")
195             except SkipTest as e:
196                 print(" skipped:", e.args[0])
197                 test_result.skippedNum += 1
198             except:
199                 print(" FAIL")
200                 test_result.failuresNum += 1
201                 # Uncomment to investigate failure in detail
202                 #raise
203                 continue
204             finally:
205                 tear_down()
206
207
208 def main(module="__main__"):
209     def test_cases(m):
210         for tn in dir(m):
211             c = getattr(m, tn)
212             if isinstance(c, object) and isinstance(c, type) and issubclass(c, TestCase):
213                 yield c
214
215     m = __import__(module) # changed to permit non-top-level testing modules
216     suite = TestSuite()
217     for c in test_cases(m):
218         suite.addTest(c)
219     runner = TestRunner()
220     result = runner.run(suite)