changeset 8728:f3fab7b124f2

imports: try to use global imports unless it is a layering violation To minimize the impact, do imports that violate the layering at runtime instead of at import time.
author Mads Kiilerich <mads@kiilerich.com>
date Sun, 01 Nov 2020 06:29:32 +0100
parents c98c7d4c9ec3
children 912563696e9e
files kallithea/config/middleware/pygrack.py kallithea/controllers/admin/settings.py kallithea/controllers/login.py kallithea/controllers/routing.py kallithea/lib/helpers.py kallithea/lib/hooks.py kallithea/lib/utils2.py kallithea/lib/vcs/backends/git/inmemory.py kallithea/lib/vcs/backends/git/repository.py kallithea/lib/vcs/backends/hg/inmemory.py kallithea/lib/vcs/backends/hg/repository.py kallithea/lib/vcs/utils/helpers.py kallithea/model/db.py kallithea/model/user.py kallithea/model/validators.py kallithea/tests/api/api_base.py kallithea/tests/base.py kallithea/tests/conftest.py kallithea/tests/fixture.py kallithea/tests/functional/test_my_account.py kallithea/tests/other/test_libs.py kallithea/tests/performance/test_vcs.py kallithea/tests/scripts/manual_test_concurrency.py kallithea/tests/vcs/test_repository.py kallithea/tests/vcs/test_workdirs.py setup.py
diffstat 26 files changed, 55 insertions(+), 84 deletions(-) [+]
line wrap: on
line diff
--- a/kallithea/config/middleware/pygrack.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/config/middleware/pygrack.py	Sun Nov 01 06:29:32 2020 +0100
@@ -36,7 +36,7 @@
 
 import kallithea
 from kallithea.lib.utils2 import ascii_bytes
-from kallithea.lib.vcs import subprocessio
+from kallithea.lib.vcs import get_repo, subprocessio
 
 
 log = logging.getLogger(__name__)
@@ -170,8 +170,6 @@
         if git_command in ['git-receive-pack']:
             # updating refs manually after each push.
             # Needed for pre-1.7.0.4 git clients using regular HTTP mode.
-
-            from kallithea.lib.vcs import get_repo
             repo = get_repo(self.content_path)
             if repo:
                 update_server_info(repo._repo)
--- a/kallithea/controllers/admin/settings.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/controllers/admin/settings.py	Sun Nov 01 06:29:32 2020 +0100
@@ -35,6 +35,7 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPFound
 
+import kallithea
 from kallithea.lib import webutils
 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 from kallithea.lib.base import BaseController, render
@@ -309,7 +310,6 @@
         defaults = db.Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
 
