Python Unittest Discover return exit code 0 even if fails

Viewed 1113

I have read several posts saying that if you call your unittests with unittest.main() that they should exit with a failure code if they fail. I call my unittests with the command: python -m unittest discover -v. I am using Python 3.6.6. An example unittest could look like this:

from server import app
import unittest

class ServerTestCase(unittest.TestCase):
    """
    Unittesting for the server application.
    """


    def setUp(self):
        """
        Create a test client
        """
        self.app = app.test_client()
        self.app.testing = True 

    def tearDown(self):
        pass

    def test_root_endpoint(self):
        """
        Testing the root endpoint
        """

        result = self.app.get('/') 
        self.assertEqual(result.status_code, 200) 

    def test_health_endpoint(self):
        """
        Testing the health endpoint
        """

        result = self.app.get('/health')
        assert b'UP' in result.data

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

Even if one of my tests fails I get this when checking the exit code:

$ echo $?
0

What am I doing wrong?

1 Answers

Did you name the unittest files something like test_*.py? Because that's what discover is looking for. Otherwise no matter your tests, the result will be:

Ran 0 tests in 0.000s
OK

(BTW you don't have to if __name__ ... unittest.main() when using -m unittest discover)

Related