Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,21 @@ Optimizations
about 30% faster.
(Contributed by Shamil Abdulaev in :gh:`158304`.)

* The import time for several standard library modules has been improved,
including
:mod:`argparse`,
:mod:`bdb`,
:mod:`code`,
:mod:`importlib`,
:mod:`pdb`,
:mod:`shutil`,
:mod:`unittest`,
:mod:`unittest.mock`,
and :mod:`xml.sax.saxutils`.

(Contributed by Brett Cannon, Brittany Reynoso, Hugo van Kemenade,
Jelle van der Waa, Maxime David, and Savannah Ostrowski in :gh:`154675`.)


ast
---
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_string/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
class LazyImportTest(unittest.TestCase):
@cpython_only
def test_lazy_import(self):
ensure_lazy_imports("base64", {"re", "collections"})
ensure_lazy_imports("string", {"re", "collections"})


class ModuleTest(unittest.TestCase):
Expand Down
34 changes: 34 additions & 0 deletions Lib/test/test_unittest/test_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

import unittest

from test.support import cpython_only
from test.support.import_helper import ensure_lazy_imports

class Test_TestLoader(unittest.TestCase):

### Basic object tests
Expand Down Expand Up @@ -1537,6 +1540,37 @@ class Foo(unittest.TestCase):
self.assertEqual(loader.getTestCaseNames(Foo), test_names)


class TestLazyImports(unittest.TestCase):
@cpython_only
def test_lazy_imports(self):
ensure_lazy_imports(
"unittest",
{
"argparse",
"difflib",
"fnmatch",
"inspect",
"io",
"pprint",
"re",
"signal",
"traceback",
"warnings",
},
)

def test_valid_module_name(self):
# Compiled on first access, via the module's __getattr__.
from unittest import loader

pattern = loader.VALID_MODULE_NAME
self.assertIs(pattern, loader.VALID_MODULE_NAME)
self.assertTrue(pattern.match("test_spam.py"))
self.assertIsNone(pattern.match("1spam.py"))
with self.assertRaises(AttributeError):
loader.NO_SUCH_NAME


class TestObsoleteFunctions(unittest.TestCase):
class MyTestSuite(unittest.TestSuite):
pass
Expand Down
19 changes: 18 additions & 1 deletion Lib/test/test_unittest/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import sys
import tempfile

from test.support import ALWAYS_EQ
from test.support import ALWAYS_EQ, cpython_only
from test.support.import_helper import ensure_lazy_imports
import unittest
from test.test_unittest.testmock.support import is_instance
from unittest import mock
Expand Down Expand Up @@ -58,6 +59,22 @@ class Typos():
def something(a): pass


class LazyImportTest(unittest.TestCase):
@cpython_only
def test_lazy_import(self):
ensure_lazy_imports(
"unittest.mock",
{
"annotationlib",
"dataclasses",
"inspect",
"io",
"pkgutil",
"pprint",
},
)


class MockTest(unittest.TestCase):

def test_all(self):
Expand Down
10 changes: 5 additions & 5 deletions Lib/unittest/case.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

import sys
import functools
import difflib
import pprint
import re
import warnings
import collections
import contextlib
import traceback
import time
import types
lazy import difflib
lazy import pprint
lazy import re
lazy import traceback
lazy import warnings