-        import kallithea
         c.ini = kallithea.CONFIG
 
         return htmlfill.render(
@@ -399,7 +399,6 @@
         defaults = db.Setting.get_app_settings()
         defaults.update(self._get_hg_ui_settings())
 
-        import kallithea
         c.ini = kallithea.CONFIG
         server_info = db.Setting.get_server_info()
         for key, val in server_info.items():
--- a/kallithea/controllers/login.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/controllers/login.py	Sun Nov 01 06:29:32 2020 +0100
@@ -40,6 +40,7 @@
 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator
 from kallithea.lib.base import BaseController, log_in_user, render
 from kallithea.lib.exceptions import UserCreationError
+from kallithea.lib.recaptcha import submit
 from kallithea.lib.webutils import url
 from kallithea.model import db, meta
 from kallithea.model.forms import LoginForm, PasswordResetConfirmationForm, PasswordResetRequestForm, RegisterForm
@@ -132,7 +133,6 @@
                 form_result['active'] = c.auto_active
 
                 if c.captcha_active:
-                    from kallithea.lib.recaptcha import submit
                     response = submit(request.POST.get('g-recaptcha-response'),
                                       private_key=captcha_private_key,
                                       remoteip=request.ip_addr)
@@ -177,7 +177,6 @@
             try:
                 form_result = password_reset_form.to_python(dict(request.POST))
                 if c.captcha_active:
-                    from kallithea.lib.recaptcha import submit
                     response = submit(request.POST.get('g-recaptcha-response'),
                                       private_key=captcha_private_key,
                                       remoteip=request.ip_addr)
--- a/kallithea/controllers/routing.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/controllers/routing.py	Sun Nov 01 06:29:32 2020 +0100
@@ -22,6 +22,7 @@
 import routes
 
 import kallithea
+from kallithea.lib.utils import is_valid_repo, is_valid_repo_group
 from kallithea.lib.utils2 import safe_str
 
 
@@ -50,8 +51,6 @@
     rmap.minimization = False
     rmap.explicit = False
 
-    from kallithea.lib.utils import is_valid_repo, is_valid_repo_group
-
     def check_repo(environ, match_dict):
         """
         Check for valid repository for proper 404 handling.
--- a/kallithea/lib/helpers.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/helpers.py	Sun Nov 01 06:29:32 2020 +0100
@@ -27,6 +27,7 @@
 from beaker.cache import cache_region
 from pygments import highlight as code_highlight
 from pygments.formatters.html import HtmlFormatter
+from tg import tmpl_context as c
 from tg.i18n import ugettext as _
 
 import kallithea
@@ -771,7 +772,6 @@
     and '_' changed to '-' and be used as attributes on the div. The default
     class is 'gravatar'.
     """
-    from tg import tmpl_context as c
     if not c.visual.use_gravatar:
         return ''
     if 'div_class' not in div_attributes:
@@ -793,7 +793,6 @@
     empty then we fallback to using an icon.
 
     """
-    from tg import tmpl_context as c
     if not c.visual.use_gravatar:
         return ''
 
@@ -815,8 +814,6 @@
 
 
 def gravatar_url(email_address, size=30, default=''):
-    from tg import tmpl_context as c
-
     if not c.visual.use_gravatar:
         return ""
 
--- a/kallithea/lib/hooks.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/hooks.py	Sun Nov 01 06:29:32 2020 +0100
@@ -30,6 +30,7 @@
 import time
 
 import mercurial.scmutil
+import paste.deploy
 
 import kallithea
 from kallithea.lib import webutils
@@ -301,8 +302,6 @@
     they thus need enough info to be able to create an app environment and
     connect to the database.
     """
-    import paste.deploy
-
     import kallithea.config.application
 
     extras = get_hook_environment()
--- a/kallithea/lib/utils2.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/utils2.py	Sun Nov 01 06:29:32 2020 +0100
@@ -39,6 +39,7 @@
 from dateutil import relativedelta
 from sqlalchemy.engine import url as sa_url
 from sqlalchemy.exc import ArgumentError
+from tg import tmpl_context
 from tg.i18n import ugettext as _
 from tg.i18n import ungettext
 from tg.support.converters import asbool, aslist
@@ -491,7 +492,6 @@
     Gets kallithea user from threadlocal tmpl_context variable if it's
     defined, else returns None.
     """
-    from tg import tmpl_context
     try:
         return getattr(tmpl_context, 'authuser', None)
     except TypeError:  # No object (name: context) has been registered for this thread
--- a/kallithea/lib/vcs/backends/git/inmemory.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/vcs/backends/git/inmemory.py	Sun Nov 01 06:29:32 2020 +0100
@@ -9,6 +9,8 @@
 from kallithea.lib.vcs.exceptions import RepositoryError
 from kallithea.lib.vcs.utils import ascii_str, safe_bytes
 
+from . import repository
+
 
 class GitInMemoryChangeset(BaseInMemoryChangeset):
 
@@ -32,9 +34,8 @@
         """
         self.check_integrity(parents)
 
-        from .repository import GitRepository
         if branch is None:
-            branch = GitRepository.DEFAULT_BRANCH_NAME
+            branch = repository.GitRepository.DEFAULT_BRANCH_NAME
 
         repo = self.repository._repo
         object_store = repo.object_store
--- a/kallithea/lib/vcs/backends/git/repository.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/vcs/backends/git/repository.py	Sun Nov 01 06:29:32 2020 +0100
@@ -36,9 +36,7 @@
 from kallithea.lib.vcs.utils.lazy import LazyProperty
 from kallithea.lib.vcs.utils.paths import abspath, get_user_home
 
-from .changeset import GitChangeset
-from .inmemory import GitInMemoryChangeset
-from .workdir import GitWorkdir
+from . import changeset, inmemory, workdir
 
 
 SHA_PATTERN = re.compile(r'^([0-9a-fA-F]{12}|[0-9a-fA-F]{40})$')
@@ -467,9 +465,9 @@
         Returns ``GitChangeset`` object representing commit from git repository
         at the given revision or head (most recent commit) if None given.
         """
-        if isinstance(revision, GitChangeset):
+        if isinstance(revision, changeset.GitChangeset):
             return revision
-        return GitChangeset(repository=self, revision=self._get_revision(revision))
+        return changeset.GitChangeset(repository=self, revision=self._get_revision(revision))
 
     def get_changesets(self, start=None, end=None, start_date=None,
            end_date=None, branch_name=None, reverse=False, max_revisions=None):
@@ -669,7 +667,7 @@
         """
         Returns ``GitInMemoryChangeset`` object for this repository.
         """
-        return GitInMemoryChangeset(self)
+        return inmemory.GitInMemoryChangeset(self)
 
     def clone(self, url, update_after_clone=True, bare=False):
         """
@@ -728,7 +726,7 @@
         """
         Returns ``Workdir`` instance for this repository.
         """
-        return GitWorkdir(self)
+        return workdir.GitWorkdir(self)
 
     def get_config_value(self, section, name, config_file=None):
         """
--- a/kallithea/lib/vcs/backends/hg/inmemory.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/vcs/backends/hg/inmemory.py	Sun Nov 01 06:29:32 2020 +0100
@@ -7,6 +7,8 @@
 from kallithea.lib.vcs.exceptions import RepositoryError
 from kallithea.lib.vcs.utils import ascii_str, safe_bytes, safe_str
 
+from . import repository
+
 
 class MercurialInMemoryChangeset(BaseInMemoryChangeset):
 
@@ -35,9 +37,8 @@
         if not isinstance(author, str):
             raise RepositoryError('author must be a str - got %r' % type(author))
 
-        from .repository import MercurialRepository
         if branch is None:
-            branch = MercurialRepository.DEFAULT_BRANCH_NAME
+            branch = repository.MercurialRepository.DEFAULT_BRANCH_NAME
         kwargs[b'branch'] = safe_bytes(branch)
 
         def filectxfn(_repo, memctx, bytes_path):
--- a/kallithea/lib/vcs/backends/hg/repository.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/vcs/backends/hg/repository.py	Sun Nov 01 06:29:32 2020 +0100
@@ -44,9 +44,7 @@
 from kallithea.lib.vcs.utils.lazy import LazyProperty
 from kallithea.lib.vcs.utils.paths import abspath
 
-from .changeset import MercurialChangeset
-from .inmemory import MercurialInMemoryChangeset
-from .workdir import MercurialWorkdir
+from . import changeset, inmemory, workdir
 
 
 log = logging.getLogger(__name__)
@@ -380,7 +378,7 @@
 
     @LazyProperty
     def in_memory_changeset(self):
-        return MercurialInMemoryChangeset(self)
+        return inmemory.MercurialInMemoryChangeset(self)
 
     @LazyProperty
     def description(self):
@@ -490,7 +488,7 @@
         Returns ``MercurialChangeset`` object representing repository's
         changeset at the given ``revision``.
         """
-        return MercurialChangeset(repository=self, revision=self._get_revision(revision))
+        return changeset.MercurialChangeset(repository=self, revision=self._get_revision(revision))
 
     def get_changesets(self, start=None, end=None, start_date=None,
                        end_date=None, branch_name=None, reverse=False, max_revisions=None):
@@ -616,7 +614,7 @@
         """
         Returns ``Workdir`` instance for this repository.
         """
-        return MercurialWorkdir(self)
+        return workdir.MercurialWorkdir(self)
 
     def get_config_value(self, section, name=None, config_file=None):
         """
--- a/kallithea/lib/vcs/utils/helpers.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/lib/vcs/utils/helpers.py	Sun Nov 01 06:29:32 2020 +0100
@@ -14,6 +14,7 @@
 from pygments.formatters import TerminalFormatter
 from pygments.lexers import ClassNotFound, guess_lexer_for_filename
 
+from kallithea.lib.vcs import backends
 from kallithea.lib.vcs.exceptions import RepositoryError, VCSError
 from kallithea.lib.vcs.utils import safe_str
 from kallithea.lib.vcs.utils.paths import abspath
@@ -71,7 +72,6 @@
 
     :raises VCSError: if given ``path`` is not a directory
     """
-    from kallithea.lib.vcs.backends import get_backend
     if hasattr(path, '__call__'):
         path = path()
     if not os.path.isdir(path):
@@ -91,7 +91,7 @@
         # We still need to check if it's not bare repository as
         # bare repos don't have working directories
         try:
-            get_backend(key)(path)
+            backends.get_backend(key)(path)
             result.append(key)
             continue
         except RepositoryError:
--- a/kallithea/model/db.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/model/db.py	Sun Nov 01 06:29:32 2020 +0100
@@ -37,6 +37,7 @@
 
 import ipaddr
 import sqlalchemy
+import urlobject
 from sqlalchemy import Boolean, Column, DateTime, Float, ForeignKey, Index, Integer, LargeBinary, String, Unicode, UnicodeText, UniqueConstraint
 from sqlalchemy.ext.hybrid import hybrid_property
 from sqlalchemy.orm import class_mapper, joinedload, relationship, validates
@@ -48,7 +49,7 @@
 from kallithea.lib.exceptions import DefaultUserException
 from kallithea.lib.utils2 import asbool, ascii_bytes, aslist, get_changeset_safe, get_clone_url, remove_prefix, safe_bytes, safe_int, safe_str, urlreadable
 from kallithea.lib.vcs import get_backend, get_repo
-from kallithea.lib.vcs.backends.base import EmptyChangeset
+from kallithea.lib.vcs.backends.base import BaseChangeset, EmptyChangeset
 from kallithea.lib.vcs.utils import author_email, author_name
 from kallithea.lib.vcs.utils.helpers import get_scm
 from kallithea.model import meta
@@ -1171,7 +1172,6 @@
     def clone_uri_hidden(self):
         clone_uri = self.clone_uri
         if clone_uri:
-            import urlobject
             url_obj = urlobject.URLObject(self.clone_uri)
             if url_obj.password:
                 clone_uri = url_obj.with_password('*****')
@@ -1226,7 +1226,6 @@
 
         :param cs_cache:
         """
-        from kallithea.lib.vcs.backends.base import BaseChangeset
         if cs_cache is None:
             cs_cache = EmptyChangeset()
             # use no-cache version here
--- a/kallithea/model/user.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/model/user.py	Sun Nov 01 06:29:32 2020 +0100
@@ -39,7 +39,7 @@
 from kallithea.lib import webutils
 from kallithea.lib.exceptions import DefaultUserException, UserOwnsReposException
 from kallithea.lib.utils2 import generate_api_key, get_current_authuser
-from kallithea.model import db, meta
+from kallithea.model import db, forms, meta
 
 
 log = logging.getLogger(__name__)
@@ -451,7 +451,6 @@
         :param user:
         :param email:
         """
-        from kallithea.model import forms
         form = forms.UserExtraEmailForm()()
         data = form.to_python(dict(email=email))
         user = db.User.guess_instance(user)
@@ -481,7 +480,6 @@
         :param user:
         :param ip:
         """
-        from kallithea.model import forms
         form = forms.UserExtraIpForm()()
         data = form.to_python(dict(ip=ip))
         user = db.User.guess_instance(user)
--- a/kallithea/model/validators.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/model/validators.py	Sun Nov 01 06:29:32 2020 +0100
@@ -28,7 +28,7 @@
 from tg.i18n import ugettext as _
 
 import kallithea
-from kallithea.lib.auth import HasPermissionAny, HasRepoGroupPermissionLevel
+from kallithea.lib import auth
 from kallithea.lib.compat import OrderedSet
 from kallithea.lib.exceptions import InvalidCloneUriException, LdapImportError
 from kallithea.lib.utils import is_valid_repo_uri
@@ -455,12 +455,12 @@
             gr_name = gr.group_name if gr is not None else None # None means ROOT location
 
             # create repositories with write permission on group is set to true
-            group_admin = HasRepoGroupPermissionLevel('admin')(gr_name,
+            group_admin = auth.HasRepoGroupPermissionLevel('admin')(gr_name,
                                             'can write into group validator')
-            group_write = HasRepoGroupPermissionLevel('write')(gr_name,
+            group_write = auth.HasRepoGroupPermissionLevel('write')(gr_name,
                                             'can write into group validator')
             forbidden = not (group_admin or group_write)
-            can_create_repos = HasPermissionAny('hg.admin', 'hg.create.repository')
+            can_create_repos = auth.HasPermissionAny('hg.admin', 'hg.create.repository')
             gid = (old_data['repo_group'].get('group_id')
                    if (old_data and 'repo_group' in old_data) else None)
             value_changed = gid != value
@@ -508,7 +508,7 @@
                 return
 
             forbidden_in_root = gr is None and not can_create_in_root
-            forbidden = not HasRepoGroupPermissionLevel('admin')(gr_name, 'can create group validator')
+            forbidden = not auth.HasRepoGroupPermissionLevel('admin')(gr_name, 'can create group validator')
             if forbidden_in_root or forbidden:
                 msg = self.message('permission_denied', state)
                 raise formencode.Invalid(msg, value, state,
--- a/kallithea/tests/api/api_base.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/api/api_base.py	Sun Nov 01 06:29:32 2020 +0100
@@ -19,6 +19,7 @@
 import os
 import random
 import re
+import string
 
 import mock
 import pytest
@@ -177,7 +178,6 @@
         assert response.status == '200 OK'
 
     def test_api_args_different_args(self):
-        import string
         expected = {
             'ascii_letters': string.ascii_letters,
             'ws': string.whitespace,
--- a/kallithea/tests/base.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/base.py	Sun Nov 01 06:29:32 2020 +0100
@@ -20,6 +20,7 @@
 import time
 
 import pytest
+from beaker.cache import cache_managers
 from webtest import TestApp
 
 from kallithea.lib.utils2 import ascii_str
@@ -126,7 +127,6 @@
     effect immediately.
     Note: Any use of this function is probably a workaround - it should be
     replaced with a more specific cache invalidation in code or test."""
-    from beaker.cache import cache_managers
     for cache in cache_managers.values():
         cache.clear()
 
--- a/kallithea/tests/conftest.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/conftest.py	Sun Nov 01 06:29:32 2020 +0100
@@ -19,6 +19,7 @@
 from kallithea.model.scm import ScmModel
 from kallithea.model.user import UserModel
 from kallithea.tests.base import TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS, TEST_USER_REGULAR_LOGIN, TESTS_TMP_PATH, invalidate_all_caches
+from kallithea.tests.fixture import create_test_env, create_test_index
 
 
 def pytest_configure():
@@ -69,7 +70,6 @@
     inifile.create(test_ini_file, None, ini_settings)
 
     context = loadwsgi.loadcontext(loadwsgi.APP, 'config:%s' % test_ini_file)
-    from kallithea.tests.fixture import create_test_env, create_test_index
 
     # set KALLITHEA_NO_TMP_PATH=1 to disable re-creating the database and test repos
     if not int(os.environ.get('KALLITHEA_NO_TMP_PATH', 0)):
--- a/kallithea/tests/fixture.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/fixture.py	Sun Nov 01 06:29:32 2020 +0100
@@ -27,6 +27,8 @@
 
 from kallithea.lib.auth import AuthUser
 from kallithea.lib.db_manage import DbManage
+from kallithea.lib.indexers.daemon import WhooshIndexingDaemon
+from kallithea.lib.pidlock import DaemonLock
 from kallithea.lib.vcs.backends.base import EmptyChangeset
 from kallithea.model import db, meta
 from kallithea.model.changeset_status import ChangesetStatusModel
@@ -41,6 +43,7 @@
 from kallithea.tests.base import (GIT_REPO, HG_REPO, IP_ADDR, TEST_USER_ADMIN_EMAIL, TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS, TEST_USER_REGULAR2_EMAIL,
                                   TEST_USER_REGULAR2_LOGIN, TEST_USER_REGULAR2_PASS, TEST_USER_REGULAR_EMAIL, TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS,
                                   TESTS_TMP_PATH, invalidate_all_caches)
+from kallithea.tests.vcs import setup_package
 
 
 log = logging.getLogger(__name__)
@@ -404,7 +407,6 @@
     tar.close()
 
     # LOAD VCS test stuff
-    from kallithea.tests.vcs import setup_package
     setup_package()
 
 
@@ -413,9 +415,6 @@
     Makes default test index
     """
 
-    from kallithea.lib.indexers.daemon import WhooshIndexingDaemon
-    from kallithea.lib.pidlock import DaemonLock
-
     index_location = os.path.join(config['index_dir'])
     if not os.path.exists(index_location):
         os.makedirs(index_location)
--- a/kallithea/tests/functional/test_my_account.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/functional/test_my_account.py	Sun Nov 01 06:29:32 2020 +0100
@@ -3,7 +3,7 @@
 from tg.util.webtest import test_context
 
 from kallithea.lib import webutils
-from kallithea.model import db, meta
+from kallithea.model import db, meta, validators
 from kallithea.model.user import UserModel
 from kallithea.tests import base
 from kallithea.tests.fixture import Fixture
@@ -182,7 +182,6 @@
                                             _session_csrf_secret_token=self.session_csrf_secret_token()))
 
         response.mustcontain('An email address must contain a single @')
-        from kallithea.model import validators
         with test_context(self.app):
             msg = validators.ValidUsername(edit=False, old_data={}) \
                     ._messages['username_exists']
--- a/kallithea/tests/other/test_libs.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/other/test_libs.py	Sun Nov 01 06:29:32 2020 +0100
@@ -27,13 +27,17 @@
 
 import datetime
 import hashlib
+import re
 
 import mock
+import routes
+from dateutil import relativedelta
+from tg import request
 from tg.util.webtest import test_context
 
 import kallithea.lib.helpers as h
 from kallithea.lib import webutils
-from kallithea.lib.utils2 import AttributeDict, safe_bytes
+from kallithea.lib.utils2 import AttributeDict, get_clone_url, safe_bytes
 from kallithea.model import db
 from kallithea.tests import base
 
@@ -138,8 +142,6 @@
         (dict(years= -3, months= -2), '3 years and 2 months ago'),
     ])
     def test_age(self, age_args, expected):
-        from dateutil import relativedelta
-
         from kallithea.lib.utils2 import age
         with test_context(self.app):
             n = datetime.datetime(year=2012, month=5, day=17)
@@ -164,8 +166,6 @@
         (dict(years= -4, months= -8), '5 years ago'),
     ])
     def test_age_short(self, age_args, expected):
-        from dateutil import relativedelta
-
         from kallithea.lib.utils2 import age
         with test_context(self.app):
             n = datetime.datetime(year=2012, month=5, day=17)
@@ -184,8 +184,6 @@
         (dict(years=1, months=1), 'in 1 year and 1 month')
     ])
     def test_age_in_future(self, age_args, expected):
-        from dateutil import relativedelta
-
         from kallithea.lib.utils2 import age
         with test_context(self.app):
             n = datetime.datetime(year=2012, month=5, day=17)
@@ -221,31 +219,30 @@
 
         with mock.patch('kallithea.lib.webutils.url.current', lambda *a, **b: 'https://example.com'):
             fake = fake_tmpl_context(_url='http://example.com/{email}')
-            with mock.patch('tg.tmpl_context', fake):
-                    from kallithea.lib.webutils import url
-                    assert url.current() == 'https://example.com'
+            with mock.patch('kallithea.lib.helpers.c', fake):
+                    assert webutils.url.current() == 'https://example.com'
                     grav = h.gravatar_url(email_address='test@example.com', size=24)
                     assert grav == 'http://example.com/test@example.com'
 
             fake = fake_tmpl_context(_url='http://example.com/{email}')
-            with mock.patch('tg.tmpl_context', fake):
+            with mock.patch('kallithea.lib.helpers.c', fake):
                 grav = h.gravatar_url(email_address='test@example.com', size=24)
                 assert grav == 'http://example.com/test@example.com'
 
             fake = fake_tmpl_context(_url='http://example.com/{md5email}')
-            with mock.patch('tg.tmpl_context', fake):
+            with mock.patch('kallithea.lib.helpers.c', fake):
                 em = 'test@example.com'
                 grav = h.gravatar_url(email_address=em, size=24)
                 assert grav == 'http://example.com/%s' % (_md5(em))
 
             fake = fake_tmpl_context(_url='http://example.com/{md5email}/{size}')
-            with mock.patch('tg.tmpl_context', fake):
+            with mock.patch('kallithea.lib.helpers.c', fake):
                 em = 'test@example.com'
                 grav = h.gravatar_url(email_address=em, size=24)
                 assert grav == 'http://example.com/%s/%s' % (_md5(em), 24)
 
             fake = fake_tmpl_context(_url='{scheme}://{netloc}/{md5email}/{size}')
-            with mock.patch('tg.tmpl_context', fake):
+            with mock.patch('kallithea.lib.helpers.c', fake):
                 em = 'test@example.com'
                 grav = h.gravatar_url(email_address=em, size=24)
                 assert grav == 'https://example.com/%s/%s' % (_md5(em), 24)
@@ -267,7 +264,6 @@
         ('https://proxy1.example.com/{user}/{repo}', 'group/repo1', 'username', '', 'https://proxy1.example.com/username/group/repo1'),
     ])
     def test_clone_url_generator(self, clone_uri_tmpl, repo_name, username, prefix, expected):
-        from kallithea.lib.utils2 import get_clone_url
         clone_url = get_clone_url(clone_uri_tmpl=clone_uri_tmpl, prefix_url='http://vps1:8000' + prefix,
                                   repo_name=repo_name, repo_id=23, username=username)
         assert clone_url == expected
@@ -278,8 +274,6 @@
 
         :param text:
         """
-        import re
-
         # quickly change expected url[] into a link
         url_pattern = re.compile(r'(?:url\[)(.+?)(?:\])')
 
@@ -553,9 +547,6 @@
     ])
     def test_canonical_url(self, canonical, test, expected):
         # setup url(), used by canonical_url
