def import_importlib(module_name): """Import a module from importlib both w/ and w/o _frozen_importlib.""" fresh = ('importlib',) if '.' in module_name else () frozen = import_helper.import_fresh_module(module_name) source = import_helper.import_fresh_module(module_name, fresh=fresh, blocked=('_frozen_importlib', '_frozen_importlib_external')) return {'Frozen': frozen, 'Source': source}
def test_environment(self): webbrowser = import_helper.import_fresh_module('webbrowser') try: browser = webbrowser.get().name except webbrowser.Error as err: self.skipTest(str(err)) with os_helper.EnvironmentVarGuard() as env: env["BROWSER"] = browser webbrowser = import_helper.import_fresh_module('webbrowser') webbrowser.get()
def load_tests(loader, tests, pattern): try: pure_tests = import_fresh_module(TESTS, fresh=['datetime', '_strptime'], blocked=['_datetime']) fast_tests = import_fresh_module( TESTS, fresh=['datetime', '_datetime', '_strptime']) finally: # XXX: import_fresh_module() is supposed to leave sys.module cache untouched, # XXX: but it does not, so we have to cleanup ourselves. for modname in ['datetime', '_datetime', '_strptime']: sys.modules.pop(modname, None) test_modules = [pure_tests, fast_tests] test_suffixes = ["_Pure", "_Fast"] # XXX(gb) First run all the _Pure tests, then all the _Fast tests. You might # not believe this, but in spite of all the sys.modules trickery running a _Pure # test last will leave a mix of pure and native datetime stuff lying around. for module, suffix in zip(test_modules, test_suffixes): test_classes = [] for name, cls in module.__dict__.items(): if not isinstance(cls, type): continue if issubclass(cls, unittest.TestCase): test_classes.append(cls) elif issubclass(cls, unittest.TestSuite): suit = cls() test_classes.extend(type(test) for test in suit) test_classes = sorted(set(test_classes), key=lambda cls: cls.__qualname__) for cls in test_classes: cls.__name__ += suffix cls.__qualname__ += suffix @classmethod def setUpClass(cls_, module=module): cls_._save_sys_modules = sys.modules.copy() sys.modules[TESTS] = module sys.modules['datetime'] = module.datetime_module sys.modules['_strptime'] = module._strptime @classmethod def tearDownClass(cls_): sys.modules.clear() sys.modules.update(cls_._save_sys_modules) cls.setUpClass = setUpClass cls.tearDownClass = tearDownClass tests.addTests(loader.loadTestsFromTestCase(cls)) return tests
def test_get(self): webbrowser = import_helper.import_fresh_module('webbrowser') self.assertIsNone(webbrowser._tryorder) self.assertFalse(webbrowser._browsers) with self.assertRaises(webbrowser.Error): webbrowser.get('fakebrowser') self.assertIsNotNone(webbrowser._tryorder)
def test_environment_preferred(self): webbrowser = import_helper.import_fresh_module('webbrowser') try: webbrowser.get() least_preferred_browser = webbrowser.get( webbrowser._tryorder[-1]).name except (webbrowser.Error, IndexError) as err: self.skipTest(str(err)) with os_helper.EnvironmentVarGuard() as env: env["BROWSER"] = least_preferred_browser webbrowser = import_helper.import_fresh_module('webbrowser') self.assertEqual(webbrowser.get().name, least_preferred_browser) with os_helper.EnvironmentVarGuard() as env: env["BROWSER"] = sys.executable webbrowser = import_helper.import_fresh_module('webbrowser') self.assertEqual(webbrowser.get().name, sys.executable)
def get_modules(): """Retrieve two copies of zoneinfo: pure Python and C accelerated. Because this function manipulates the import system in a way that might be fragile or do unexpected things if it is run many times, it uses a `call_once` decorator to ensure that this is only ever called exactly one time — in other words, when using this function you will only ever get one copy of each module rather than a fresh import each time. """ import zoneinfo as c_module py_module = import_fresh_module("zoneinfo", blocked=["_zoneinfo"]) return py_module, c_module
def test__struct_reference_cycle_cleaned_up(self): # Regression test for python/cpython#94207. # When we create a new struct module, trigger use of its cache, # and then delete it ... _struct_module = import_helper.import_fresh_module("_struct") module_ref = weakref.ref(_struct_module) _struct_module.calcsize("b") del _struct_module # Then the module should have been garbage collected. gc.collect() self.assertIsNone(module_ref(), "_struct module was not garbage collected")
def test_register(self): webbrowser = import_helper.import_fresh_module('webbrowser') self.assertIsNone(webbrowser._tryorder) self.assertFalse(webbrowser._browsers) class ExampleBrowser: pass webbrowser.register('Example1', ExampleBrowser) self.assertTrue(webbrowser._tryorder) self.assertEqual(webbrowser._tryorder[-1], 'Example1') self.assertTrue(webbrowser._browsers) self.assertIn('example1', webbrowser._browsers) self.assertEqual(webbrowser._browsers['example1'], [ExampleBrowser, None])
def test_import_fresh_module(self): import_helper.import_fresh_module("ftplib")
"""Unittests for heapq.""" import random import unittest import doctest from test.support import import_helper from unittest import TestCase, skipUnless from operator import itemgetter py_heapq = import_helper.import_fresh_module('heapq', blocked=['_heapq']) c_heapq = import_helper.import_fresh_module('heapq', fresh=['_heapq']) # _heapq.nlargest/nsmallest are saved in heapq._nlargest/_smallest when # _heapq is imported, so check them there func_names = [ 'heapify', 'heappop', 'heappush', 'heappushpop', 'heapreplace', '_heappop_max', '_heapreplace_max', '_heapify_max' ] class TestModules(TestCase): def test_py_functions(self): for fname in func_names: self.assertEqual(getattr(py_heapq, fname).__module__, 'heapq') @skipUnless(c_heapq, 'requires _heapq') def test_c_functions(self): for fname in func_names: self.assertEqual(getattr(c_heapq, fname).__module__, '_heapq')
# # Copyright (C) 2001-2012 Python Software Foundation. All Rights Reserved. # Modified and extended by Stefan Krah. # # Usage: ../../../python bench.py import time from test.support.import_helper import import_fresh_module C = import_fresh_module('decimal', fresh=['_decimal']) P = import_fresh_module('decimal', blocked=['_decimal']) # # NOTE: This is the pi function from the decimal documentation, modified # for benchmarking purposes. Since floats do not have a context, the higher # intermediate precision from the original is NOT used, so the modified # algorithm only gives an approximation to the correctly rounded result. # For serious use, refer to the documentation or the appropriate literature. # def pi_float(): """native float""" lasts, t, s, n, na, d, da = 0, 3.0, 3, 1, 0, 0, 24 while s != lasts: lasts = s n, na = n + na, na + 8 d, da = d + da, da + 32 t = (t * n) / d s += t return s
import unittest import os import socket import sys from test.support import os_helper from test.support import socket_helper from test.support.import_helper import import_fresh_module from test.support.os_helper import TESTFN c_stat = import_fresh_module('stat', fresh=['_stat']) py_stat = import_fresh_module('stat', blocked=['_stat']) class TestFilemode: statmod = None file_flags = { 'SF_APPEND', 'SF_ARCHIVED', 'SF_IMMUTABLE', 'SF_NOUNLINK', 'SF_SNAPSHOT', 'UF_APPEND', 'UF_COMPRESSED', 'UF_HIDDEN', 'UF_IMMUTABLE', 'UF_NODUMP', 'UF_NOUNLINK', 'UF_OPAQUE' } formats = { 'S_IFBLK', 'S_IFCHR', 'S_IFDIR', 'S_IFIFO', 'S_IFLNK', 'S_IFREG', 'S_IFSOCK', 'S_IFDOOR', 'S_IFPORT', 'S_IFWHT' } format_funcs = { 'S_ISBLK', 'S_ISCHR', 'S_ISDIR', 'S_ISFIFO', 'S_ISLNK', 'S_ISREG', 'S_ISSOCK', 'S_ISDOOR', 'S_ISPORT', 'S_ISWHT' }
import unittest import sys from test.support import run_unittest from test.support.import_helper import import_fresh_module TESTS = 'test.datetimetester' try: pure_tests = import_fresh_module(TESTS, fresh=['datetime', '_strptime'], blocked=['_datetime']) fast_tests = import_fresh_module( TESTS, fresh=['datetime', '_datetime', '_strptime']) finally: # XXX: import_fresh_module() is supposed to leave sys.module cache untouched, # XXX: but it does not, so we have to cleanup ourselves. for modname in ['datetime', '_datetime', '_strptime']: sys.modules.pop(modname, None) test_modules = [pure_tests, fast_tests] test_suffixes = ["_Pure", "_Fast"] # XXX(gb) First run all the _Pure tests, then all the _Fast tests. You might # not believe this, but in spite of all the sys.modules trickery running a _Pure # test last will leave a mix of pure and native datetime stuff lying around. all_test_classes = [] for module, suffix in zip(test_modules, test_suffixes): test_classes = [] for name, cls in module.__dict__.items(): if not isinstance(cls, type): continue
import builtins import contextlib import copy import gc import pickle from random import randrange, shuffle import struct import sys import unittest import weakref from collections.abc import MutableMapping from test import mapping_tests, support from test.support import import_helper py_coll = import_helper.import_fresh_module('collections', blocked=['_collections']) c_coll = import_helper.import_fresh_module('collections', fresh=['_collections']) @contextlib.contextmanager def replaced_module(name, replacement): original_module = sys.modules[name] sys.modules[name] = replacement try: yield finally: sys.modules[name] = original_module class OrderedDictTests:
import unittest from test.support.import_helper import import_fresh_module from test.support.warnings_helper import check_warnings with check_warnings(("", PendingDeprecationWarning)): load_tests = import_fresh_module('lib2to3.tests', fresh=['lib2to3']).load_tests if __name__ == '__main__': unittest.main()
import unittest import pickle import sys from test import support from test.support import import_helper py_operator = import_helper.import_fresh_module('operator', blocked=['_operator']) c_operator = import_helper.import_fresh_module('operator', fresh=['_operator']) class Seq1: def __init__(self, lst): self.lst = lst def __len__(self): return len(self.lst) def __getitem__(self, i): return self.lst[i] def __add__(self, other): return self.lst + other.lst def __mul__(self, other): return self.lst * other def __rmul__(self, other): return other * self.lst class Seq2(object): def __init__(self, lst): self.lst = lst def __len__(self):
def test_tix_deprecation(self): with self.assertWarns(DeprecationWarning): import_helper.import_fresh_module( 'tkinter.tix', fresh=('tkinter.tix', ), )
# xml.etree test for cElementTree import io import struct from test import support from test.support.import_helper import import_fresh_module import types import unittest cET = import_fresh_module('xml.etree.ElementTree', fresh=['_elementtree']) cET_alias = import_fresh_module('xml.etree.cElementTree', fresh=['_elementtree', 'xml.etree'], deprecated=True) @unittest.skipUnless(cET, 'requires _elementtree') class MiscTests(unittest.TestCase): # Issue #8651. @support.bigmemtest(size=support._2G + 100, memuse=1, dry_run=False) def test_length_overflow(self, size): data = b'x' * size parser = cET.XMLParser() try: self.assertRaises(OverflowError, parser.feed, data) finally: data = None def test_del_attribute(self): element = cET.Element('tag') element.tag = 'TAG' with self.assertRaises(AttributeError):
def test_synthesize(self): webbrowser = import_helper.import_fresh_module('webbrowser') name = os.path.basename(sys.executable).lower() webbrowser.register(name, None, webbrowser.GenericBrowser(name)) webbrowser.get(sys.executable)
def setUp(self): delete_files() self.filename = os_helper.TESTFN self.d = dbm.open(self.filename, 'c') self.d.close() self.dbm = import_helper.import_fresh_module('dbm')
"""Test script for the binhex C module Uses the mechanism of the python binhex module Based on an original test by Roger E. Masse. """ import unittest from test import support from test.support import import_helper from test.support import os_helper from test.support import warnings_helper with warnings_helper.check_warnings(('', DeprecationWarning)): binhex = import_helper.import_fresh_module('binhex') class BinHexTestCase(unittest.TestCase): def setUp(self): # binhex supports only file names encodable to Latin1 self.fname1 = os_helper.TESTFN_ASCII + "1" self.fname2 = os_helper.TESTFN_ASCII + "2" self.fname3 = os_helper.TESTFN_ASCII + "very_long_filename__very_long_filename__very_long_filename__very_long_filename__" def tearDown(self): os_helper.unlink(self.fname1) os_helper.unlink(self.fname2) os_helper.unlink(self.fname3) DATA = b'Jack is my hero' def test_binhex(self): with open(self.fname1, 'wb') as f:
# Some simple queue module tests, plus some failure conditions # to ensure the Queue locks remain stable. import itertools import random import threading import time import unittest import weakref from test import support from test.support import import_helper py_queue = import_helper.import_fresh_module('queue', blocked=['_queue']) c_queue = import_helper.import_fresh_module('queue', fresh=['_queue']) need_c_queue = unittest.skipUnless(c_queue, "No _queue module found") QUEUE_SIZE = 5 def qfull(q): return q.maxsize > 0 and q.qsize() == q.maxsize # A thread to run a function that unclogs a blocked Queue. class _TriggerThread(threading.Thread): def __init__(self, fn, args): self.fn = fn self.args = args self.startedEvent = threading.Event() threading.Thread.__init__(self) def run(self):
import os import json import doctest import unittest from test import support from test.support import import_helper # import json with and without accelerations cjson = import_helper.import_fresh_module('json', fresh=['_json']) pyjson = import_helper.import_fresh_module('json', blocked=['_json']) # JSONDecodeError is cached inside the _json module cjson.JSONDecodeError = cjson.decoder.JSONDecodeError = json.JSONDecodeError # create two base classes that will be used by the other tests class PyTest(unittest.TestCase): json = pyjson loads = staticmethod(pyjson.loads) dumps = staticmethod(pyjson.dumps) JSONDecodeError = staticmethod(pyjson.JSONDecodeError) @unittest.skipUnless(cjson, 'requires _json') class CTest(unittest.TestCase): if cjson is not None: json = cjson loads = staticmethod(cjson.loads) dumps = staticmethod(cjson.dumps) JSONDecodeError = staticmethod(cjson.JSONDecodeError) # test PyTest and CTest checking if the functions come from the right module
def test_annotations_are_created_correctly(self): ann_module4 = import_helper.import_fresh_module('test.ann_module4') self.assertTrue("__annotations__" in ann_module4.__dict__) del ann_module4.__annotations__ self.assertFalse("__annotations__" in ann_module4.__dict__)
def setUp(self): self.addCleanup(cleaunup_test_dir) setup_test_dir() self.dbm = import_helper.import_fresh_module('dbm')
import unittest from test import support from test.support import import_helper import builtins import contextlib import copy import io import os import pickle import sys import weakref from unittest import mock py_uuid = import_helper.import_fresh_module('uuid', blocked=['_uuid']) c_uuid = import_helper.import_fresh_module('uuid', fresh=['_uuid']) def importable(name): try: __import__(name) return True except: return False def mock_get_command_stdout(data): def get_command_stdout(command, args): return io.BytesIO(data.encode()) return get_command_stdout class BaseTestUUID:
import sys import unittest from test.support import import_helper from collections import UserList py_bisect = import_helper.import_fresh_module('bisect', blocked=['_bisect']) c_bisect = import_helper.import_fresh_module('bisect', fresh=['_bisect']) class Range(object): """A trivial range()-like object that has an insert() method.""" def __init__(self, start, stop): self.start = start self.stop = stop self.last_insert = None def __len__(self): return self.stop - self.start def __getitem__(self, idx): n = self.stop - self.start if idx < 0: idx += n if idx >= n: raise IndexError(idx) return self.start + idx def insert(self, idx, item): self.last_insert = idx, item
# default builtin hash module default_builtin_hashes = {'md5', 'sha1', 'sha256', 'sha512', 'sha3', 'blake2'} # --with-builtin-hashlib-hashes override builtin_hashes = sysconfig.get_config_var("PY_BUILTIN_HASHLIB_HASHES") if builtin_hashes is None: builtin_hashes = default_builtin_hashes else: builtin_hashes = { m.strip() for m in builtin_hashes.strip('"').lower().split(",") } # hashlib with and without OpenSSL backend for PBKDF2 # only import builtin_hashlib when all builtin hashes are available. # Otherwise import prints noise on stderr openssl_hashlib = import_fresh_module('hashlib', fresh=['_hashlib']) if builtin_hashes == default_builtin_hashes: builtin_hashlib = import_fresh_module('hashlib', blocked=['_hashlib']) else: builtin_hashlib = None try: from _hashlib import HASH, HASHXOF, openssl_md_meth_names, get_fips_mode except ImportError: HASH = None HASHXOF = None openssl_md_meth_names = frozenset() def get_fips_mode(): return 0
import os import sys import sysconfig import threading import unittest import warnings from test import support from test.support import _4G, bigmemtest from test.support.import_helper import import_fresh_module from test.support import threading_helper from http.client import HTTPException # Were we compiled --with-pydebug or with #define Py_DEBUG? COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount') c_hashlib = import_fresh_module('hashlib', fresh=['_hashlib']) py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib']) builtin_hashes = sysconfig.get_config_var("PY_BUILTIN_HASHLIB_HASHES") if builtin_hashes is None: builtin_hashes = {'md5', 'sha1', 'sha256', 'sha512', 'sha3', 'blake2'} else: builtin_hashes = { m.strip() for m in builtin_hashes.strip('"').lower().split(",") } try: from _hashlib import HASH, HASHXOF, openssl_md_meth_names except ImportError: HASH = None HASHXOF = None