Fast Tests
As long as your tests are properly isolated, you can run them in parallel to gain a speed up on multi-core hardware.
python mange.py --parallel
The default password hasher is rather slow by design. If you’re authenticating many users in your tests, you may want to use a custom settings file and set the PASSWORD_HASHERS setting to a faster hashing algorithm:
PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher',]
The test --keepdb option preserves the test database between test runs. It skips the create and destroy actions which can greatly decrease the time to run tests.
manage.py test | Ran 442 tests in 294.374s |
manage.py test --parallel | Ran 442 tests in 136.189s (2 cpus) |
manage.py test --parallel --keepdb | Ran 442 tests in 138.454s |
manage.py test --parallel --keepdb + with md5 password hashing |
Ran 442 tests in 130.763s |
manage.py test --parallel --keepdb + pg without fsync | Ran 442 tests in 82.288s |
python manage.py testmail.tests.test_send_notification.TestSendNotificationConditionHours
In Pycharm:
right click on test -> copy reference
if env.bool("TEST_WITHOUT_MIGRATIONS", False):
MIGRATION_MODULES = {
app.split(".")[-1]: None
for app in INSTALLED_APPS
if app not in ["replication_utils"]
}
Create db based on models
import sys
TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'
https://github.com/realpython/django-slow-tests
TEST_RUNNER = 'django_slowtests.testrunner.DiscoverSlowestTestsRunner'
NUM_SLOW_TESTS = 10
Find slow tests
Mock requests
class BaseMockTestCase(SimpleTestCase):
def setUp(self) -> None:
self.requests_mock = requests_mock.mock()
self.requests_mock.start()
self.addCleanup(self.requests_mock.stop)
super().setUp()
TestCase vs TransactionTestCase
(Avoid TransactionTestCase)
Hit the db only when necessary
Avoid fixtures
Use factories (faster and can evolve)
fsync = off synchronous_commit = off full_page_writes = off
UNLOGGED TABLE