Example #1
0
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 = support.import_fresh_module(module_name)
    source = support.import_fresh_module(module_name, fresh=fresh,
                                         blocked=('_frozen_importlib',))
    return frozen, source
Example #2
0
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 = support.import_fresh_module(module_name)
    source = support.import_fresh_module(module_name, fresh=fresh,
                                         blocked=('_frozen_importlib', '_frozen_importlib_external'))
    return {'Frozen': frozen, 'Source': source}
Example #3
0
 def test_environment(self):
     webbrowser = support.import_fresh_module('webbrowser')
     try:
         browser = webbrowser.get().name
     except (webbrowser.Error, AttributeError) as err:
         self.skipTest(str(err))
     with support.EnvironmentVarGuard() as env:
         env["BROWSER"] = browser
         webbrowser = support.import_fresh_module('webbrowser')
         webbrowser.get()
Example #4
0
 def testWithoutThreading(self):
     if not hasattr(support, "import_fresh_module"):
         return
     module = support.import_fresh_module("bz2file", blocked=("threading",))
     with module.BZ2File(self.filename, "wb") as f:
         f.write(b"abc")
     with module.BZ2File(self.filename, "rb") as f:
         self.assertEqual(f.read(), b"abc")
Example #5
0
    def test_environment_preferred(self):
        webbrowser = support.import_fresh_module('webbrowser')
        try:
            webbrowser.get()
            least_preferred_browser = webbrowser.get(webbrowser._tryorder[-1]).name
        except (webbrowser.Error, AttributeError, IndexError) as err:
            self.skipTest(str(err))

        with support.EnvironmentVarGuard() as env:
            env["BROWSER"] = least_preferred_browser
            webbrowser = support.import_fresh_module('webbrowser')
            self.assertEqual(webbrowser.get().name, least_preferred_browser)

        with support.EnvironmentVarGuard() as env:
            env["BROWSER"] = sys.executable
            webbrowser = support.import_fresh_module('webbrowser')
            self.assertEqual(webbrowser.get().name, sys.executable)
Example #6
0
    def test_get(self):
        webbrowser = support.import_fresh_module('webbrowser')
        self.assertIsNone(webbrowser._tryorder)
        self.assertFalse(webbrowser._browsers)

        with self.assertRaises(webbrowser.Error):
            webbrowser.get('fakebrowser')
        self.assertIsNotNone(webbrowser._tryorder)
Example #7
0
    def test_register(self):
        webbrowser = support.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])
Example #8
0
"""Unittests for heapq."""

import sys
import random
import unittest

from test import support
from unittest import TestCase, skipUnless
from operator import itemgetter

py_heapq = support.import_fresh_module("heapq", blocked=["_heapq"])
c_heapq = support.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")
import unittest
import sys
from test.support import import_fresh_module, run_unittest
TESTS = 'test.datetimetester'
# XXX: import_fresh_module() is supposed to leave sys.module cache untouched,
# XXX: but it does not, so we have to save and restore it ourselves.
save_sys_modules = sys.modules.copy()
try:
    pure_tests = import_fresh_module(TESTS, fresh=['datetime', '_strptime'],
                                     blocked=['_datetime'])
    fast_tests = import_fresh_module(TESTS, fresh=['datetime',
                                                   '_datetime', '_strptime'])
finally:
    sys.modules.clear()
    sys.modules.update(save_sys_modules)
test_modules = [pure_tests, fast_tests]
test_suffixes = ["_Pure", "_Fast"]

for module, suffix in zip(test_modules, test_suffixes):
    for name, cls in module.__dict__.items():
        if isinstance(cls, type) and issubclass(cls, unittest.TestCase):
            name += suffix
            cls.__name__ = name
            globals()[name] = cls
            def setUp(self, module=module, setup=cls.setUp):
                self._save_sys_modules = sys.modules.copy()
                sys.modules[TESTS] = module
                sys.modules['datetime'] = module.datetime_module
                sys.modules['_strptime'] = module._strptime
                setup(self)
            def tearDown(self, teardown=cls.tearDown):
Example #10
0
import os
import sys
import json
import doctest
import unittest

from test import support

