So I found this article from 2016 detailing how to create a custom test runner that captures the time it takes to run tests in Django:
runner.py:
from unittest.runner import TextTestResult
from django.test.runner import DiscoverRunner
import time
class TimeLoggingTestRunner(DiscoverRunner):
def __init__(self, slow_test_threshold=0.0, *args, **kwargs):
self.slow_test_threshold = slow_test_threshold
return super().__init__(
resultclass=TimeLoggingTestResult,
*args,
**kwargs,
)
def run(self, test):
result = super().run(test)
self.stream.writeln(
"\nSlow Tests (>{:.03}s):".format(
self.slow_test_threshold))
for name, elapsed in result.getTestTimings():
if elapsed > self.slow_test_threshold:
self.stream.writeln(
"({:.03}s) {}".format(
elapsed, name))
return result
def get_resultclass(self):
return TimeLoggingTestResult
class TimeLoggingTestResult(TextTestResult):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.test_timings = []
def startTest(self, test):
self._test_started_at = time.time()
super().startTest(test)
def addSuccess(self, test):
elapsed = time.time() - self._test_started_at
name = self.getDescription(test)
self.test_timings.append((name, elapsed))
super().addSuccess(test)
def getTestTimings(self):
return self.test_timings
settings.py:
TEST_RUNNER = 'core.utils.test_runner.runner.TimeLoggingTestRunner'
However, nothing prints at the end. I know the code runs, because debug statements fire in both classes - but the actual end result (run) doesn't appear to get called.
What I have managed to do is get the timings to print (by adding print statements inside TimeLoggingTestResult), but I can't seem to get them to all print out at the end.
Does anyone have any experience with doing something like this? The run method doesn't appear to be accessed at all.
Using Django 1.11.
run_testsmethod and notrun.run_testsworks differently, and I'm not sure how to get it to work with this code.runmethod in DiscoverRunner. Could you print what happen if you run tests with this runner but removing your ownrunmethod ?TimeLoggingTestResult) but I can't get the final result to print out.