From c98be9b0fc9744c26effb83516b77595c86a4432 Mon Sep 17 00:00:00 2001 From: Tom Soulanille Date: Thu, 23 Jul 2015 23:26:37 -0700 Subject: [PATCH] unittest: make unittest.main() work Enables standalone test scripts to use the common idiom if __name__ == '__main__': unittest.main() e.g. https://docs.python.org/3.4/library/unittest.html#basic-example --- unittest/metadata.txt | 2 +- unittest/test_unittest.py | 20 ++++++++++++++++++++ unittest/unittest.py | 19 +++++++++++++++---- 3 files changed, 36 insertions(+), 5 deletions(-) create mode 100644 unittest/test_unittest.py diff --git a/unittest/metadata.txt b/unittest/metadata.txt index c60a4d6c..bf0b614d 100644 --- a/unittest/metadata.txt +++ b/unittest/metadata.txt @@ -1,4 +1,4 @@ srctype = micropython-lib type = module -version = 0.0.7 +version = 0.0.8 author = Paul Sokolovsky diff --git a/unittest/test_unittest.py b/unittest/test_unittest.py new file mode 100644 index 00000000..efbd6017 --- /dev/null +++ b/unittest/test_unittest.py @@ -0,0 +1,20 @@ +import unittest + +class TestStringMethods(unittest.TestCase): + + def test_upper(self): + self.assertEqual('foo'.upper(), 'FOO') + + def test_isupper(self): + self.assertTrue('FOO'.isupper()) + self.assertFalse('Foo'.isupper()) + + def test_split(self): + s = 'hello world' + self.assertEqual(s.split(), ['hello', 'world']) + # check that s.split fails when the separator is not a string + with self.assertRaises(TypeError): + s.split(2) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/unittest/unittest.py b/unittest/unittest.py index 3a261244..e3f7540b 100644 --- a/unittest/unittest.py +++ b/unittest/unittest.py @@ -116,8 +116,19 @@ def run_class(c, test_result): def main(module="__main__"): + def test_cases(m): + for tn in dir(m): + c = getattr(m, tn) + if isinstance(c, object) and isinstance(c, type) and issubclass(c, TestCase): + yield c + m = __import__(module) - for tn in dir(m): - c = getattr(m, tn) - if isinstance(c, object) and issubclass(c, TestCase): - run_class(c) + suite = TestSuite() + for c in test_cases(m): + suite.addTest(c) + runner = TestRunner() + result = runner.run(suite) + msg = "Ran %d tests" % result.testsRun + if result.skippedNum > 0: + msg += " (%d skipped)" % result.skippedNum + print(msg)