# import json with and without accelerations
cjson = support.import_fresh_module('json', fresh=['_json'])
pyjson = support.import_fresh_module('json', blocked=['_json'])

# 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)

@unittest.skipUnless(cjson, 'requires _json')
class CTest(unittest.TestCase):
    if cjson is not None:
        json = cjson
        loads = staticmethod(cjson.loads)
        dumps = staticmethod(cjson.dumps)

# test PyTest and CTest checking if the functions come from the right module
class TestPyTest(PyTest):
    def test_pyjson(self):
        self.assertEqual(self.json.scanner.make_scanner.__module__,
                         'json.scanner')
        self.assertEqual(self.json.decoder.scanstring.__module__,
Example #11
0
import sys
import unittest
from test import support
from collections import UserList

py_bisect = support.import_fresh_module('bisect', blocked=['_bisect'])
c_bisect = support.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


class TestBisect:
Example #12
0
 def test_import_fresh_module(self):
     support.import_fresh_module("ftplib")
Example #13
0
 def test_no_frozen_importlib(self):
     # Should be able to import w/o _frozen_importlib being defined.
     module = support.import_fresh_module('importlib', blocked=['_frozen_importlib'])
     self.assertFalse(isinstance(module.__loader__,
                                 machinery.FrozenImporter))
import unittest
from test import support
import builtins
import contextlib
import copy
import io
import os
import pickle
import shutil
import subprocess
import sys
import weakref
from unittest import mock

py_uuid = support.import_fresh_module('uuid', blocked=['_uuid'])
c_uuid = support.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
Example #15
0
# xml.etree test for cElementTree
import sys, struct
from test import support
from test.support 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'])


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


@unittest.skipUnless(cET, 'requires _elementtree')
class TestAliasWorking(unittest.TestCase):
    # Test that the cET alias module is alive
    def test_alias_working(self):
        e = cET_alias.Element('foo')
        self.assertEqual(e.tag, 'foo')
Example #16
0
import os
import unittest
from test import support

# Skip this test if _tkinter wasn't built.
support.import_module('_tkinter')

# Make sure tkinter._fix runs to set up the environment
support.import_fresh_module('tkinter')

# Skip test if tk cannot be initialized.
support.requires('gui')

from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests
from tkinter.test.support import get_tk_root

try:
    ttk.Button()
except TclError as msg:
    # assuming ttk is not available
    raise unittest.SkipTest("ttk not available: %s" % msg)


def test_main():
    try:
        support.run_unittest(
            *runtktests.get_tests(text=False, packages=['test_ttk']))
    finally:
        get_tk_root().destroy()
Example #17
0
import unittest
import pickle
import sys

from test import support

py_operator = support.import_fresh_module('operator', blocked=['_operator'])
c_operator = support.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):
        return len(self.lst)
    def __getitem__(self, i):
        return self.lst[i]
    def __add__(self, other):
Example #18
0
 def testWithoutThreading(self):
     module = support.import_fresh_module("bz2", blocked=("threading", ))
     with module.BZ2File(self.filename, "wb") as f:
         f.write(b"abc")
     with module.BZ2File(self.filename, "rb") as f:
         self.assertEqual(f.read(), b"abc")
Example #19
0
import unittest
import sys
from test.support import import_fresh_module, run_unittest

TESTS = 'test.datetimetester'

# XXX: import_fresh_module() is supposed to leave sys.module cache untouched,
# XXX: but it does not, so we have to save and restore it ourselves.
save_sys_modules = sys.modules.copy()
try:
    pure_tests = import_fresh_module(TESTS,
                                     fresh=['datetime', '_strptime'],
                                     blocked=['_datetime'])
    fast_tests = import_fresh_module(
        TESTS, fresh=['datetime', '_datetime', '_strptime'])
finally:
    sys.modules.clear()
    sys.modules.update(save_sys_modules)
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.
test_classes = []

for module, suffix in zip(test_modules, test_suffixes):
    if module is None:
        continue
    for name, cls in module.__dict__.items():
        if not (isinstance(cls, type) and issubclass(cls, unittest.TestCase)):
            continue
Example #20
0
# 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

py_queue = support.import_fresh_module('queue', blocked=['_queue'])
c_queue = support.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):
        # The sleep isn't necessary, but is intended to give the blocking
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

