diff --git a/README.rst b/README.rst index 6de1967..dfaba0f 100644 --- a/README.rst +++ b/README.rst @@ -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 diff --git a/django_slowtests/testrunner.py b/django_slowtests/testrunner.py index 10ae63f..23ff3e7 100644 --- a/django_slowtests/testrunner.py +++ b/django_slowtests/testrunner.py @@ -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): @@ -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))