Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
List the longest running tests in a Django test suite
import time
from collections import defaultdict, OrderedDict
from junorunner.testrunner import TestSuiteRunner
from junorunner.extended_runner import TextTestRunner, TextTestResult
class TimedTestSuiteRunner(TestSuiteRunner):
"""
List the longest running tests in a suite
by test module, class and method
Customises the YunoJuno testrunner:
pip install django-juno-testrunner
In settings:
TEST_RUNNER = 'timed_testrunner.TimedTestSuiteRunner'
"""
def run_suite(self, suite, **kwargs):
return TimedTextTestRunner(
verbosity=self.verbosity,
failfast=self.failfast,
total_tests=len(suite._tests)
).run(suite)
class TimedTextTestResult(TextTestResult):
timings = OrderedDict([
('module', defaultdict(float)),
('class', defaultdict(float)),
('method', defaultdict(float))
])
def startTest(self, test):
self.testStartTime = time.time()
super(TimedTextTestResult, self).startTest(test)
def stopTest(self, test):
super(TimedTextTestResult, self).stopTest(test)
testEndTime = time.time() - self.testStartTime
module = test.__module__
klass = "%s.%s" % (module, test.__class__.__name__)
method = "%s.%s" % (klass, test._testMethodName)
self.timings['module'][module] += testEndTime
self.timings['class'][klass] += testEndTime
self.timings['method'][method] = testEndTime
class TimedTextTestRunner(TextTestRunner):
resultclass = TimedTextTestResult
def run(self, test):
result = super(TimedTextTestRunner, self).run(test)
limit = 5 * (1 + self.verbosity)
self.stream.writeln("Longest tests:")
for k, v in result.timings.iteritems():
self.stream.writeln(" By %s" % k)
for x in sorted(v.iteritems(), key=lambda (k, v): v, reverse=True)[:limit]:
self.stream.writeln(" %3.0fs %s" % (x[1], x[0]))
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.