py_coll = support.import_fresh_module('collections', blocked=['_collections'])
c_coll = support.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:
    def test_init(self):
        OrderedDict = self.OrderedDict
        with self.assertRaises(TypeError):
# xml.etree test for cElementTree
import sys, struct
from test import support
from test.support 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'])


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):
            del element.tag
        self.assertEqual(element.tag, 'TAG')
Example #23
0
from contextlib import contextmanager
import linecache
import os
from io import StringIO
import sys
import unittest
from test import support
from test.support.script_helper import assert_python_ok, assert_python_failure

from test.test_warnings.data import stacklevel as warning_tests

import warnings as original_warnings

py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])


@contextmanager
def warnings_state(module):
    """Use a specific warnings implementation in warning_tests."""
    global __warningregistry__
    for to_clear in (sys, warning_tests):
        try:
            to_clear.__warningregistry__.clear()
        except AttributeError:
            pass
    try:
        __warningregistry__.clear()
    except NameError:
        pass
    original_warnings = warning_tests.warnings
Example #24
0
 def test_synthesize(self):
     webbrowser = support.import_fresh_module('webbrowser')
     name = os.path.basename(sys.executable).lower()
     webbrowser.register(name, None, webbrowser.GenericBrowser(name))
     webbrowser.get(sys.executable)
Example #25
0
 def test_no_frozen_importlib(self):
     # Should be able to import w/o _frozen_importlib being defined.
     module = support.import_fresh_module('importlib', blocked=['_frozen_importlib'])
     self.assertFalse(isinstance(module.__loader__,
                                 machinery.FrozenImporter))
"""Unittests for heapq."""

import sys
import random

from test import support
from unittest import TestCase, skipUnless

py_heapq = support.import_fresh_module('heapq', blocked=['_heapq'])
c_heapq = support.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', '_nlargest', '_nsmallest']

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')


class TestHeap(TestCase):
    module = None

    def test_push_pop(self):
import hashlib
import importlib
import itertools
import os
import sys
import threading
import unittest
import warnings
from test import support
from test.support import _4G, bigmemtest, import_fresh_module
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'])

try:
    import _blake2
except ImportError:
    _blake2 = None

requires_blake2 = unittest.skipUnless(_blake2, 'requires _blake2')

try:
    import _sha3
except ImportError:
    _sha3 = None

requires_sha3 = unittest.skipUnless(_sha3, 'requires _sha3')
Example #28
0
"""Unittests for heapq."""

import sys
import random
import unittest

from test import support
from unittest import TestCase, skipUnless

py_heapq = support.import_fresh_module('heapq', blocked=['_heapq'])
c_heapq = support.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', '_heapreplace_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')


class TestHeap:

    def test_push_pop(self):
Example #29
0
#
# Copyright (C) 2001-2012 Python Software Foundation. All Rights Reserved.
# Modified and extended by Stefan Krah.
#

# Usage: ../../../python bench.py

import time
from math import log, ceil
try:
    from test.support import import_fresh_module
except ImportError:
    from test.test_support import import_fresh_module

C = import_fresh_module('decimal', fresh=['_decimal'])
P = import_fresh_module('decimal', blocked=['_decimal'])


# Pi function from the decimal.py documentation
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 os
import json
import doctest
import unittest

from test import support

# import json with and without accelerations
cjson = support.import_fresh_module('json', fresh=['_json'])
pyjson = support.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
class TestPyTest(PyTest):
    def test_pyjson(self):
Example #31
0
import unittest
import os
from test.support import TESTFN, import_fresh_module

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'}

    format_funcs = {'S_ISBLK', 'S_ISCHR', 'S_ISDIR', 'S_ISFIFO', 'S_ISLNK',
                    'S_ISREG', 'S_ISSOCK'}

    stat_struct = {
        'ST_MODE': 0,
        'ST_INO': 1,
        'ST_DEV': 2,
        'ST_NLINK': 3,
        'ST_UID': 4,
        'ST_GID': 5,
        'ST_SIZE': 6,
        'ST_ATIME': 7,
        'ST_MTIME': 8,
        'ST_CTIME': 9}
Example #32
0
import itertools
import os
import sys
try:
    import threading