from . import result
from .util import (strclass, safe_repr, _count_diff_all_purpose,
Expand Down
24 changes: 15 additions & 9 deletions Lib/unittest/loader.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
"""Loading unittests."""

import inspect
import os
import re
import sys
import traceback
import types
import functools
lazy import inspect
lazy import re
lazy import traceback

from fnmatch import fnmatch, fnmatchcase
lazy from fnmatch import fnmatch, fnmatchcase

from . import case, suite, util

__unittest = True

# what about .pyc (etc)
# we would need to avoid loading the same tests multiple times
# from '.py', *and* '.pyc'
VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE)
def __getattr__(name):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find these kind of constructions quite ugly, especially if you put them at the top of the module where anyone following the unittest loader would find it. Is it necessary to make re import faster here? (I think it's 11% only right?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, in this case I don't think it is worth it, unittest isn't particularly performance sensitive. Also, how many of these does a simple test suite trigger anyway?

if name == "VALID_MODULE_NAME":
# Compiled on first use so that importing unittest doesn't import re.
global VALID_MODULE_NAME
# what about .pyc (etc)
# we would need to avoid loading the same tests multiple times
# from '.py', *and* '.pyc'
VALID_MODULE_NAME = re.compile(r"[_a-z]\w*\.py$", re.IGNORECASE)
return VALID_MODULE_NAME
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


class _FailedTest(case.TestCase):
Expand Down Expand Up @@ -422,7 +428,7 @@ def _find_test_path(self, full_path, pattern, namespace=False):
"""
basename = os.path.basename(full_path)
if os.path.isfile(full_path):
if not VALID_MODULE_NAME.match(basename):
if not sys.modules[__name__].VALID_MODULE_NAME.match(basename):
# valid Python identifiers only
return None, False
if not self._match_path(basename, full_path, pattern):
Expand Down
2 changes: 1 addition & 1 deletion Lib/unittest/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Unittest main program"""

import sys
import argparse
import os
lazy import argparse

from . import loader, runner
from .signals import installHandler
Expand Down
34 changes: 19 additions & 15 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,20 @@


import contextlib
import io
import inspect
import pprint
import sys
import builtins
import pkgutil
from inspect import iscoroutinefunction
import threading
from annotationlib import Format
from dataclasses import fields, is_dataclass
from types import CodeType, LazyImportType, ModuleType, MethodType
from unittest.util import safe_repr
from functools import wraps, partial
from functools import cache, wraps, partial
from threading import RLock
lazy import inspect
lazy import io
lazy import pkgutil
lazy import pprint
lazy from annotationlib import Format
lazy from dataclasses import fields, is_dataclass
lazy from inspect import iscoroutinefunction


class InvalidSpecError(Exception):
Expand Down Expand Up @@ -2275,11 +2275,15 @@ def __get__(self, obj, _type=None):
return self.create_mock()


try:
_CODE_SIG = inspect.signature(partial(CodeType.__init__, None))
_CODE_ATTRS = dir(CodeType)
except ValueError:
_CODE_SIG = None
_CODE_ATTRS = dir(CodeType)

@cache
def _get_code_sig():
# Computed on first use to defer importing inspect
try:
return inspect.signature(partial(CodeType.__init__, None))
except ValueError:
return None


class AsyncMockMixin(Base):
Expand All @@ -2292,10 +2296,10 @@ def __init__(self, /, *args, **kwargs):
self.__dict__['_mock_await_count'] = 0
self.__dict__['_mock_await_args'] = None
self.__dict__['_mock_await_args_list'] = _CallList()
if _CODE_SIG:
if code_sig := _get_code_sig():
code_mock = NonCallableMock(spec_set=_CODE_ATTRS)
code_mock.__dict__["_spec_class"] = CodeType
code_mock.__dict__["_spec_signature"] = _CODE_SIG
code_mock.__dict__["_spec_signature"] = code_sig
else:
code_mock = NonCallableMock(spec_set=CodeType)
code_mock.co_flags = (
Expand Down
4 changes: 2 additions & 2 deletions Lib/unittest/result.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Test result object"""

import io
import sys
import traceback
lazy import io
lazy import traceback

from . import util
from functools import wraps
Expand Down
2 changes: 1 addition & 1 deletion Lib/unittest/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import sys
import time
import warnings
lazy import warnings

from . import result
from .case import _SubTest
Expand Down
2 changes: 1 addition & 1 deletion Lib/unittest/signals.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import signal
import weakref
lazy import signal

from functools import wraps

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve import time of :mod:`unittest` and :mod:`unittest.mock` by around 4
times. Patch by Hugo van Kemenade.
Loading