def test_pickle(self): import_helper.import_module("pickle") self.do_test("test_pickle")
import unittest from test.support.import_helper import import_module from test.support import check_sanitizer if check_sanitizer(address=True, memory=True): raise unittest.SkipTest( "Tests involvin libX11 can SEGFAULT on ASAN/MSAN builds") # 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 = True tk._default_root = None
import weakref import importlib.machinery import importlib.util from test import support from test.support import MISSING_C_DOCSTRINGS from test.support import import_helper from test.support import threading_helper from test.support import warnings_helper 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 = import_helper.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)
# Generated by Tools/scripts/stable_abi.py """Test that all symbols of the Stable ABI are accessible using ctypes """ import unittest from test.support.import_helper import import_module ctypes_test = import_module('ctypes') class TestStableABIAvailability(unittest.TestCase): def test_available_symbols(self): for symbol_name in SYMBOL_NAMES: with self.subTest(symbol_name): ctypes_test.pythonapi[symbol_name] SYMBOL_NAMES = ( "PyAIter_Check", "PyArg_Parse", "PyArg_ParseTuple", "PyArg_ParseTupleAndKeywords", "PyArg_UnpackTuple", "PyArg_VaParse", "PyArg_VaParseTupleAndKeywords", "PyArg_ValidateKeywordArguments", "PyBaseObject_Type", "PyBool_FromLong", "PyBool_Type", "PyByteArrayIter_Type", "PyByteArray_AsString",
import unittest from test import support from test.support import import_helper from test.support import check_sanitizer if check_sanitizer(address=True, memory=True): raise unittest.SkipTest( "Tests involvin libX11 can SEGFAULT on ASAN/MSAN builds") # Skip test if _tkinter wasn't built. import_helper.import_module('_tkinter') # Skip test if tk cannot be initialized. support.requires('gui') def load_tests(loader, tests, pattern): return loader.discover('tkinter.test.test_tkinter') if __name__ == '__main__': unittest.main()
import array import unittest from test.support import get_attribute from test.support.import_helper import import_module 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", "rb") except OSError: raise unittest.SkipTest("Unable to open /dev/tty") else: with tty: # Skip if another process is in foreground r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") 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):
import array import functools import io import os import pathlib import struct import sys import unittest from subprocess import PIPE, Popen from test import support from test.support import import_helper from test.support import os_helper from test.support import _4G, bigmemtest from test.support.script_helper import assert_python_ok, assert_python_failure gzip = import_helper.import_module('gzip') data1 = b""" int length=DEFAULTALLOC, err = Z_OK; PyObject *RetVal; int flushmode = Z_FINISH; unsigned long start_total_out; """ data2 = b"""/* zlibmodule.c -- gzip-compatible data compression */ /* See http://www.gzip.org/zlib/ /* See http://www.winimage.com/zLibDll for Windows */ """ TEMPDIR = os.path.abspath(os_helper.TESTFN) + '-gzdir'
import inspect import types import unittest import contextlib from test.support.import_helper import import_module from test.support import gc_collect, requires_working_socket asyncio = import_module("asyncio") requires_working_socket(module=True) _no_default = object() 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:
from test.support import import_helper syslog = import_helper.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) def test_log_upto(self):
import sys import unittest from test.support import import_helper pwd = import_helper.import_module('pwd') @unittest.skipUnless(hasattr(pwd, 'getpwall'), 'Does not have getpwall()') 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.assertIn(type(e.pw_gecos), (str, type(None))) 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
# tests __main__ module handling in multiprocessing from test import support from test.support import import_helper # Skip tests if _multiprocessing wasn't built. import_helper.import_module('_multiprocessing') import importlib import importlib.machinery import unittest import sys import os import os.path import py_compile from test.support import os_helper 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 multiprocessing AVAILABLE_START_METHODS = set(multiprocessing.get_all_start_methods()) # Issue #22332: Skip tests if sem_open implementation is broken. support.skip_if_broken_multiprocessing_synchronize() verbose = support.verbose test_source = """\
def test_load_dll_with_flags(self): _sqlite3 = import_helper.import_module("_sqlite3") src = _sqlite3.__file__ if src.lower().endswith("_d.pyd"): ext = "_d.dll" else: ext = ".dll" with test.support.temp_dir() as tmp: # We copy two files and load _sqlite3.dll (formerly .pyd), # which has a dependency on sqlite3.dll. Then we test # loading it in subprocesses to avoid it starting in memory # for each test. target = os.path.join(tmp, "_sqlite3.dll") shutil.copy(src, target) shutil.copy(os.path.join(os.path.dirname(src), "sqlite3" + ext), os.path.join(tmp, "sqlite3" + ext)) def should_pass(command): with self.subTest(command): subprocess.check_output([ sys.executable, "-c", "from ctypes import *; import nt;" + command ], cwd=tmp) def should_fail(command): with self.subTest(command): with self.assertRaises(subprocess.CalledProcessError): subprocess.check_output( [ sys.executable, "-c", "from ctypes import *; import nt;" + command ], cwd=tmp, stderr=subprocess.STDOUT, ) # Default load should not find this in CWD should_fail("WinDLL('_sqlite3.dll')") # Relative path (but not just filename) should succeed should_pass("WinDLL('./_sqlite3.dll')") # Insecure load flags should succeed # Clear the DLL directory to avoid safe search settings propagating should_pass( "windll.kernel32.SetDllDirectoryW(None); WinDLL('_sqlite3.dll', winmode=0)" ) # Full path load without DLL_LOAD_DIR shouldn't find dependency should_fail("WinDLL(nt._getfullpathname('_sqlite3.dll'), " + "winmode=nt._LOAD_LIBRARY_SEARCH_SYSTEM32)") # Full path load with DLL_LOAD_DIR should succeed should_pass("WinDLL(nt._getfullpathname('_sqlite3.dll'), " + "winmode=nt._LOAD_LIBRARY_SEARCH_SYSTEM32|" + "nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)") # User-specified directory should succeed should_pass("import os; p = os.add_dll_directory(os.getcwd());" + "WinDLL('_sqlite3.dll'); p.close()")
import unittest from test.support.import_helper import import_module ctypes_test = import_module('ctypes.test') load_tests = ctypes_test.load_tests if __name__ == "__main__": unittest.main()
"""Test program for the fcntl C module. """ import platform import os import struct import sys import unittest from multiprocessing import Process from test.support import (verbose, run_unittest, cpython_only) from test.support.import_helper import import_module from test.support.os_helper import TESTFN, unlink # Skip test if no fcntl module. fcntl = import_module('fcntl') def get_lockdata(): try: os.O_LARGEFILE except AttributeError: start_len = "ll" else: start_len = "qq" if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd')) or sys.platform == 'darwin'): if struct.calcsize('l') == 8: off_t = 'l' pid_t = 'i' else: off_t = 'lxxxx'
import contextlib import sys import unittest from test import support from test.support import import_helper from test.support import os_helper import time resource = import_helper.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) @unittest.skipIf(sys.platform == "vxworks", "setting RLIMIT_FSIZE is not supported on VxWorks") 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
import os from test.support import load_package_tests from test.support import import_helper # Skip tests if we don't have concurrent.futures. import_helper.import_module('concurrent.futures') def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args)
from test.support import import_helper, load_package_tests, verbose # Skip test if _sqlite3 module not installed. import_helper.import_module('_sqlite3') import os import sqlite3 # Implement the unittest "load tests" protocol. def load_tests(*args): pkg_dir = os.path.dirname(__file__) return load_package_tests(pkg_dir, *args) if verbose: print(f"test_sqlite3: testing with SQLite version {sqlite3.sqlite_version}")
from test import support from test.support import import_helper, cpython_only gdbm = import_helper.import_module("dbm.gnu") #skip if not supported import unittest import os from test.support.os_helper import TESTFN, TESTFN_NONASCII, unlink filename = TESTFN class TestGdbm(unittest.TestCase): @staticmethod def setUpClass(): if support.verbose: try: from _gdbm import _GDBM_VERSION as version except ImportError: pass else: print(f"gdbm version: {version}") def setUp(self): self.g = None def tearDown(self): if self.g is not None: self.g.close() unlink(filename) @cpython_only def test_disallow_instantiation(self):
import unittest from test import support from test.support import import_helper import binascii import copy import pickle import random import sys from test.support import bigmemtest, _1G, _4G zlib = import_helper.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 def test_crc32start(self):
def test_import_module(self): import_helper.import_module("ftplib") self.assertRaises(unittest.SkipTest, import_helper.import_module, "foo")
from test import support from test.support import import_helper import_helper.import_module("dbm.ndbm") #skip if not supported import os import unittest import dbm.ndbm from dbm.ndbm import error class DbmTestCase(unittest.TestCase): def setUp(self): self.filename = support.TESTFN self.d = dbm.ndbm.open(self.filename, 'c') self.d.close() def tearDown(self): for suffix in ['', '.pag', '.dir', '.db']: support.unlink(self.filename + suffix) def test_keys(self): self.d = dbm.ndbm.open(self.filename, 'c') self.assertEqual(self.d.keys(), []) self.d['a'] = 'b' self.d[b'bytes'] = b'data' self.d['12345678910'] = '019237410982340912840198242' self.d.keys() self.assertIn('a', self.d) self.assertIn(b'a', self.d) self.assertEqual(self.d[b'bytes'], b'data') # get() and setdefault() work as in the dict interface self.assertEqual(self.d.get(b'a'), b'b')
import faulthandler from test.support import import_helper import unittest _xxtestfuzz = import_helper.import_module('_xxtestfuzz') class TestFuzzer(unittest.TestCase): """To keep our https://github.com/google/oss-fuzz API working.""" def test_sample_input_smoke_test(self): """This is only a regression test: Check that it doesn't crash.""" _xxtestfuzz.run(b"") _xxtestfuzz.run(b"\0") _xxtestfuzz.run(b"{") _xxtestfuzz.run(b" ") _xxtestfuzz.run(b"x") _xxtestfuzz.run(b"1") _xxtestfuzz.run(b"AAAAAAA") _xxtestfuzz.run(b"AAAAAA\0") if __name__ == "__main__": faulthandler.enable() unittest.main()
from test import support from test.support import import_helper support.requires('audio') from test.support import findfile ossaudiodev = import_helper.import_module('ossaudiodev') import errno import sys import sunau import time import audioop import unittest # Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a # fairly recent addition to OSS. try: from ossaudiodev import AFMT_S16_NE except ImportError: if sys.byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE def read_sound_file(path): with open(path, 'rb') as fp: au = sunau.open(fp) rate = au.getframerate() nchannels = au.getnchannels()
import pickle import unittest from test import support from test.support import import_helper from test.support import os_helper turtle = import_helper.import_module('turtle') Vec2D = turtle.Vec2D test_config = """\ width = 0.75 height = 0.8 canvwidth = 500 canvheight = 200 leftright = 100 topbottom = 100 mode = world colormode = 255 delay = 100 undobuffersize = 10000 shape = circle pencolor = red fillcolor = blue resizemode = auto visible = None language = english exampleturtle = turtle examplescreen = screen title = Python Turtle Graphics using_IDLE = ''
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()
from test.support import verbose, reap_children from test.support.import_helper import import_module # 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 import struct import tty import fcntl import platform import warnings TEST_STRING_1 = b"I wish to buy a fish license.\n" TEST_STRING_2 = b"For my pet fish, Eric.\n" try: _TIOCGWINSZ = tty.TIOCGWINSZ _TIOCSWINSZ = tty.TIOCSWINSZ _HAVE_WINSZ = True except AttributeError: _HAVE_WINSZ = False
from test.support import (requires, _2G, _4G, gc_collect, cpython_only) from test.support.import_helper import import_module from test.support.os_helper import TESTFN, unlink import unittest import os import re import itertools import socket import sys import weakref # Skip test if we can't import mmap. mmap = import_module('mmap') PAGESIZE = mmap.PAGESIZE class MmapTests(unittest.TestCase): def setUp(self): if os.path.exists(TESTFN): os.unlink(TESTFN) def tearDown(self): try: os.unlink(TESTFN) except OSError: pass def test_basic(self): # Test mmap module on Unix systems and Windows
import string import sys import tempfile import unittest from test.support import requires, verbose, SaveSignals from test.support.import_helper import import_module # 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 inspect requires('curses') # If either of these don't exist, skip the tests. curses = import_module('curses') import_module('curses.ascii') import_module('curses.textpad') try: import curses.panel except ImportError: pass def requires_curses_func(name): return unittest.skipUnless(hasattr(curses, name), 'requires curses.%s' % name) term = os.environ.get('TERM')
from . import util as test_util machinery = test_util.import_importlib('importlib.machinery') import os import re import sys import unittest from test import support from test.support import import_helper from distutils.util import get_platform from contextlib import contextmanager from .util import temp_module import_helper.import_module('winreg', required_on=['win']) from winreg import (CreateKey, HKEY_CURRENT_USER, SetValue, REG_SZ, KEY_ALL_ACCESS, EnumKey, CloseKey, DeleteKey, OpenKey) def delete_registry_tree(root, subkey): try: hkey = OpenKey(root, subkey, access=KEY_ALL_ACCESS) except OSError: # subkey does not exist return while True: try: subsubkey = EnumKey(hkey, 0) except OSError: # no more subkeys break
def test_marshal(self): import_helper.import_module("marshal") self.do_test("test_marshal")