except ImportError:
    threading = None
import unittest
import warnings
from test import support
from test.support import _4G, bigmemtest, import_fresh_module

# 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'])

def hexstr(s):
    assert isinstance(s, bytes), repr(s)
    h = "0123456789abcdef"
    r = ''
    for i in s:
        r += h[(i >> 4) & 0xF] + h[i & 0xF]
    return r


class HashLibTestCase(unittest.TestCase):
    supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
                             'sha224', 'SHA224', 'sha256', 'SHA256',
                             'sha384', 'SHA384', 'sha512', 'SHA512')
Example #33
0
 def testWithoutThreading(self):
     bz2 = support.import_fresh_module("bz2", blocked=("threading",))
     with bz2.BZ2File(self.filename, "wb") as f:
         f.write(b"abc")
     with bz2.BZ2File(self.filename, "rb") as f:
         self.assertEqual(f.read(), b"abc")
Example #34
0
#

#
# Usage: python deccheck.py [--short|--medium|--long|--all]
#

import sys, random
from copy import copy
from collections import defaultdict
from test.support import import_fresh_module
from randdec import randfloat, all_unary, all_binary, all_ternary
from randdec import unary_optarg, binary_optarg, ternary_optarg
from formathelper import rand_format, rand_locale
from _pydecimal import _dec_from_triple

C = import_fresh_module("decimal", fresh=["_decimal"])
P = import_fresh_module("decimal", blocked=["_decimal"])
EXIT_STATUS = 0


# Contains all categories of Decimal methods.
Functions = {
    # Plain unary:
    "unary": (
        "__abs__",
        "__bool__",
        "__ceil__",
        "__complex__",
        "__copy__",
        "__floor__",
        "__float__",
import unittest
import pickle
import sys

from test import support

py_operator = support.import_fresh_module('operator', blocked=['_operator'])
c_operator = support.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):
        return len(self.lst)
    def __getitem__(self, i):
        return self.lst[i]
    def __add__(self, other):
Example #36
0
import unittest.mock
from test import support
import builtins
import contextlib
import copy
import io
import os
import pickle
import shutil
import subprocess
import sys

py_uuid = support.import_fresh_module('uuid', blocked=['_uuid'])
c_uuid = support.import_fresh_module('uuid', fresh=['_uuid'])


def importable(name):
    try:
        __import__(name)
        return True
    except:
        return False


class BaseTestUUID:
    uuid = None

    def test_UUID(self):
        equal = self.assertEqual
        ascending = []
        for (string, curly, hex, bytes, bytes_le, fields, integer, urn,
Example #37
0
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


py_coll = support.import_fresh_module('collections', blocked=['_collections'])
c_coll = support.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:

    def test_init(self):
Example #38
0
import unittest
import sys
import os
from test import support

# Skip this test if the _tkinter module wasn't built.
_tkinter = support.import_module('_tkinter')

# Make sure tkinter._fix runs to set up the environment
support.import_fresh_module('tkinter')

from tkinter import Tcl
from _tkinter import TclError

try:
    from _testcapi import INT_MAX, PY_SSIZE_T_MAX
except ImportError:
    INT_MAX = PY_SSIZE_T_MAX = sys.maxsize

tcl_version = _tkinter.TCL_VERSION.split('.')
try:
    for i in range(len(tcl_version)):
        tcl_version[i] = int(tcl_version[i])
except ValueError:
    pass
tcl_version = tuple(tcl_version)

_tk_patchlevel = None
def get_tk_patchlevel():
    global _tk_patchlevel
    if _tk_patchlevel is None:
Example #39
0
import unittest
import os
import sys
from test.support import TESTFN, import_fresh_module

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'
    }

    format_funcs = {
        'S_ISBLK', 'S_ISCHR', 'S_ISDIR', 'S_ISFIFO', 'S_ISLNK', 'S_ISREG',
        'S_ISSOCK'
    }

    stat_struct = {
        'ST_MODE': 0,
        'ST_INO': 1,
Example #40
0
 def test_import_fresh_module(self):
     support.import_fresh_module("ftplib")
Example #41
0
import unittest
import sys
import os
from test import support

# Skip this test if the _tkinter module wasn't built.
_tkinter = support.import_module("_tkinter")

# Make sure tkinter._fix runs to set up the environment
support.import_fresh_module("tkinter")

from tkinter import Tcl
from _tkinter import TclError

try:
    from _testcapi import INT_MAX, PY_SSIZE_T_MAX
except ImportError:
    INT_MAX = PY_SSIZE_T_MAX = sys.maxsize

tcl_version = _tkinter.TCL_VERSION.split(".")
try:
    for i in range(len(tcl_version)):
        tcl_version[i] = int(tcl_version[i])
except ValueError:
    pass
tcl_version = tuple(tcl_version)

_tk_patchlevel = None


def get_tk_patchlevel():
Example #42
0
from contextlib import contextmanager
import linecache
import os
from io import StringIO
import re
import sys
import textwrap
import unittest
from test import support
from test.support.script_helper import assert_python_ok, assert_python_failure

from test.test_warnings.data import stacklevel as warning_tests

import warnings as original_warnings

py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])

