Eu escolhi herdar django.test.runner.DiscoverRunnere fazer algumas adições ao run_testsmétodo.
Minha primeira adição verifica se é necessário configurar um banco de dados e permite que a setup_databasesfuncionalidade normal seja ativada se um banco de dados for necessário. Minha segunda adição permite que o normal teardown_databasesseja executado se o setup_databasesmétodo tiver permissão para ser executado.
Meu código pressupõe que qualquer TestCase que herda django.test.TransactionTestCase(e, portanto django.test.TestCase) exige que um banco de dados seja configurado. Eu fiz essa suposição porque os documentos do Django dizem:
Se você precisar de outros recursos específicos do Django, mais complexos e pesados, como ... Testando ou usando o ORM ..., você deve usar TransactionTestCase ou TestCase.
https://docs.djangoproject.com/en/1.6/topics/testing/tools/#django.test.SimpleTestCase
mysite / scripts / settings.py
from django.test import TransactionTestCase
from django.test.runner import DiscoverRunner
class MyDiscoverRunner(DiscoverRunner):
def run_tests(self, test_labels, extra_tests=None, **kwargs):
"""
Run the unit tests for all the test labels in the provided list.
Test labels should be dotted Python paths to test modules, test
classes, or test methods.
A list of 'extra' tests may also be provided; these tests
will be added to the test suite.
If any of the tests in the test suite inherit from
``django.test.TransactionTestCase``, databases will be setup.
Otherwise, databases will not be set up.
Returns the number of tests that failed.
"""
self.setup_test_environment()
suite = self.build_suite(test_labels, extra_tests)
# ----------------- First Addition --------------
need_databases = any(isinstance(test_case, TransactionTestCase)
for test_case in suite)
old_config = None
if need_databases:
# --------------- End First Addition ------------
old_config = self.setup_databases()
result = self.run_suite(suite)
# ----------------- Second Addition -------------
if need_databases:
# --------------- End Second Addition -----------
self.teardown_databases(old_config)
self.teardown_test_environment()
return self.suite_result(suite, result)
Por fim, adicionei a seguinte linha ao arquivo settings.py do meu projeto.
mysite / settings.py
TEST_RUNNER = 'mysite.scripts.settings.MyDiscoverRunner'
Agora, ao executar apenas testes não dependentes de banco de dados, minha suíte de testes executa uma ordem de magnitude mais rapidamente! :)