gr1zzly be4r
gr1zzly be4r

Reputation: 2152

Invoking Test Methods with a Method for a unittest.TestCase Subclass Python

I've been reading the documentation for the unittest module, but I haven't been able to decipher if it's even possible to do what I'm looking to do. Specifically, I'd like to be able to do something like the following class:

class TestMyCode(unittest.TestCase):

    def test_code(self):
        self.assertTrue(True)

    # Not sure how to do implement this method below
    def run_tests(self):
        # This would run all of the tests in my class
        self.run()

The reason I would like to do this is because I would like to run my tests from within another Python file. E.g., say I'm writing code in another file:

from test_my_code import TestMyCode
tests = TestMyCode()
# Runs all of the tests from the TestMyCode subclass
tests.run_tests()

Is this possible?

Thanks

Upvotes: 1

Views: 1050

Answers (1)

Noctis Skytower
Noctis Skytower

Reputation: 22001

An alternative to what you are trying to do would be to run the main module shown below. Make sure that the test module is available for import if you wish to run the tests in it. Hope this helps you!


Module: test

import unittest


class TestMyCode(unittest.TestCase):

    def test_code(self):
        self.assertTrue(True)

Module: main

import test


def run_tests(module):
    module.unittest.main(module.__name__)


if __name__ == '__main__':
    run_tests(test)

Addendum: To do what you are requesting, add a method that replicates some of the internal work done by unittest.main to run the tests. The following two modules help to demonstrate how you might go about modifying your TestMyCode class so that it can run tests on itself without outside help.


Module: test_module

import unittest


class TestMyCode(unittest.TestCase):

    def test_code(self):
        self.assertTrue(True)

    @classmethod
    def run_tests(cls):
        test = unittest.defaultTestLoader.loadTestsFromTestCase(cls)
        unittest.TextTestRunner().run(test)

Module: main

import test_module


def main():
    test_module.TestMyCode.run_tests()


if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions