Debug School

rakesh kumar
rakesh kumar

Posted on

Explain all functions or method for Loading and running tests in unittest

n Python's unittest framework, you can load and run tests using various functions and methods. Here's a checklist of commonly used functions and methods for loading and running tests, along with examples and expected output for each:

Checklist of Functions/Methods for Loading and Running Tests in unittest

unittest.TestLoader().loadTestsFromModule(module) - Load tests from a Python module.
unittest.TestLoader().loadTestsFromTestCase(testCase) - Load tests from a test case class.
unittest.TestLoader().loadTestsFromName(name, module) - Load a specific test by name from a module.
unittest.TestLoader().loadTestsFromNames(names, module) - Load multiple tests by name from a module.
unittest.TestSuite(tests) - Create a test suite to group and run tests.
unittest.TextTestRunner().run(suite) - Run the tests and produce test results.
unittest.TextTestResult - Customize the test result reporting.
Command-Line: python -m unittest - Run tests from the command line.
Example and Expected Output:

Here's an example that demonstrates the use of these functions and methods:

import unittest

# Step 1: Load tests from a module
math_tests = unittest.TestLoader().loadTestsFromModule(test_math_module)

# Step 2: Load tests from a test case class
string_tests = unittest.TestLoader().loadTestsFromTestCase(TestStringOperations)

# Step 3: Load a specific test by name from a module
specific_test = unittest.TestLoader().loadTestsFromName('test_string_length', test_strings_module)

# Step 4: Load multiple tests by name from a module
specific_tests = unittest.TestLoader().loadTestsFromNames(['test_addition', 'test_subtraction'], test_math_module)

# Step 5: Create a test suite to group tests
all_tests = unittest.TestSuite([math_tests, string_tests, specific_test, specific_tests])

# Step 6: Run the tests and produce test results
result = unittest.TextTestRunner(verbosity=2).run(all_tests)

# Step 7: Customizing test result reporting (TextTestResult)
class CustomResult(unittest.TextTestResult):
    def startTest(self, test):
        super().startTest(test)
        print(f"Running test: {test}")

    def addSuccess(self, test):
        super().addSuccess(test)
        print(f"Test {test} passed!")

    def addError(self, test, err):
        super().addError(test, err)
        print(f"Test {test} encountered an error: {err[1]}")

custom_result = unittest.TextTestRunner(resultclass=CustomResult, verbosity=2).run(all_tests)
Enter fullscreen mode Exit fullscreen mode

Expected Output:

When you run the tests, the output will show detailed information about the tests being loaded and run, along with the results. The output will be extensive and include information on test discovery, loading, and the execution of each test. Here, I provide a simplified version of the output to illustrate the key elements:

test_addition (test_math_module.TestMathOperations) ... ok
test_subtraction (test_math_module.TestMathOperations) ... ok
test_string_concatenation (TestStringOperations) ... ok
test_string_length (test_strings_module.TestStringOperations) ... ok
Running test: <test_math_module.TestMathOperations testMethod=test_addition>
Test <test_math_module.TestMathOperations testMethod=test_addition> passed!
Running test: <test_math_module.TestMathOperations testMethod=test_subtraction>
Test <test_math_module.TestMathOperations testMethod=test_subtraction> passed!
Running test: <test_strings_module.TestStringOperations testMethod=test_string_length>
Test <test_strings_module.TestStringOperations testMethod=test_string_length> passed!
Enter fullscreen mode Exit fullscreen mode

...
This output demonstrates loading, running, and customizing the reporting of tests using the functions and methods provided by the unittest framework. The actual output will be more extensive and include detailed information for each test method and any failures or errors encountered.

Another Example

Certainly, let's provide a more concrete example using a project structure with multiple test modules, classes, and methods. In this example, we'll load and run tests from multiple sources and customize the test result reporting.

Consider the following project structure:

project/
│
├── math_operations.py
├── string_operations.py
├── test_math.py
├── test_strings.py
└── run_tests.py
Enter fullscreen mode Exit fullscreen mode

Here's the content of each file:

math_operations.py:

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

def subtract(a, b):
    return a - b
Enter fullscreen mode Exit fullscreen mode

string_operations.py:

def concatenate_strings(str1, str2):
    return str1 + str2

def string_length(string):
    return len(string)
Enter fullscreen mode Exit fullscreen mode

test_math.py:

import unittest
from math_operations import add, subtract

class TestMathOperations(unittest.TestCase):
    def test_addition(self):
        self.assertEqual(add(5, 10), 15)

    def test_subtraction(self):
        self.assertEqual(subtract(20, 7), 13)
Enter fullscreen mode Exit fullscreen mode

test_strings.py:

import unittest
from string_operations import concatenate_strings, string_length

class TestStringOperations(unittest.TestCase):
    def test_string_concatenation(self):
        result = concatenate_strings("Hello, ", "World!")
        self.assertEqual(result, "Hello, World")

    def test_string_length(self):
        length = string_length("Python")
        self.assertEqual(length, 6)
Enter fullscreen mode Exit fullscreen mode

run_tests.py:

import unittest

# Load tests from modules
math_tests = unittest.TestLoader().loadTestsFromModule(test_math)
string_tests = unittest.TestLoader().loadTestsFromModule(test_strings)

# Create a test suite to group tests
all_tests = unittest.TestSuite([math_tests, string_tests])

# Customize the test result reporting
class CustomResult(unittest.TextTestResult):
    def startTest(self, test):
        super().startTest(test)
        print(f"Running test: {test}")

    def addSuccess(self, test):
        super().addSuccess(test)
        print(f"Test {test} passed!")

    def addFailure(self, test, err):
        super().addFailure(test, err)
        print(f"Test {test} failed: {err[1]}")

    def addError(self, test, err):
        super().addError(test, err)
        print(f"Test {test} encountered an error: {err[1]}")

# Run the tests and produce test results with custom reporting
custom_result = unittest.TextTestRunner(resultclass=CustomResult, verbosity=2).run(all_tests)
Enter fullscreen mode Exit fullscreen mode

Expected Output:

When you run the run_tests.py script, it will load and run the tests from test_math.py and test_strings.py, and the custom result reporting will be displayed. The expected output will look like this:

Running test: <test_math.TestMathOperations testMethod=test_addition>
Test <test_math.TestMathOperations testMethod=test_addition> passed!
Running test: <test_math.TestMathOperations testMethod=test_subtraction>
Test <test_math.TestMathOperations testMethod=test_subtraction> passed!
Running test: <test_strings.TestStringOperations testMethod=test_string_concatenation>
Test <test_strings.TestStringOperations testMethod=test_string_concatenation> passed!
Running test: <test_strings.TestStringOperations testMethod=test_string_length>
Test <test_strings.TestStringOperations testMethod=test_string_length> passed!

----------------------------------------------------------------------
Ran 4 tests in 0.002s

OK
Enter fullscreen mode Exit fullscreen mode

This output demonstrates how to load and run tests from multiple modules, customize the test result reporting, and see the test results for each test method.
Refrence

Top comments (0)