Certainly! Let's expand on the CachingTestRunner concept and provide a more detailed implementation. The goal is to create a custom test runner that tracks the results of each test and skips tests that passed in previous runs. This approach will help you optimize your test suite by avoiding redundant executions of already-passed tests.
Detailed Implementation of CachingTestRunner
1. Understanding the Workflow
The CachingTestRunner will:
- Load Cache: Read a
.test_cache.json file that stores the results of previously executed tests.
- Track Results: During the test run, it will record whether each test passed, failed, or encountered an error.
- Skip Passed Tests: Before running a test, it will check the cache. If the test passed in a previous run, it will skip execution.
- Save Cache: After the test run, it will update the
.test_cache.json file with the latest results.
2. Implementation
Here’s the complete implementation of the CachingTestRunner:
import os
import json
from django.test.runner import DiscoverRunner
from unittest import TextTestResult
class CachingTestRunner(DiscoverRunner):
CACHE_FILE = ".test_cache.json"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.cache = self.load_cache()
def load_cache(self):
"""Load the test result cache from a JSON file."""
if os.path.exists(self.CACHE_FILE):
with open(self.CACHE_FILE, "r") as f:
return json.load(f)
return {}
def save_cache(self):
"""Save the current test result cache to a JSON file."""
with open(self.CACHE_FILE, "w") as f:
json.dump(self.cache, f, indent=4)
def get_test_id(self, test):
"""Generate a unique identifier for a test."""
return f"{test.__class__.__module__}.{test.__class__.__name__}.{test._testMethodName}"
def record_test_result(self, test, outcome):
"""Record the result of a test in the cache."""
test_id = self.get_test_id(test)
self.cache[test_id] = outcome
def should_skip_test(self, test):
"""Determine if a test should be skipped based on the cache."""
test_id = self.get_test_id(test)
return self.cache.get(test_id) == "success"
def run_suite(self, suite, **kwargs):
"""Run the test suite while skipping cached tests."""
class CachingTestResult(TextTestResult):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.runner = kwargs["runner"]
def startTest(self, test):
if self.runner.should_skip_test(test):
# Skip the test if it passed in the last run
self.addSkip(test, "Test passed in previous run (cached)")
else:
super().startTest(test)
def addSuccess(self, test):
super().addSuccess(test)
self.runner.record_test_result(test, "success")
def addFailure(self, test, err):
super().addFailure(test, err)
self.runner.record_test_result(test, "failure")
def addError(self, test, err):
super().addError(test, err)
self.runner.record_test_result(test, "error")
# Use a custom result class to track and skip tests
result = self.test_runner(
verbosity=self.verbosity,
failfast=self.failfast,
buffer=self.buffer,
warnings=self.warnings,
resultclass=lambda stream: CachingTestResult(stream, descriptions=True, verbosity=self.verbosity, runner=self),
).run(suite)
return result
def run_tests(self, test_labels, extra_tests=None, **kwargs):
"""Run the tests and save the cache after execution."""
result = super().run_tests(test_labels, extra_tests, **kwargs)
self.save_cache()
return result