Generating HTML Reports and Code Coverage for Python Unit Tests

Test Execution and HTML Reporting

To generate visual test reports using the HTMLTestRunner or BSTestRunner libraries, you must configure a test runner that outputs to an HTML file. The following script demonstrates how to discover tests dynamically and produce a timestamped report.

import unittest
import datetime
from pathlib import Path

# Assuming BSTestRunner.py or HTMLTestRunner.py is in your python path
from BSTestRunner import BSTestRunner

def get_test_suite():
    """
    Discovers and returns all tests within the current directory.
    """
    current_dir = Path(__file__).parent
    # Discover tests matching the pattern 'test_*.py'
    loader = unittest.TestLoader()
    suite = loader.discover(start_dir=current_dir, pattern='test_*.py')
    return suite

def execute_tests():
    """
    Runs the test suite and generates an HTML report.
    """
    # Generate a timestamp for unique report filenames
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    report_filename = f"test_report_{timestamp}.html"
    
    # Define the output path for the report file
    output_path = Path(__file__).parent / report_filename
    
    # Open the file in binary write mode as required by the runner
    with open(output_path, 'wb') as report_file:
        # Initialize the runner with custom configuration
        runner = BSTestRunner(
            stream=report_file,
            title='Automated Test Execution Summary',
            description='Results generated via BSTestRunner'
        )
        
        # Run the discovered test suite
        runner.run(get_test_suite())

if __name__ == '__main__':
    execute_tests()

Code Coverage Analysis

To ensure comprehensive testing, you can integrate code coverage analysis. This process tracks which lines of code are executed during the test run.

Installation

First, install the coverage package using pip:

pip install coverage

Execution and Reporting

Run your test suite through the coverage tool to collect data, then generate an HTML report to visualize the results.

# Execute the test script using coverage (replace 'main_runner.py' with your script name)
coverage run main_runner.py

# Generate the HTML coverage report
coverage html

This command creates a directory named htmlcov containing the detailed coverage data. Open htmlcov/index.html in a web browser to view the analysis.

Tags: python unittest testing code-coverage html-reports

Posted on Wed, 20 May 2026 03:39:33 +0000 by henka