I want to use Python 3.3 with unit tests in small self-contained program, i.e. I don’t want to split it up into a command line part and a “functional” part, which can be tested if it is started on itself on the command line.
So I have this little program:
import unittest
def stradd(a, b):
return a + b
class test_hello(unittest.TestCase):
def test_1(self):
self.assertEqual(stradd("a", "b"), "ab")
unittest.main()
print(stradd("Hello, ", "world"))
Unfortunately, the print() is never reached, since unittest.main() exits the program. And even if it would not exit, it would print all kinds of output to the screen that I don’t want to see in normal operation.
Is there a way to run the tests silently, as long as there is no error? Of course, they should complain loudly if something doesn’t work.
I’ve seen Run python unit tests as an option of the program, but that doesn’t answer my question as well.
It is possible to achieve the effect you want with a plain
unittestmodule. You just need to write your own simple test runner. Like this:run_my_testsfunction will returnTrueif all tests pass successfully. But if there is a test failure, it will print all errors/failures to stdout. For example: