Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return status of python unittest

I'm trying to call a unittest from another python file, and evaluate the exit code. I was able to use unittest.TestLoader().loadTestsFromModule and unittest.TextTestRunner.run to call the unittest from another python file, but that's returning the entire results to the cmd. I would like to simply set a variable equal to the status code so I can evaluate it. I was able to find a method unittest.TestResult.wasSuccessful, but I'm having trouble implementing it. When I add it to the use case, I get the following AttributeError: AttributeError: 'ConnectionTest' object has no attribute 'failures'

I've included some code samples below and a mockup of the desired result as an illustration of what I'm trying to achieve. Thank you in advance.

""" Tests/ConnectionTest.py """

import unittest
from Connection import Connection


class ConnectionTest(unittest.TestCase):

    def test_connection(self):
        #my tests

    def test_pass(self):
        return unittest.TestResult.wasSuccessful(self)


if __name__ == '__main__':
    unittest.main()


""" StatusTest.py """

import unittest
import Tests.ConnectionTest as test
#import Tests.Test2 as test2
#import Tests.Test3 as test3
#import other unit tests ...

suite = unittest.TestLoader().loadTestsFromModule(test)
unittest.TextTestRunner(verbosity=2).run(suite)


""" Return True if unit test passed
"""
def test_passed(test):
    if test.test_pass() == 0:
        return True
    else:
        return False

""" Run unittest for each module before using it in code
"""
def main():
    tests = "test test2 test3".split()
    for test in tests:
        if test_passed(test):
            # do something
        else:
            # log failure
            pass

Update

To put the question more simply, I need to set the highlighted variable below to the highlighted value.

goal


1 Answers

You mentioned you tried implementing result.wasSuccessful, but would something like the following work:

result = unittest.TextTestRunner(verbosity=2).run(suite)
test_exit_code = int(not result.wasSuccessful())

The value of test_exit_code would then be either 0 when the test suite ran successfully or 1 otherwise.

If you want to disable the output of the TextTestRunner you can specify your own stream, such as:

from io import StringIO

result = unittest.TextTestRunner(stream=StringIO(), verbosity=2).run(suite)
like image 96
Will Keeling Avatar answered May 03 '26 22:05

Will Keeling



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!