-        import routes
-        from tg import request
-
         m = routes.Mapper()
         m.connect('about', '/about-page')
         url = routes.URLGenerator(m, {'HTTP_HOST': 'http_host.example.org'})
@@ -575,9 +566,6 @@
         ('http://www.example.org/kallithea/repos/', 'www.example.org'),
     ])
     def test_canonical_hostname(self, canonical, expected):
-        import routes
-        from tg import request
-
         # setup url(), used by canonical_hostname
         m = routes.Mapper()
         url = routes.URLGenerator(m, {'HTTP_HOST': 'http_host.example.org'})
--- a/kallithea/tests/performance/test_vcs.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/performance/test_vcs.py	Sun Nov 01 06:29:32 2020 +0100
@@ -14,6 +14,7 @@
 
 import pytest
 
+from kallithea.lib.graphmod import graph_data
 from kallithea.model import db
 from kallithea.tests import base
 
@@ -23,7 +24,6 @@
 
     def graphmod(self, repo):
         """ Simple test for running the graph_data function for profiling/testing performance. """
-        from kallithea.lib.graphmod import graph_data
         dbr = db.Repository.get_by_repo_name(repo)
         scm_inst = dbr.scm_instance
         collection = scm_inst.get_changesets(start=0, end=None, branch_name=None)
