Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python unit tests in self-contained program?

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.

like image 791
cxxl Avatar asked Jul 11 '26 11:07

cxxl


1 Answers

It is possible to achieve the effect you want with a plain unittest module. You just need to write your own simple test runner. Like this:

import unittest

def stradd(a, b):
    return a + b

class test_hello(unittest.TestCase):
    def test_1(self):
        self.assertEqual(stradd("a", "b"), "ab")


def run_my_tests(test_case):
    case = unittest.TestLoader().loadTestsFromTestCase(test_case)
    result = unittest.TestResult()
    case(result)
    if result.wasSuccessful():
        return True
    else:
        print("Some tests failed!")
        for test, err in result.failures + result.errors:
            print(test)
            print(err)
        return False


if run_my_tests(test_hello):
    # All tests passed, so we can run our programm.
    print(stradd("Hello, ", "world"))

run_my_tests function will return True if all tests pass successfully. But if there is a test failure, it will print all errors/failures to stdout. For example:

$ python myscript.py 
Hello, world

$ # And now the test fails...
$ python myscript.py 
Some tests failed!
test_1 (__main__.test_hello)
Traceback (most recent call last):
  File "myscript.py", line 8, in test_1
    self.assertEqual(stradd("a", "c"), "ab")
AssertionError: 'ac' != 'ab'
like image 173
Maxim Avatar answered Jul 13 '26 21:07

Maxim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!