Python test.test_support.import_module() Examples

The following are 30 code examples of test.test_support.import_module(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module test.test_support , or try the search function .
Example #1
Source File: regrtest.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def skip_conditional_support(test_module,module_name):
    try:
        test_support.import_module(module_name)
    except unittest.SkipTest:
        return '\n' + test_module
    return ""



# Map sys.platform to a string containing the basenames of tests
# expected to be skipped on that platform.
#
# Special cases:
#     test_pep277
#         The _ExpectedSkips constructor adds this to the set of expected
#         skips if not os.path.supports_unicode_filenames.
#     test_socket_ssl
#         Controlled by test_socket_ssl.skip_expected.  Requires the network
#         resource, and a socket module with ssl support.
#     test_timeout
#         Controlled by test_timeout.skip_expected.  Requires the network
#         resource and a socket module.
#
# Tests that are expected to be skipped everywhere except on one platform
# are also handled separately. 
Example #2
Source File: test_weakref.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def collect_in_thread(period=0.001):
    """
    Ensure GC collections happen in a different thread, at a high frequency.
    """
    threading = test_support.import_module('threading')
    please_stop = False

    def collect():
        while not please_stop:
            time.sleep(period)
            gc.collect()

    with test_support.disable_gc():
        old_interval = sys.getcheckinterval()
        sys.setcheckinterval(20)
        t = threading.Thread(target=collect)
        t.start()
        try:
            yield
        finally:
            please_stop = True
            t.join()
            sys.setcheckinterval(old_interval) 
Example #3
Source File: regrtest.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def skip_conditional_support(test_module,module_name):
    try:
        test_support.import_module(module_name)
    except unittest.SkipTest:
        return '\n' + test_module
    return ""



# Map sys.platform to a string containing the basenames of tests
# expected to be skipped on that platform.
#
# Special cases:
#     test_pep277
#         The _ExpectedSkips constructor adds this to the set of expected
#         skips if not os.path.supports_unicode_filenames.
#     test_socket_ssl
#         Controlled by test_socket_ssl.skip_expected.  Requires the network
#         resource, and a socket module with ssl support.
#     test_timeout
#         Controlled by test_timeout.skip_expected.  Requires the network
#         resource and a socket module.
#
# Tests that are expected to be skipped everywhere except on one platform
# are also handled separately. 
Example #4
Source File: test_cmd.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                        trace=0, count=1)
    tracer.run('reload(cmd);test_main()')
    r=tracer.results()
    print "Writing coverage results..."
    r.write_results(show_missing=True, summary=True, coverdir=coverdir) 
Example #5
Source File: test_doctest.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                         trace=0, count=1)
    tracer.run('reload(doctest); test_main()')
    r = tracer.results()
    print 'Writing coverage results...'
    r.write_results(show_missing=True, summary=True,
                    coverdir=coverdir) 
Example #6
Source File: test_cmd.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                        trace=0, count=1)
    tracer.run('reload(cmd);test_main()')
    r=tracer.results()
    print "Writing coverage results..."
    r.write_results(show_missing=True, summary=True, coverdir=coverdir) 
Example #7
Source File: test_build_ext.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #8
Source File: test_build_ext.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #9
Source File: test_build_ext.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #10
Source File: test_build_ext.py    From datafari with Apache License 2.0 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #11
Source File: test_cmd.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                        trace=0, count=1)
    tracer.run('reload(cmd);test_main()')
    r=tracer.results()
    print "Writing coverage results..."
    r.write_results(show_missing=True, summary=True, coverdir=coverdir) 
Example #12
Source File: test_doctest.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                         trace=0, count=1)
    tracer.run('reload(doctest); test_main()')
    r = tracer.results()
    print 'Writing coverage results...'
    r.write_results(show_missing=True, summary=True,
                    coverdir=coverdir) 
Example #13
Source File: test_pyclbr.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_easy(self):
        self.checkModule('pyclbr')
        self.checkModule('doctest', ignore=("DocTestCase",))
        # Silence Py3k warning
        rfc822 = import_module('rfc822', deprecated=True)
        self.checkModule('rfc822', rfc822)
        self.checkModule('difflib') 
Example #14
Source File: test_build_ext.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #15
Source File: test_build_ext.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #16
Source File: test_doctest.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                         trace=0, count=1)
    tracer.run('reload(doctest); test_main()')
    r = tracer.results()
    print 'Writing coverage results...'
    r.write_results(show_missing=True, summary=True,
                    coverdir=coverdir) 
Example #17
Source File: test_pyclbr.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_easy(self):
        self.checkModule('pyclbr')
        self.checkModule('doctest', ignore=("DocTestCase",))
        # Silence Py3k warning
        rfc822 = import_module('rfc822', deprecated=True)
        self.checkModule('rfc822', rfc822)
        self.checkModule('difflib') 
Example #18
Source File: test_build_ext.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #19
Source File: test_build_ext.py    From Computable with MIT License 5 votes vote down vote up
def test_setuptools_compat(self):
        import distutils.core, distutils.extension, distutils.command.build_ext
        saved_ext = distutils.extension.Extension
        try:
            # on some platforms, it loads the deprecated "dl" module
            test_support.import_module('setuptools_build_ext', deprecated=True)

            # theses import patch Distutils' Extension class
            from setuptools_build_ext import build_ext as setuptools_build_ext
            from setuptools_extension import Extension

            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
            etree_ext = Extension('lxml.etree', [etree_c])
            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
            cmd = setuptools_build_ext(dist)
            cmd.ensure_finalized()
            cmd.inplace = 1
            cmd.distribution.package_dir = {'': 'src'}
            cmd.distribution.packages = ['lxml', 'lxml.html']
            curdir = os.getcwd()
            ext = sysconfig.get_config_var("SO")
            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
            path = cmd.get_ext_fullpath('lxml.etree')
            self.assertEqual(wanted, path)
        finally:
            # restoring Distutils' Extension class otherwise its broken
            distutils.extension.Extension = saved_ext
            distutils.core.Extension = saved_ext
            distutils.command.build_ext.Extension = saved_ext 
Example #20
Source File: test_cmd.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                        trace=0, count=1)
    tracer.run('reload(cmd);test_main()')
    r=tracer.results()
    print "Writing coverage results..."
    r.write_results(show_missing=True, summary=True, coverdir=coverdir) 
Example #21
Source File: test_doctest.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                         trace=0, count=1)
    tracer.run('reload(doctest); test_main()')
    r = tracer.results()
    print 'Writing coverage results...'
    r.write_results(show_missing=True, summary=True,
                    coverdir=coverdir) 
Example #22
Source File: test_pyclbr.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_easy(self):
        self.checkModule('pyclbr')
        self.checkModule('doctest', ignore=("DocTestCase",))
        # Silence Py3k warning
        rfc822 = import_module('rfc822', deprecated=True)
        self.checkModule('rfc822', rfc822)
        self.checkModule('difflib') 
Example #23
Source File: test_doctest.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                         trace=0, count=1)
    tracer.run('reload(doctest); test_main()')
    r = tracer.results()
    print 'Writing coverage results...'
    r.write_results(show_missing=True, summary=True,
                    coverdir=coverdir) 
Example #24
Source File: test_cmd.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                        trace=0, count=1)
    tracer.run('reload(cmd);test_main()')
    r=tracer.results()
    print "Writing coverage results..."
    r.write_results(show_missing=True, summary=True, coverdir=coverdir) 
Example #25
Source File: test_posixpath.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_expanduser_pwd(self):
        pwd = support.import_module('pwd')

        self.assertIsInstance(posixpath.expanduser("~/"), str)

        # if home directory == root directory, this test makes no sense
        if posixpath.expanduser("~") != '/':
            self.assertEqual(
                posixpath.expanduser("~") + "/",
                posixpath.expanduser("~/")
            )
        self.assertIsInstance(posixpath.expanduser("~root/"), str)
        self.assertIsInstance(posixpath.expanduser("~foo/"), str)

        with support.EnvironmentVarGuard() as env:
            # expanduser should fall back to using the password database
            del env['HOME']

            home = pwd.getpwuid(os.getuid()).pw_dir
            # $HOME can end with a trailing /, so strip it (see #17809)
            home = home.rstrip("/") or '/'
            self.assertEqual(posixpath.expanduser("~"), home)

            # bpo-10496: If the HOME environment variable is not set and the
            # user (current identifier or name in the path) doesn't exist in
            # the password database (pwd.getuid() or pwd.getpwnam() fail),
            # expanduser() must return the path unchanged.
            def raise_keyerror(*args):
                raise KeyError

            with support.swap_attr(pwd, 'getpwuid', raise_keyerror), \
                 support.swap_attr(pwd, 'getpwnam', raise_keyerror):
                for path in ('~', '~/.local', '~vstinner/'):
                    self.assertEqual(posixpath.expanduser(path), path) 
Example #26
Source File: test_doctest.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                         trace=0, count=1)
    tracer.run('reload(doctest); test_main()')
    r = tracer.results()
    print 'Writing coverage results...'
    r.write_results(show_missing=True, summary=True,
                    coverdir=coverdir) 
Example #27
Source File: test_pyclbr.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_easy(self):
        self.checkModule('pyclbr')
        self.checkModule('doctest', ignore=("DocTestCase",))
        # Silence Py3k warning
        rfc822 = import_module('rfc822', deprecated=True)
        self.checkModule('rfc822', rfc822)
        self.checkModule('difflib') 
Example #28
Source File: regrtest.py    From CTFCrackTools with GNU General Public License v3.0 4 votes vote down vote up
def dash_R_cleanup(fs, ps, pic, abcs):
    import gc, copy_reg
    import _strptime, linecache
    dircache = test_support.import_module('dircache', deprecated=True)
    import urlparse, urllib, urllib2, mimetypes, doctest
    import struct, filecmp
    from distutils.dir_util import _path_created

    # Clear the warnings registry, so they can be displayed again
    for mod in sys.modules.values():
        if hasattr(mod, '__warningregistry__'):
            del mod.__warningregistry__

    # Restore some original values.
    warnings.filters[:] = fs
    copy_reg.dispatch_table.clear()
    copy_reg.dispatch_table.update(ps)
    sys.path_importer_cache.clear()
    sys.path_importer_cache.update(pic)

    # clear type cache
    sys._clear_type_cache()

    # Clear ABC registries, restoring previously saved ABC registries.
    for abc, registry in abcs.items():
        abc._abc_registry = registry.copy()
        abc._abc_cache.clear()
        abc._abc_negative_cache.clear()

    # Clear assorted module caches.
    _path_created.clear()
    re.purge()
    _strptime._regex_cache.clear()
    urlparse.clear_cache()
    urllib.urlcleanup()
    urllib2.install_opener(None)
    dircache.reset()
    linecache.clearcache()
    mimetypes._default_mime_types()
    filecmp._cache.clear()
    struct._clearcache()
    doctest.master = None

    # Collect cyclic trash.
    gc.collect() 
Example #29
Source File: test_io.py    From CTFCrackTools with GNU General Public License v3.0 4 votes vote down vote up
def check_interrupted_write_retry(self, item, **fdopen_kwargs):
        """Check that a buffered write, when it gets interrupted (either
        returning a partial result or EINTR), properly invokes the signal
        handler and retries if the latter returned successfully."""
        select = support.import_module("select")
        # A quantity that exceeds the buffer size of an anonymous pipe's
        # write end.
        N = 1024 * 1024
        r, w = os.pipe()
        fdopen_kwargs["closefd"] = False
        # We need a separate thread to read from the pipe and allow the
        # write() to finish.  This thread is started after the SIGALRM is
        # received (forcing a first EINTR in write()).
        read_results = []
        write_finished = False
        def _read():
            while not write_finished:
                while r in select.select([r], [], [], 1.0)[0]:
                    s = os.read(r, 1024)
                    read_results.append(s)
        t = threading.Thread(target=_read)
        t.daemon = True
        def alarm1(sig, frame):
            signal.signal(signal.SIGALRM, alarm2)
            signal.alarm(1)
        def alarm2(sig, frame):
            t.start()
        signal.signal(signal.SIGALRM, alarm1)
        try:
            wio = self.io.open(w, **fdopen_kwargs)
            signal.alarm(1)
            # Expected behaviour:
            # - first raw write() is partial (because of the limited pipe buffer
            #   and the first alarm)
            # - second raw write() returns EINTR (because of the second alarm)
            # - subsequent write()s are successful (either partial or complete)
            self.assertEqual(N, wio.write(item * N))
            wio.flush()
            write_finished = True
            t.join()
            self.assertEqual(N, sum(len(x) for x in read_results))
        finally:
            write_finished = True
            os.close(w)
            os.close(r)
            # This is deliberate. If we didn't close the file descriptor
            # before closing wio, wio would try to flush its internal
            # buffer, and could block (in case of failure).
            try:
                wio.close()
            except IOError as e:
                if e.errno != errno.EBADF:
                    raise 
Example #30
Source File: test_io.py    From gcblue with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def check_interrupted_write_retry(self, item, **fdopen_kwargs):
        """Check that a buffered write, when it gets interrupted (either
        returning a partial result or EINTR), properly invokes the signal
        handler and retries if the latter returned successfully."""
        select = support.import_module("select")
        # A quantity that exceeds the buffer size of an anonymous pipe's
        # write end.
        N = support.PIPE_MAX_SIZE
        r, w = os.pipe()
        fdopen_kwargs["closefd"] = False
        # We need a separate thread to read from the pipe and allow the
        # write() to finish.  This thread is started after the SIGALRM is
        # received (forcing a first EINTR in write()).
        read_results = []
        write_finished = False
        def _read():
            while not write_finished:
                while r in select.select([r], [], [], 1.0)[0]:
                    s = os.read(r, 1024)
                    read_results.append(s)
        t = threading.Thread(target=_read)
        t.daemon = True
        def alarm1(sig, frame):
            signal.signal(signal.SIGALRM, alarm2)
            signal.alarm(1)
        def alarm2(sig, frame):
            t.start()
        signal.signal(signal.SIGALRM, alarm1)
        try:
            wio = self.io.open(w, **fdopen_kwargs)
            signal.alarm(1)
            # Expected behaviour:
            # - first raw write() is partial (because of the limited pipe buffer
            #   and the first alarm)
            # - second raw write() returns EINTR (because of the second alarm)
            # - subsequent write()s are successful (either partial or complete)
            self.assertEqual(N, wio.write(item * N))
            wio.flush()
            write_finished = True
            t.join()
            self.assertEqual(N, sum(len(x) for x in read_results))
        finally:
            write_finished = True
            os.close(w)
            os.close(r)
            # This is deliberate. If we didn't close the file descriptor
            # before closing wio, wio would try to flush its internal
            # buffer, and could block (in case of failure).
            try:
                wio.close()
            except IOError as e:
                if e.errno != errno.EBADF:
                    raise