python: Avoid importing the mock module in production.

These lazy imports save a significant amount of time on Zulip's core
import process, because mock imports pbr, which in turn import
pkgresources, which is in turn incredibly slow to import.

Fixes part of #9953.
This commit is contained in:
Tim Abbott 2018-10-17 15:27:27 -07:00
parent ff61c56f47
commit a34b79a3f4
2 changed files with 14 additions and 3 deletions

View File

@ -1,4 +1,3 @@
from mock import patch
from django.forms import Form
from django.conf import settings
from django.core.exceptions import ValidationError
@ -591,6 +590,13 @@ class TwoFactorLoginView(BaseTwoFactorLoginView):
realm.uri instead of '/'.
"""
realm_uri = self.get_user().realm.uri
# This mock.patch business is an unpleasant hack that we'd
# ideally like to remove by instead patching the upstream
# module to support better configurability of the
# LOGIN_REDIRECT_URL setting. But until then, it works. We
# import mock.patch here because mock has an expensive import
# process involving pbr -> pkgresources (which is really slow).
from mock import patch
with patch.object(settings, 'LOGIN_REDIRECT_URL', realm_uri):
return super().done(form_list, **kwargs)

View File

@ -1,5 +1,4 @@
import logging
import mock
from typing import Any, Dict, List, Set, Tuple, Optional, Sequence
from django_auth_ldap.backend import LDAPBackend, _LDAPUser
@ -319,7 +318,13 @@ class ZulipLDAPAuthBackend(ZulipLDAPAuthBackendBase):
REALM_IS_NONE_ERROR = 1
def __init__(self) -> None:
if settings.DEVELOPMENT and settings.FAKE_LDAP_MODE: # nocoverage # We only use this in development
if settings.DEVELOPMENT and settings.FAKE_LDAP_MODE: # nocoverage
# We only use this in development. Importing mock inside
# this function is an import time optimization, which
# avoids the expensive import of the mock module (slow
# because its dependency pbr uses pkgresources, which is
# really slow to import.)
import mock
from fakeldap import MockLDAP
ldap_patcher = mock.patch('django_auth_ldap.config.ldap.initialize')