--- a/kallithea/tests/scripts/manual_test_concurrency.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/scripts/manual_test_concurrency.py	Sun Nov 01 06:29:32 2020 +0100
@@ -41,6 +41,7 @@
 from kallithea.lib.auth import get_crypt_password
 from kallithea.model import db, meta
 from kallithea.model.base import init_model
+from kallithea.model.repo import RepoModel
 from kallithea.tests.base import HG_REPO, TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS
 
 
@@ -114,7 +115,6 @@
 
 def create_test_repo(force=True):
     print('creating test repo')
-    from kallithea.model.repo import RepoModel
     sa = get_session()
 
     user = sa.query(db.User).filter(db.User.username == USER).scalar()
--- a/kallithea/tests/vcs/test_repository.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/vcs/test_repository.py	Sun Nov 01 06:29:32 2020 +0100
@@ -1,3 +1,4 @@
+import copy
 import datetime
 
 import pytest
@@ -31,7 +32,6 @@
         assert self.repo == self.repo
 
     def test_repo_equality_broken_object(self):
-        import copy
         _repo = copy.copy(self.repo)
         delattr(_repo, 'path')
         assert self.repo != _repo
--- a/kallithea/tests/vcs/test_workdirs.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/kallithea/tests/vcs/test_workdirs.py	Sun Nov 01 06:29:32 2020 +0100
@@ -2,6 +2,7 @@
 
 import pytest
 
+from kallithea.lib.vcs.exceptions import BranchDoesNotExistError
 from kallithea.lib.vcs.nodes import FileNode
 from kallithea.tests.vcs.base import _BackendTestMixin
 
@@ -67,8 +68,6 @@
         assert self.repo.workdir.get_changeset() == old_head
 
     def test_checkout_branch(self):
-        from kallithea.lib.vcs.exceptions import BranchDoesNotExistError
-
         # first, 'foobranch' does not exist.
         with pytest.raises(BranchDoesNotExistError):
             self.repo.workdir.checkout_branch(branch='foobranch')
--- a/setup.py	Fri Oct 30 14:54:42 2020 +0100
+++ b/setup.py	Sun Nov 01 06:29:32 2020 +0100
@@ -2,6 +2,7 @@
 # -*- coding: utf-8 -*-
 import os
 import platform
+import re
 import sys
 
 import setuptools
@@ -17,7 +18,6 @@
 
 
 def _get_meta_var(name, data, callback_handler=None):
-    import re
     matches = re.compile(r'(?:%s)\s*=\s*(.*)' % name).search(data)
     if matches:
         s = eval(matches.groups()[0])