@contextmanager
def warnings_state(module):
    """Use a specific warnings implementation in warning_tests."""
    global __warningregistry__
    for to_clear in (sys, warning_tests):
        try:
            to_clear.__warningregistry__.clear()
        except AttributeError:
            pass
    try:
        __warningregistry__.clear()
    except NameError:
        pass
Example #43
0
import collections
import sys
import unittest
from test import support
from weakref import proxy
import pickle
from random import choice

import functools

original_functools = functools
py_functools = support.import_fresh_module('functools', blocked=['_functools'])
c_functools = support.import_fresh_module('functools', fresh=['_functools'])

class BaseTest(unittest.TestCase):

    """Base class required for testing C and Py implementations."""

    def setUp(self):

        # The module must be explicitly set so that the proper
        # interaction between the c module and the python module
        # can be controlled.
        self.partial = self.module.partial
        super(BaseTest, self).setUp()

class BaseTestC(BaseTest):
    module = c_functools

class BaseTestPy(BaseTest):
    module = py_functools
Example #44
0
#!/usr/bin/env python

#
# Copyright (C) 2001-2012 Python Software Foundation. All Rights Reserved.
# Modified and extended by Stefan Krah.
#

# Usage: ../../../python bench.py


import time
from math import log, ceil
from test.support import import_fresh_module

C = import_fresh_module('decimal', fresh=['_decimal'])
P = import_fresh_module('decimal', blocked=['_decimal'])


# Pi function from the decimal.py documentation
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

def pi_cdecimal():
Example #45
0
import collections
from itertools import permutations
import pickle
from random import choice
import sys
from test import support
import unittest
from weakref import proxy

import functools

py_functools = support.import_fresh_module('functools', blocked=['_functools'])
c_functools = support.import_fresh_module('functools', fresh=['_functools'])

decimal = support.import_fresh_module('decimal', fresh=['_decimal'])


def capture(*args, **kw):
    """capture all positional and keyword arguments"""
    return args, kw


def signature(part):
    """ return the signature of a partial object """
    return (part.func, part.args, part.keywords, part.__dict__)


class TestPartial:

    def test_basic_examples(self):
        p = self.partial(capture, 1, 2, a=10, b=20)
Example #46
0
import unittest
from test.support import import_module, import_fresh_module

# Skip test if _thread or _tkinter wasn't built or idlelib was deleted.
import_module('threading')  # imported by PyShell, imports _thread
tk = import_module('tkinter')  # imports _tkinter
idletest = import_module('idlelib.idle_test')
# Make sure TCL_LIBRARY is set properly on Windows.  Note that this will
# cause a warning about test_idle modifying the environment
import_fresh_module('tkinter._fix')

# Without test_main present, regrtest.runtest_inner (line1219) calls
# unittest.TestLoader().loadTestsFromModule(this_module) which calls
# load_tests() if it finds it. (Unittest.main does the same.)
load_tests = idletest.load_tests

if __name__ == '__main__':
    unittest.main(verbosity=2, exit=False)
import sys
import unittest
from test import support
from collections import UserList

py_bisect = support.import_fresh_module('bisect', blocked=['_bisect'])
c_bisect = support.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


class TestBisect: