1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
11 from mozlog
import commandline
, get_default_logger
14 class TestAssertion(Exception):
18 def assert_equals(a
, b
):
20 raise TestAssertion("%r not equal to %r" % (a
, b
))
28 test_func
.__name
__ = f
.__name
__
29 test_func
._expected
= status
35 def test_that_passes():
36 assert_equals(1, int("1"))
39 def test_that_fails():
40 assert_equals(1, int("2"))
43 def test_that_has_an_error():
44 assert_equals(2, 1 + "1")
48 def test_expected_fail():
49 assert_equals(2 + 2, 5)
52 class TestRunner(object):
54 self
.logger
= get_default_logger(component
="TestRunner")
56 def gather_tests(self
):
57 for item
in six
.itervalues(globals()):
58 if isinstance(item
, types
.FunctionType
) and item
.__name
__.startswith(
61 yield item
.__name
__, item
64 tests
= list(self
.gather_tests())
66 self
.logger
.suite_start(tests
=[name
for name
, func
in tests
])
67 self
.logger
.info("Running tests")
68 for name
, func
in tests
:
69 self
.run_test(name
, func
)
70 self
.logger
.suite_end()
72 def run_test(self
, name
, func
):
73 self
.logger
.test_start(name
)
76 expected
= func
._expected
if hasattr(func
, "_expected") else "PASS"
79 except TestAssertion
as e
:
84 message
= traceback
.format_exc()
87 self
.logger
.test_end(name
, status
=status
, expected
=expected
, message
=message
)
91 parser
= argparse
.ArgumentParser()
97 commandline
.add_logging_group(parser
)
99 args
= parser
.parse_args()
101 logger
= commandline
.setup_logging("structured-example", args
, {"raw": sys
.stdout
})
103 runner
= TestRunner()
107 logger
.critical("Error during test run:\n%s" % traceback
.format_exc())
110 if __name__
== "__main__":