Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ Instructions
TEST_RUNNER = 'django_slowtests.testrunner.DiscoverSlowestTestsRunner'
NUM_SLOW_TESTS = 10

# (Optional)
SLOW_TEST_THRESHOLD_MS = 200 # Only show tests slower than 200ms

3. Run test suite::

$ python manage.py test
Expand Down
37 changes: 35 additions & 2 deletions django_slowtests/testrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

TIMINGS = {}
NUM_SLOW_TESTS = getattr(settings, 'NUM_SLOW_TESTS', 10)
SLOW_TEST_THRESHOLD_MS = getattr(settings, 'SLOW_TEST_THRESHOLD_MS', 0)


class TimingSuite(TestSuite):
Expand Down Expand Up @@ -65,11 +66,43 @@ class DiscoverSlowestTestsRunner(DiscoverRunner):

def teardown_test_environment(self, **kwargs):
super(DiscoverSlowestTestsRunner, self).teardown_test_environment(**kwargs)

# Grab slowest tests
by_time = sorted(
iter(TIMINGS.items()),
key=operator.itemgetter(1),
reverse=True
)[:NUM_SLOW_TESTS]
print("\n%s slowest tests:" % NUM_SLOW_TESTS)
for func_name, timing in by_time:

test_results = by_time

if SLOW_TEST_THRESHOLD_MS:
# Filter tests by threshold
test_results = []

for result in by_time:
# Convert test time from seconds to miliseconds for comparison
result_time_ms = result[1] * 1000

# If the test was under the threshold
# don't show it to the user
if result_time_ms < SLOW_TEST_THRESHOLD_MS:
continue

test_results.append(result)

test_result_count = len(test_results)

if test_result_count:
if SLOW_TEST_THRESHOLD_MS:
print("\n{r} slowest tests over {ms}ms:".format(
r=test_result_count, ms=SLOW_TEST_THRESHOLD_MS)
)
else:
print("\n{r} slowest tests:".format(r=test_result_count))

for func_name, timing in test_results:
print(("{t:.4f}s {f}".format(f=func_name, t=timing)))

if not len(test_results) and SLOW_TEST_THRESHOLD_MS:
print("\nNo tests slower than {ms}ms".format(ms=SLOW_TEST_THRESHOLD_MS))