Creating Unittest class inside function not working

In the attached script why 0 testcases are running

import unittest


def smg():
    def add(x, y):
        return x + y

    class SimpleTest(unittest.TestCase):
        def testadd1(self):
            self.assertEquals(add(4, 5), 9)
        

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

smg()

Gives

Ran 0 tests in 0.000s 

What can be done to fix it kindly assist

Answer

You might be interested with unittest.TextTestRunner:

A basic test runner implementation that outputs results to a stream.

Sample usage:

However, should you want to customize the building of your test suite, you can do it yourself:

def suite():
    suite = unittest.TestSuite()
    suite.addTest(WidgetTestCase('test_default_widget_size'))
    suite.addTest(WidgetTestCase('test_widget_resize'))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())

Sample run for your case.

src.py

def add(x, y):
    print("Add", x, y)
    return x + y

test_src.py

import unittest

from src import add


class SimpleTest(unittest.TestCase):
    def testadd1(self):
        self.assertEqual(add(4, 5), 9)

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

Running tests is as how it’s done normally

$ python test_src.py  # Using unittest
Add 4 5
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
$ pytest -q  # Using pytest
.                                                                                                                                                                                                   
1 passed in 0.06s

Now if you want to manually call it via function.

run_tests.py

import unittest

import test_src


def suite():
    suite = unittest.TestSuite()
    suite.addTest(test_src.SimpleTest('testadd1'))
    return suite


def run():
    runner = unittest.TextTestRunner()
    runner.run(suite())

# run()  # Uncomment if you want to try to run it as a script e.g. <python run_tests.py>

You can now just import the file and call run() whenever you need:

$ python3
>>> import run_tests
>>> run_tests.run()
Add 4 5
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
>>>