def test_issue13210(self): # invoking "continue" on a non-main thread triggered an exception # inside signal.signal # raises SkipTest if python was built without threads support.import_module("threading") with open(support.TESTFN, "wb") as f: f.write( textwrap.dedent( """ import threading import pdb def start_pdb(): pdb.Pdb().set_trace() x = 1 y = 1 t = threading.Thread(target=start_pdb) t.start()""" ).encode("ascii") ) cmd = [sys.executable, "-u", support.TESTFN] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) self.addCleanup(proc.stdout.close) stdout, stderr = proc.communicate(b"cont\n") self.assertNotIn("Error", stdout.decode(), "Got an error running test script under PDB")
def test_finalize_runnning_thread(self): # Issue 1402: the PyGILState_Ensure / _Release functions may be called # very late on python exit: on deallocation of a running thread for # example. import_module("ctypes") rc, out, err = assert_python_failure( "-c", """if 1: import ctypes, sys, time, _thread # This lock is used as a simple event variable. ready = _thread.allocate_lock() ready.acquire() # Module globals are cleared before __del__ is run # So we save the functions in class dict class C: ensure = ctypes.pythonapi.PyGILState_Ensure release = ctypes.pythonapi.PyGILState_Release def __del__(self): state = self.ensure() self.release(state) def waitingThread(): x = C() ready.release() time.sleep(100) _thread.start_new_thread(waitingThread, ()) ready.acquire() # Be sure the other thread is waiting. sys.exit(42) """, ) self.assertEqual(rc, 42)
def test_untested_modules_can_be_imported(self): untested = ('bdb', 'encodings', 'formatter', 'nturl2path', 'tabnanny') with support.check_warnings(quiet=True): for name in untested: try: support.import_module('test.test_{}'.format(name)) except unittest.SkipTest: importlib.import_module(name) else: self.fail('{} has tests even though test_sundry claims ' 'otherwise'.format(name)) # distutils not available on UWP if sys.platform != 'uwp': import distutils.bcppcompiler import distutils.ccompiler import distutils.cygwinccompiler import distutils.filelist import distutils.text_file import distutils.unixccompiler import distutils.command.bdist_dumb if sys.platform.startswith('win'): import distutils.command.bdist_msi import distutils.command.bdist import distutils.command.bdist_rpm import distutils.command.bdist_wininst import distutils.command.build_clib import distutils.command.build_ext import distutils.command.build import distutils.command.clean import distutils.command.config import distutils.command.install_data import distutils.command.install_egg_info import distutils.command.install_headers import distutils.command.install_lib import distutils.command.register import distutils.command.sdist import distutils.command.upload import html.entities try: import tty # Not available on Windows except ImportError: if support.verbose: print("skipping tty")
def test_refcount_errors(self): self.preclean() # Verify the "handling" of objects with broken refcounts # Skip the test if ctypes is not available import_module("ctypes") import subprocess code = textwrap.dedent(''' from test.support import gc_collect, SuppressCrashReport a = [1, 2, 3] b = [a] # Avoid coredump when Py_FatalError() calls abort() SuppressCrashReport().__enter__() # Simulate the refcount of "a" being too low (compared to the # references held on it by live data), but keeping it above zero # (to avoid deallocating it): import ctypes ctypes.pythonapi.Py_DecRef(ctypes.py_object(a)) # The garbage collector should now have a fatal error # when it reaches the broken object gc_collect() ''') p = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() p.stdout.close() p.stderr.close() # Verify that stderr has a useful error message: self.assertRegex(stderr, br'gcmodule\.c:[0-9]+: gc_decref: Assertion "gc_get_refs\(g\) > 0" failed.') self.assertRegex(stderr, br'refcount is too small') self.assertRegex(stderr, br'object : \[1, 2, 3\]') self.assertRegex(stderr, br'type : list') self.assertRegex(stderr, br'refcount: 1') # "address : 0x7fb5062efc18" # "address : 7FB5062EFC18" self.assertRegex(stderr, br'address : [0-9a-fA-Fx]+')
def test_coverage(coverdir): trace = 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)
def test_windows_message(self): """Should fill in unknown error code in Windows error message""" ctypes = import_module('ctypes') # this error code has no message, Python formats it as hexadecimal code = 3765269347 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
def test_coverage(coverdir): trace = support.import_module('trace') tracer=trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,], trace=0, count=1) tracer.run('import importlib; importlib.reload(cmd); test_main()') r=tracer.results() print("Writing coverage results...") r.write_results(show_missing=True, summary=True, coverdir=coverdir)
def setUp(self): #print("DBG:CB.setUp()") # fire up the test subject self.expty = import_module('editline.tests.expty') # should use sys.ps1 for the prompt, but it seems to only be define # when the system actually IS interactive... ? self.tool = self.expty.InteractivePTY(sys.executable, '>>> ', 'exit()') cruft = self.tool.first_prompt()
def test_multiprocessing_exceptions(self): module = support.import_module('multiprocessing.context') for name, exc in get_exceptions(module): with self.subTest(name): self.assertEqual(reverse_mapping('multiprocessing.context', name), ('multiprocessing', name)) self.assertEqual(mapping('multiprocessing', name), ('multiprocessing.context', name))
def test_200_terminal_size(self): rows = int(subprocess.check_output(['tput', 'lines']).decode()) columns = int(subprocess.check_output(['tput', 'cols']).decode()) self.assertNotEqual(columns, 0) editline = import_module('editline.editline') el = editline.EditLine("testcase", sys.stdin, sys.stdout, sys.stderr) el_cols = el.gettc('co') self.assertEqual(el_cols, columns)
def test_triplet_in_ext_suffix(self): ctypes = import_module('ctypes') import platform, re machine = platform.machine() suffix = sysconfig.get_config_var('EXT_SUFFIX') if re.match('(aarch64|arm|mips|ppc|powerpc|s390|sparc)', machine): self.assertTrue('linux' in suffix, suffix) if re.match('(i[3-6]86|x86_64)$', machine): if ctypes.sizeof(ctypes.c_char_p()) == 4: self.assertTrue(suffix.endswith('i386-linux-gnu.so') or suffix.endswith('x86_64-linux-gnux32.so'), suffix) else: # 8 byte pointer size self.assertTrue(suffix.endswith('x86_64-linux-gnu.so'), suffix)
def test_interrupted_write(self): # BaseHandler._write() and _flush() have to write all data, even if # it takes multiple send() calls. Test this by interrupting a send() # call with a Unix signal. threading = support.import_module("threading") pthread_kill = support.get_attribute(signal, "pthread_kill") def app(environ, start_response): start_response("200 OK", []) return [b'\0' * support.SOCK_MAX_SIZE] class WsgiHandler(NoLogRequestHandler, WSGIRequestHandler): pass server = make_server(support.HOST, 0, app, handler_class=WsgiHandler) self.addCleanup(server.server_close) interrupted = threading.Event() def signal_handler(signum, frame): interrupted.set() original = signal.signal(signal.SIGUSR1, signal_handler) self.addCleanup(signal.signal, signal.SIGUSR1, original) received = None main_thread = threading.get_ident() def run_client(): http = HTTPConnection(*server.server_address) http.request("GET", "/") with http.getresponse() as response: response.read(100) # The main thread should now be blocking in a send() system # call. But in theory, it could get interrupted by other # signals, and then retried. So keep sending the signal in a # loop, in case an earlier signal happens to be delivered at # an inconvenient moment. while True: pthread_kill(main_thread, signal.SIGUSR1) if interrupted.wait(timeout=float(1)): break nonlocal received received = len(response.read()) http.close() background = threading.Thread(target=run_client) background.start() server.handle_request() background.join() self.assertEqual(received, support.SOCK_MAX_SIZE - 100)
def run_pty(script, input=b"dummy input\r", env=None): pty = import_module('pty') output = bytearray() [master, slave] = pty.openpty() args = (sys.executable, '-c', script) proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave, env=env) os.close(slave) with ExitStack() as cleanup: cleanup.enter_context(proc) def terminate(proc): try: proc.terminate() except ProcessLookupError: # Workaround for Open/Net BSD bug (Issue 16762) pass cleanup.callback(terminate, proc) cleanup.callback(os.close, master) # Avoid using DefaultSelector and PollSelector. Kqueue() does not # work with pseudo-terminals on OS X < 10.9 (Issue 20365) and Open # BSD (Issue 20667). Poll() does not work with OS X 10.6 or 10.4 # either (Issue 20472). Hopefully the file descriptor is low enough # to use with select(). sel = cleanup.enter_context(selectors.SelectSelector()) sel.register(master, selectors.EVENT_READ | selectors.EVENT_WRITE) os.set_blocking(master, False) while True: for [_, events] in sel.select(): if events & selectors.EVENT_READ: try: chunk = os.read(master, 0x10000) except OSError as err: # Linux raises EIO when slave is closed (Issue 5380) if err.errno != EIO: raise chunk = b"" if not chunk: return output output.extend(chunk) if events & selectors.EVENT_WRITE: try: input = input[os.write(master, input):] except OSError as err: # Apparently EIO means the slave was closed if err.errno != EIO: raise input = b"" # Stop writing if not input: sel.modify(master, selectors.EVENT_READ)
def dash_R_cleanup(fs, ps, pic, abcs): import gc, copyreg import _strptime, linecache dircache = support.import_module('dircache', deprecated=True) import urllib.parse, urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, 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 list(sys.modules.values()): if hasattr(mod, '__warningregistry__'): del mod.__warningregistry__ # Restore some original values. warnings.filters[:] = fs copyreg.dispatch_table.clear() copyreg.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 list(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() urllib.parse.clear_cache() urllib.request.urlcleanup() urllib.request.install_opener(None) dircache.reset() linecache.clearcache() mimetypes._default_mime_types() filecmp._cache.clear() struct._clearcache() doctest.master = None # Collect cyclic trash. gc.collect()
def test_triplet_in_ext_suffix(self): ctypes = import_module("ctypes") import platform, re machine = platform.machine() suffix = sysconfig.get_config_var("EXT_SUFFIX") if re.match("(aarch64|arm|mips|ppc|powerpc|s390|sparc)", machine): self.assertTrue("linux" in suffix, suffix) if re.match("(i[3-6]86|x86_64)$", machine): if ctypes.sizeof(ctypes.c_char_p()) == 4: self.assertTrue( suffix.endswith("i386-linux-gnu.so") or suffix.endswith("i686-linux-android.so") or suffix.endswith("x86_64-linux-gnux32.so"), suffix, ) else: # 8 byte pointer size self.assertTrue(suffix.endswith("x86_64-linux-gnu.so"), suffix)
def test_expanduser_pwd(self): pwd = support.import_module('pwd') self.assertIsInstance(posixpath.expanduser("~/"), str) self.assertIsInstance(posixpath.expanduser(b"~/"), bytes) # if home directory == root directory, this test makes no sense if posixpath.expanduser("~") != '/': self.assertEqual( posixpath.expanduser("~") + "/", posixpath.expanduser("~/") ) self.assertEqual( posixpath.expanduser(b"~") + b"/", posixpath.expanduser(b"~/") ) self.assertIsInstance(posixpath.expanduser("~root/"), str) self.assertIsInstance(posixpath.expanduser("~foo/"), str) self.assertIsInstance(posixpath.expanduser(b"~root/"), bytes) self.assertIsInstance(posixpath.expanduser(b"~foo/"), bytes) 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. with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError), \ mock.patch.object(pwd, 'getpwnam', side_effect=KeyError): for path in ('~', '~/.local', '~vstinner/'): self.assertEqual(posixpath.expanduser(path), path)
def test_asyncio_1(self): # asyncio cannot be imported when Python is compiled without thread # support asyncio = support.import_module('asyncio') class MyException(Exception): pass buffer = [] class CM: async def __aenter__(self): buffer.append(1) await asyncio.sleep(0.01) buffer.append(2) return self async def __aexit__(self, exc_type, exc_val, exc_tb): await asyncio.sleep(0.01) buffer.append(exc_type.__name__) async def f(): async with CM() as c: await asyncio.sleep(0.01) raise MyException buffer.append('unreachable') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: loop.run_until_complete(f()) except MyException: pass finally: loop.close() asyncio.set_event_loop(None) self.assertEqual(buffer, [1, 2, 'MyException'])
""" Tests for the threading module. """ import test.support from test.support import (verbose, import_module, cpython_only, requires_type_collecting) from test.support.script_helper import assert_python_ok, assert_python_failure import random import sys _thread = import_module('_thread') threading = import_module('threading') import time import unittest import weakref import os import subprocess from test import lock_tests from test import support # Between fork() and exec(), only async-safe functions are allowed (issues # #12316 and #11870), and fork() from a worker thread is known to trigger # problems with some operating systems (issue #3863): skip problematic tests # on platforms known to behave badly. platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', 'hp-ux11')
from test import support gdbm = support.import_module("dbm.gnu") #skip if not supported import unittest import os from test.support import verbose, TESTFN, unlink filename = TESTFN class TestGdbm(unittest.TestCase): def setUp(self): self.g = None def tearDown(self): if self.g is not None: self.g.close() unlink(filename) def test_key_methods(self): self.g = gdbm.open(filename, 'c') self.assertEqual(self.g.keys(), []) self.g['a'] = 'b' self.g['12345678910'] = '019237410982340912840198242' self.g[b'bytes'] = b'data' key_set = set(self.g.keys()) self.assertEqual(key_set, set([b'a', b'bytes', b'12345678910'])) self.assertIn(b'a', self.g) self.assertEqual(self.g[b'bytes'], b'data') key = self.g.firstkey() while key: self.assertIn(key, key_set)
import functools import os import subprocess import time import unittest from test import support support.requires('audio') winsound = support.import_module('winsound') def sound_func(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: ret = func(*args, **kwargs) except RuntimeError as e: if support.verbose: print(func.__name__, 'failed:', e) else: if support.verbose: print(func.__name__, 'returned') return ret return wrapper safe_Beep = sound_func(winsound.Beep) safe_MessageBeep = sound_func(winsound.MessageBeep) safe_PlaySound = sound_func(winsound.PlaySound)
import unittest from test.support import run_unittest, import_module # Skip tests if _ctypes module was not built. import_module('_ctypes') import ctypes.test def test_main(): skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0) suites = [unittest.makeSuite(t) for t in testcases] run_unittest(unittest.TestSuite(suites)) if __name__ == "__main__": test_main()
from test import support # If we end up with a significant number of tests that don't require # threading, this test module should be split. Right now we skip # them all if we don't have threading. threading = support.import_module('threading') from contextlib import contextmanager import imaplib import os.path import socketserver import time import calendar from test.support import reap_threads, verbose, transient_internet, run_with_tz import unittest try: import ssl except ImportError: ssl = None CERTFILE = None class TestImaplib(unittest.TestCase): def test_Internaldate2tuple(self): t0 = calendar.timegm((2000, 1, 1, 0, 0, 0, -1, -1, -1)) tt = imaplib.Internaldate2tuple( b'25 (INTERNALDATE "01-Jan-2000 00:00:00 +0000")') self.assertEqual(time.mktime(tt), t0)
import unittest from test import support import time resource = support.import_module('resource') # This test is checking a few specific problem spots with the resource module. class ResourceTest(unittest.TestCase): def test_args(self): self.assertRaises(TypeError, resource.getrlimit) self.assertRaises(TypeError, resource.getrlimit, 42, 42) self.assertRaises(TypeError, resource.setrlimit) self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42) def test_fsize_ismax(self): try: (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) except AttributeError: pass else: # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really big # number on a platform with large file support. On these platforms, # we need to test that the get/setrlimit functions properly convert # the number to a C long long and that the conversion doesn't raise # an error. self.assertEqual(resource.RLIM_INFINITY, max) resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) def test_fsize_enforced(self):
# Modified by Giampaolo Rodola' to give poplib.POP3 and poplib.POP3_SSL # a real test suite import poplib import asyncore import asynchat import socket import os import time import errno from unittest import TestCase, skipUnless from test import support as test_support threading = test_support.import_module('threading') HOST = test_support.HOST PORT = 0 # the dummy data returned by server when LIST and RETR commands are issued LIST_RESP = b'1 1\r\n2 2\r\n3 3\r\n4 4\r\n5 5\r\n.\r\n' RETR_RESP = b"""From: [email protected]\ \r\nContent-Type: text/plain\r\n\ MIME-Version: 1.0\r\n\ Subject: Dummy\r\n\ \r\n\ line1\r\n\ line2\r\n\ line3\r\n\ .\r\n"""
def test_PyThreadState_SetAsyncExc(self): ctypes = import_module("ctypes") set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc set_async_exc.argtypes = (ctypes.c_ulong, ctypes.py_object) class AsyncExc(Exception): pass exception = ctypes.py_object(AsyncExc) # First check it works when setting the exception from the same thread. tid = threading.get_ident() self.assertIsInstance(tid, int) self.assertGreater(tid, 0) try: result = set_async_exc(tid, exception) # The exception is async, so we might have to keep the VM busy until # it notices. while True: pass except AsyncExc: pass else: # This code is unreachable but it reflects the intent. If we wanted # to be smarter the above loop wouldn't be infinite. self.fail("AsyncExc not raised") try: self.assertEqual(result, 1) # one thread state modified except UnboundLocalError: # The exception was raised too quickly for us to get the result. pass # `worker_started` is set by the thread when it's inside a try/except # block waiting to catch the asynchronously set AsyncExc exception. # `worker_saw_exception` is set by the thread upon catching that # exception. worker_started = threading.Event() worker_saw_exception = threading.Event() class Worker(threading.Thread): def run(self): self.id = threading.get_ident() self.finished = False try: while True: worker_started.set() time.sleep(0.1) except AsyncExc: self.finished = True worker_saw_exception.set() t = Worker() t.daemon = True # so if this fails, we don't hang Python at shutdown t.start() if verbose: print(" started worker thread") # Try a thread id that doesn't make sense. if verbose: print(" trying nonsensical thread id") result = set_async_exc(-1, exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: print(" waiting for worker thread to get started") ret = worker_started.wait() self.assertTrue(ret) if verbose: print(" verifying worker hasn't exited") self.assertFalse(t.finished) if verbose: print(" attempting to raise asynch exception in worker") result = set_async_exc(t.id, exception) self.assertEqual(result, 1) # one thread state modified if verbose: print(" waiting for worker to say it caught the exception") worker_saw_exception.wait(timeout=10) self.assertTrue(t.finished) if verbose: print(" all OK -- joining worker") if t.finished: t.join()
import os from test.support import load_package_tests, import_module # Skip tests if we don't have threading. import_module('threading') # Skip tests if we don't have concurrent.futures. import_module('concurrent.futures') def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args)
import array import unittest from test.support import run_unittest, import_module, get_attribute import os, struct fcntl = import_module('fcntl') termios = import_module('termios') get_attribute(termios, 'TIOCGPGRP') #Can't run tests without this feature try: tty = open("/dev/tty", "r") except IOError: raise unittest.SkipTest("Unable to open /dev/tty") else: # Skip if another process is in foreground r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") tty.close() rpgrp = struct.unpack("i", r)[0] if rpgrp not in (os.getpgrp(), os.getsid(0)): raise unittest.SkipTest("Neither the process group nor the session " "are attached to /dev/tty") del tty, r, rpgrp try: import pty except ImportError: pty = None class IoctlTests(unittest.TestCase): def test_ioctl(self): # If this process has been put into the background, TIOCGPGRP returns
""" Tests for the threading module. """ import test.support from test.support import verbose, strip_python_stderr, import_module, cpython_only from test.script_helper import assert_python_ok import random import re import sys _thread = import_module('_thread') threading = import_module('threading') import time import unittest import weakref import os from test.script_helper import assert_python_ok, assert_python_failure import subprocess from test import lock_tests # Between fork() and exec(), only async-safe functions are allowed (issues # #12316 and #11870), and fork() from a worker thread is known to trigger # problems with some operating systems (issue #3863): skip problematic tests # on platforms known to behave badly. platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5', 'hp-ux11') # A trivial mutable counter.
import os import string import sys import tempfile import unittest from test.support import requires, import_module, verbose import inspect requires('curses') curses = import_module('curses') import_module('curses.panel') import_module('curses.ascii') import_module('curses.textpad') def requires_curses_func(name): return unittest.skipUnless(hasattr(curses, name), 'requires curses.%s' % name) term = os.environ.get('TERM') @unittest.skipIf(not term or term == 'unknown', '$TERM=%r, calling initscr() may cause exit' % term) @unittest.skipIf(sys.platform == 'cygwin', "cygwin's curses mostly just hangs") class TestCurses(unittest.TestCase): @classmethod def setUpClass(cls): if not sys.__stdout__.isatty(): raise unittest.SkipTest('sys.__stdout__ is not a tty')
from io import BytesIO, DEFAULT_BUFFER_SIZE import os import pickle import glob import tempfile import pathlib import random import shutil import subprocess import threading from test.support import unlink import _compression import sys # Skip tests if the bz2 module doesn't exist. bz2 = support.import_module('bz2') from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor has_cmdline_bunzip2 = None def ext_decompress(data): global has_cmdline_bunzip2 if has_cmdline_bunzip2 is None: has_cmdline_bunzip2 = bool(shutil.which('bunzip2')) if has_cmdline_bunzip2: return subprocess.check_output(['bunzip2'], input=data) else: return bz2.decompress(data)
"Test posix functions" from test import support # Skip these tests if there is no posix module. posix = support.import_module('posix') import errno import sys import time import os import pwd import shutil import stat import tempfile import unittest import warnings _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(), support.TESTFN + '-dummy-symlink') class PosixTester(unittest.TestCase): def setUp(self): # create empty file fp = open(support.TESTFN, 'w+') fp.close() self.teardown_files = [ support.TESTFN ] self._warnings_manager = support.check_warnings() self._warnings_manager.__enter__() warnings.filterwarnings('ignore', '.* potential security risk .*',
# tests __main__ module handling in multiprocessing from test import support # Skip tests if _thread or _multiprocessing wasn't built. support.import_module('_thread') support.import_module('_multiprocess') import importlib import importlib.machinery import unittest import sys import os import os.path import py_compile from test.support.script_helper import (make_pkg, make_script, make_zip_pkg, make_zip_script, assert_python_ok) if support.PGO: raise unittest.SkipTest("test is not helpful for PGO") # Look up which start methods are available to test import multiprocess as multiprocessing AVAILABLE_START_METHODS = set(multiprocessing.get_all_start_methods()) # Issue #22332: Skip tests if sem_open implementation is broken. support.import_module('multiprocess.synchronize') verbose = support.verbose test_source = """\ # multiprocessing includes all sorts of shenanigans to make __main__
from test import support syslog = support.import_module("syslog") # skip if not supported import unittest # XXX(nnorwitz): This test sucks. I don't know of a platform independent way # to verify that the messages were really logged. # The only purpose of this test is to verify the code doesn't crash or leak. class Test(unittest.TestCase): def test_openlog(self): syslog.openlog("python") # Issue #6697. self.assertRaises(UnicodeEncodeError, syslog.openlog, "\uD800") def test_syslog(self): syslog.openlog("python") syslog.syslog("test message from python test_syslog") syslog.syslog(syslog.LOG_ERR, "test error from python test_syslog") def test_closelog(self): syslog.openlog("python") syslog.closelog() def test_setlogmask(self): syslog.setlogmask(syslog.LOG_DEBUG) def test_log_mask(self): syslog.LOG_MASK(syslog.LOG_INFO)
import inspect import types import unittest from test.support import import_module asyncio = import_module("asyncio") class AwaitException(Exception): pass @types.coroutine def awaitable(*, throw=False): if throw: yield ('throw',) else: yield ('result',) def run_until_complete(coro): exc = False while True: try: if exc: exc = False fut = coro.throw(AwaitException) else: fut = coro.send(None) except StopIteration as ex: return ex.args[0]
import sys import unittest from test import support pwd = support.import_module('pwd') class PwdTest(unittest.TestCase): def test_values(self): entries = pwd.getpwall() for e in entries: self.assertEqual(len(e), 7) self.assertEqual(e[0], e.pw_name) self.assertIsInstance(e.pw_name, str) self.assertEqual(e[1], e.pw_passwd) self.assertIsInstance(e.pw_passwd, str) self.assertEqual(e[2], e.pw_uid) self.assertIsInstance(e.pw_uid, int) self.assertEqual(e[3], e.pw_gid) self.assertIsInstance(e.pw_gid, int) self.assertEqual(e[4], e.pw_gecos) self.assertIsInstance(e.pw_gecos, str) self.assertEqual(e[5], e.pw_dir) self.assertIsInstance(e.pw_dir, str) self.assertEqual(e[6], e.pw_shell) self.assertIsInstance(e.pw_shell, str) # The following won't work, because of duplicate entries # for one uid # self.assertEqual(pwd.getpwuid(e.pw_uid), e)
SimpleHTTPRequestHandler, CGIHTTPRequestHandler from http import server import os import sys import re import base64 import shutil import urllib.parse import http.client import tempfile from io import BytesIO import unittest from test import support threading = support.import_module('threading') class NoLogRequestHandler: def log_message(self, *args): # don't write log messages to stderr pass def read(self, n=None): return '' class TestServerThread(threading.Thread): def __init__(self, test_object, request_handler): threading.Thread.__init__(self) self.request_handler = request_handler
import unittest from test import support import binascii import pickle import random import sys from test.support import bigmemtest, _1G, _4G zlib = support.import_module('zlib') requires_Compress_copy = unittest.skipUnless( hasattr(zlib.compressobj(), 'copy'), 'requires Compress.copy()') requires_Decompress_copy = unittest.skipUnless( hasattr(zlib.decompressobj(), 'copy'), 'requires Decompress.copy()') class VersionTestCase(unittest.TestCase): def test_library_version(self): self.assertEqual(zlib.ZLIB_RUNTIME_VERSION[0], zlib.ZLIB_VERSION[0]) class ChecksumTestCase(unittest.TestCase): def test_crc32start(self): self.assertEqual(zlib.crc32(b''), zlib.crc32(b'', 0)) self.assertTrue(zlib.crc32(b'abc', 4294967295)) def test_crc32empty(self): self.assertEqual(zlib.crc32(b'', 0), 0) self.assertEqual(zlib.crc32(b'', 1), 1) self.assertEqual(zlib.crc32(b'', 432), 432) def test_adler32start(self): self.assertEqual(zlib.adler32(b''), zlib.adler32(b'', 1))
# test asynchat from test import support # If this fails, the test will be skipped. thread = support.import_module('_thread') import asynchat import asyncore import errno import socket import sys import time import unittest import warnings import unittest.mock try: import threading except ImportError: threading = None HOST = support.HOST SERVER_QUIT = b'QUIT\n' TIMEOUT = 3.0 if threading: class echo_server(threading.Thread): # parameter to determine the number of bytes passed back to the # client each send chunk_size = 1
import unittest from test.support import import_module # Skip test_idle if _tkinter wasn't built, if tkinter is missing, # if tcl/tk is not the 8.5+ needed for ttk widgets, # or if idlelib is missing (not installed). tk = import_module('tkinter') # Also imports _tkinter. if tk.TkVersion < 8.5: raise unittest.SkipTest("IDLE requires tk 8.5 or later.") idlelib = import_module('idlelib') # Before importing and executing more of idlelib, # tell IDLE to avoid changing the environment. idlelib.testing = True # Unittest.main and test.libregrtest.runtest.runtest_inner # call load_tests, when present here, to discover tests to run. from idlelib.idle_test import load_tests if __name__ == '__main__': tk.NoDefaultRoot() unittest.main(exit=False) tk._support_default_root = 1 tk._default_root = None
# tests __main__ module handling in multiprocessing from test import support # Skip tests if _thread or _multiprocessing wasn't built. support.import_module('_thread') support.import_module('_multiprocessing') import importlib import importlib.machinery import zipimport import unittest import sys import os import os.path import py_compile from test.script_helper import ( make_pkg, make_script, make_zip_pkg, make_zip_script, assert_python_ok, assert_python_failure, temp_dir, spawn_python, kill_python) # Look up which start methods are available to test import multiprocessing AVAILABLE_START_METHODS = set(multiprocessing.get_all_start_methods()) verbose = support.verbose test_source = """\ # multiprocessing includes all sorts of shenanigans to make __main__ # attributes accessible in the subprocess in a pickle compatible way. # We run the "doesn't work in the interactive interpreter" example from
""" Test suite for the code in msilib """ import os.path import unittest from test.support import TESTFN, import_module, unlink msilib = import_module('msilib') import msilib.schema def init_database(): path = TESTFN + '.msi' db = msilib.init_database( path, msilib.schema, 'Python Tests', 'product_code', '1.0', 'PSF', ) return db, path class MsiDatabaseTestCase(unittest.TestCase): def test_view_fetch_returns_none(self): db, db_path = init_database() properties = [] view = db.OpenView('SELECT Property, Value FROM Property') view.Execute(None) while True: record = view.Fetch() if record is None: break
# Test the windows specific win32reg module. # Only win32reg functions not hit here: FlushKey, LoadKey and SaveKey import os, sys, errno import unittest from test import support threading = support.import_module("threading") from platform import machine # Do this first so test will be skipped if module doesn't exist support.import_module('winreg', required_on=['win']) # Now import everything from winreg import * try: REMOTE_NAME = sys.argv[sys.argv.index("--remote") + 1] except (IndexError, ValueError): REMOTE_NAME = None # tuple of (major, minor) WIN_VER = sys.getwindowsversion()[:2] # Some tests should only run on 64-bit architectures where WOW64 will be. WIN64_MACHINE = True if machine() == "AMD64" else False # Starting with Windows 7 and Windows Server 2008 R2, WOW64 no longer uses # registry reflection and formerly reflected keys are shared instead. # Windows 7 and Windows Server 2008 R2 are version 6.1. Due to this, some # tests are only valid up until 6.1 HAS_REFLECTION = True if WIN_VER < (6, 1) else False # Use a per-process key to prevent concurrent test runs (buildbot!) from
from test import support # Skip tests if _multiprocessing wasn't built. support.import_module('_multiprocessing') # Skip tests if sem_open implementation is broken. support.import_module('multiprocessing.synchronize') from test.support.script_helper import assert_python_ok import contextlib import itertools import logging from logging.handlers import QueueHandler import os import queue import sys import threading import time import unittest import weakref from pickle import PicklingError from concurrent import futures from concurrent.futures._base import (PENDING, RUNNING, CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED, Future, BrokenExecutor) from concurrent.futures.process import BrokenProcessPool from multiprocessing import get_context import multiprocessing.process import multiprocessing.util
import threading import time import unittest import weakref import importlib.machinery import importlib.util from test import support from test.support import MISSING_C_DOCSTRINGS from test.support.script_helper import assert_python_failure, assert_python_ok try: import _posixsubprocess except ImportError: _posixsubprocess = None # Skip this test if the _testcapi module isn't available. _testcapi = support.import_module('_testcapi') import _testinternalcapi # Were we compiled --with-pydebug or with #define Py_DEBUG? Py_DEBUG = hasattr(sys, 'gettotalrefcount') def testfunction(self): """some doc""" return self class InstanceMethod: id = _testcapi.instancemethod(id) testfunction = _testcapi.instancemethod(testfunction)
import contextlib import os import pickle from textwrap import dedent, indent import threading import time import unittest from test import support from test.support import script_helper interpreters = support.import_module('_xxsubinterpreters') def _captured_script(script): r, w = os.pipe() indented = script.replace('\n', '\n ') wrapped = dedent(f""" import contextlib with open({w}, 'w') as chan: with contextlib.redirect_stdout(chan): {indented} """) return wrapped, open(r) def _run_output(interp, request, shared=None): script, chan = _captured_script(request) with chan: interpreters.run_string(interp, script, shared) return chan.read()
import unittest from test.support import import_module # For 3.6, skip test_idle if threads are not supported. import_module('threading') # Imported by PyShell, imports _thread. # Skip test_idle if _tkinter wasn't built, if tkinter is missing, # if tcl/tk is not the 8.5+ needed for ttk widgets, # or if idlelib is missing (not installed). tk = import_module('tkinter') # imports _tkinter if tk.TkVersion < 8.5: raise unittest.SkipTest("IDLE requires tk 8.5 or later.") idlelib = import_module('idlelib') # Before importing and executing more of idlelib, # tell IDLE to avoid changing the environment. idlelib.testing = True # Unittest.main and test.libregrtest.runtest.runtest_inner # call load_tests, when present here, to discover tests to run. from idlelib.idle_test import load_tests if __name__ == '__main__': tk.NoDefaultRoot() unittest.main(exit=False) tk._support_default_root = 1 tk._default_root = None
""" Test suite for the code in msilib """ import unittest import os from test.support import run_unittest, import_module msilib = import_module('msilib') class Test_make_id(unittest.TestCase): #http://msdn.microsoft.com/en-us/library/aa369212(v=vs.85).aspx """The Identifier data type is a text string. Identifiers may contain the ASCII characters A-Z (a-z), digits, underscores (_), or periods (.). However, every identifier must begin with either a letter or an underscore. """ def test_is_no_change_required(self): self.assertEqual( msilib.make_id("short"), "short") self.assertEqual( msilib.make_id("nochangerequired"), "nochangerequired") self.assertEqual( msilib.make_id("one.dot"), "one.dot") self.assertEqual( msilib.make_id("_"), "_") self.assertEqual( msilib.make_id("a"), "a") #self.assertEqual( # msilib.make_id(""), "") def test_invalid_first_char(self): self.assertEqual( msilib.make_id("9.short"), "_9.short")
def test_PyThreadState_SetAsyncExc(self): ctypes = import_module("ctypes") set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc class AsyncExc(Exception): pass exception = ctypes.py_object(AsyncExc) # First check it works when setting the exception from the same thread. tid = threading.get_ident() try: result = set_async_exc(ctypes.c_long(tid), exception) # The exception is async, so we might have to keep the VM busy until # it notices. while True: pass except AsyncExc: pass else: # This code is unreachable but it reflects the intent. If we wanted # to be smarter the above loop wouldn't be infinite. self.fail("AsyncExc not raised") try: self.assertEqual(result, 1) # one thread state modified except UnboundLocalError: # The exception was raised too quickly for us to get the result. pass # `worker_started` is set by the thread when it's inside a try/except # block waiting to catch the asynchronously set AsyncExc exception. # `worker_saw_exception` is set by the thread upon catching that # exception. worker_started = threading.Event() worker_saw_exception = threading.Event() class Worker(threading.Thread): def run(self): self.id = threading.get_ident() self.finished = False try: while True: worker_started.set() time.sleep(0.1) except AsyncExc: self.finished = True worker_saw_exception.set() t = Worker() t.daemon = True # so if this fails, we don't hang Python at shutdown t.start() if verbose: print(" started worker thread") # Try a thread id that doesn't make sense. if verbose: print(" trying nonsensical thread id") result = set_async_exc(ctypes.c_long(-1), exception) self.assertEqual(result, 0) # no thread states modified # Now raise an exception in the worker thread. if verbose: print(" waiting for worker thread to get started") ret = worker_started.wait() self.assertTrue(ret) if verbose: print(" verifying worker hasn't exited") self.assertTrue(not t.finished) if verbose: print(" attempting to raise asynch exception in worker") result = set_async_exc(ctypes.c_long(t.id), exception) self.assertEqual(result, 1) # one thread state modified if verbose: print(" waiting for worker to say it caught the exception") worker_saw_exception.wait(timeout=10) self.assertTrue(t.finished) if verbose: print(" all OK -- joining worker") if t.finished: t.join()
"""Test program for the fcntl C module. OS/2+EMX doesn't support the file locking operations. """ import os import struct import sys import unittest from test.support import verbose, TESTFN, unlink, run_unittest, import_module # Skip test if no fnctl module. fcntl = import_module('fcntl') # TODO - Write tests for flock() and lockf(). def get_lockdata(): try: os.O_LARGEFILE except AttributeError: start_len = "ll" else: start_len = "qq" if sys.platform in ('netbsd1', 'netbsd2', 'netbsd3', 'Darwin1.2', 'darwin', 'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8', 'bsdos2', 'bsdos3', 'bsdos4', 'openbsd', 'openbsd2', 'openbsd3', 'openbsd4'):
import os import unittest from test import support spwd = support.import_module('spwd') @unittest.skipUnless( hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') class TestSpwdRoot(unittest.TestCase): def test_getspall(self): entries = spwd.getspall() self.assertIsInstance(entries, list) for entry in entries: self.assertIsInstance(entry, spwd.struct_spwd) def test_getspnam(self): entries = spwd.getspall() if not entries: self.skipTest('empty shadow password database') random_name = entries[0].sp_namp entry = spwd.getspnam(random_name) self.assertIsInstance(entry, spwd.struct_spwd) self.assertEqual(entry.sp_namp, random_name) self.assertEqual(entry.sp_namp, entry[0]) self.assertEqual(entry.sp_namp, entry.sp_nam) self.assertIsInstance(entry.sp_pwdp, str) self.assertEqual(entry.sp_pwdp, entry[1]) self.assertEqual(entry.sp_pwdp, entry.sp_pwd) self.assertIsInstance(entry.sp_lstchg, int) self.assertEqual(entry.sp_lstchg, entry[2])
import unittest from test import support import binascii import pickle import random import sys from test.support import bigmemtest, _1G, _4G zlib = support.import_module('zlib') requires_Compress_copy = unittest.skipUnless( hasattr(zlib.compressobj(), "copy"), 'requires Compress.copy()') requires_Decompress_copy = unittest.skipUnless( hasattr(zlib.decompressobj(), "copy"), 'requires Decompress.copy()') class VersionTestCase(unittest.TestCase): def test_library_version(self): # Test that the major version of the actual library in use matches the # major version that we were compiled against. We can't guarantee that # the minor versions will match (even on the machine on which the module # was compiled), and the API is stable between minor versions, so # testing only the major versions avoids spurious failures. self.assertEqual(zlib.ZLIB_RUNTIME_VERSION[0], zlib.ZLIB_VERSION[0]) class ChecksumTestCase(unittest.TestCase): # checksum test cases
# Demo/threads/bug.py. It simply provokes a number of threads into # trying to import the same module "at the same time". # There are no pleasant failure modes -- most likely is that Python # complains several times about module random having no attribute # randrange, and then Python hangs. import _imp as imp import os import importlib import sys import time import shutil import unittest from test.support import ( verbose, import_module, run_unittest, TESTFN, reap_threads, forget, unlink) threading = import_module('threading') def task(N, done, done_tasks, errors): try: # We don't use modulefinder but still import it in order to stress # importing of different modules from several threads. if len(done_tasks) % 2: import modulefinder import random else: import random import modulefinder # This will fail if random is not completely initialized x = random.randrange(1, 3) except Exception as e: errors.append(e.with_traceback(None))
import unittest from doctest import DocTestSuite from test import support import weakref import gc # Modules under test _thread = support.import_module('_thread') threading = support.import_module('threading') import _threading_local class Weak(object): pass def target(local, weaklist): weak = Weak() local.weak = weak weaklist.append(weakref.ref(weak)) class BaseLocalTest: def test_local_refs(self): self._local_refs(20) self._local_refs(50) self._local_refs(100) def _local_refs(self, n): local = self._local() weaklist = []
"Test posix functions" from test import support # Skip these tests if there is no posix module. posix = support.import_module('posix') import errno import sys import time import os import fcntl import platform import pwd import shutil import stat import tempfile import unittest import warnings import _testcapi _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(), support.TESTFN + '-dummy-symlink') class PosixTester(unittest.TestCase): def setUp(self): # create empty file fp = open(support.TESTFN, 'w+') fp.close() self.teardown_files = [ support.TESTFN ]
""" Tests for the threading module. """ import test.support from test.support import verbose, strip_python_stderr, import_module from test.script_helper import assert_python_ok import random import re import sys _thread = import_module("_thread") threading = import_module("threading") import time import unittest import weakref import os from test.script_helper import assert_python_ok, assert_python_failure import subprocess try: import _testcapi except ImportError: _testcapi = None from test import lock_tests # A trivial mutable counter. class Counter(object): def __init__(self):
# xml.etree test for cElementTree from test import support from test.support import precisionbigmemtest, _2G import unittest cET = support.import_module('xml.etree.cElementTree') # cElementTree specific tests def sanity(): r""" Import sanity. >>> from xml.etree import cElementTree Issue #6697. >>> e = cElementTree.Element('a') >>> getattr(e, '\uD800') # doctest: +ELLIPSIS Traceback (most recent call last): ... UnicodeEncodeError: ... >>> p = cElementTree.XMLParser() >>> p.version.split()[0] 'Expat' >>> getattr(p, '\uD800') Traceback (most recent call last): ...
import unittest import sys import os import _testcapi 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 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) class TkinterTest(unittest.TestCase): def testFlattenLen(self): # flatten(<object with no length>) self.assertRaises(TypeError, _tkinter._flatten, True) class TclTest(unittest.TestCase):
# Only called, not tested: getmouse(), ungetmouse() # import sys, tempfile, os # Optionally test curses module. This currently requires that the # 'curses' resource be given on the regrtest command line using the -u # option. If not available, nothing after this line will be executed. import unittest from test.support import requires, import_module requires('curses') # If either of these don't exist, skip the tests. curses = import_module('curses') curses.panel = import_module('curses.panel') # XXX: if newterm was supported we could use it instead of initscr and not exit term = os.environ.get('TERM') if not term or term == 'unknown': raise unittest.SkipTest("$TERM=%r, calling initscr() may cause exit" % term) if sys.platform == "cygwin": raise unittest.SkipTest("cygwin's curses mostly just hangs") def window_funcs(stdscr): "Test the methods of windows" win = curses.newwin(10, 10)
# test asynchat from test import support # If this fails, the test will be skipped. thread = support.import_module('_thread') import asyncore, asynchat, socket, time import unittest import sys import warnings try: import threading except ImportError: threading = None HOST = support.HOST SERVER_QUIT = b'QUIT\n' TIMEOUT = 3.0 if threading: class echo_server(threading.Thread): # parameter to determine the number of bytes passed back to the # client each send chunk_size = 1 def __init__(self, event): threading.Thread.__init__(self) self.event = event self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.port = support.bind_port(self.sock)
from test.support import verbose, import_module, reap_children # Skip these tests if termios is not available import_module('termios') import errno import pty import os import sys import select import signal import socket import io # readline import unittest TEST_STRING_1 = b"I wish to buy a fish license.\n" TEST_STRING_2 = b"For my pet fish, Eric.\n" if verbose: def debug(msg): print(msg) else: def debug(msg): pass # Note that os.read() is nondeterministic so we need to be very careful # to make the test suite deterministic. A normal call to os.read() may # give us less than expected.