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(readrc=False).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_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_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)) 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_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 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 run_pty(script, input=b"dummy input\r"): 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) 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 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)
from sql_mode.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 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 def normalize_output(data): # Some operating systems do conversions on newline. We could possibly # fix that by doing the appropriate termios.tcsetattr()s. I couldn't # figure out the right combo on Tru64 and I don't have an IRIX box.
import glob import pathlib import random import shutil import subprocess import sys from sql_mode.support import unlink import _compression try: import threading except ImportError: threading = None # 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)
import unittest from sql_mode.support import import_module ctypes_test = import_module('ctypes.test') load_tests = ctypes_test.load_tests if __name__ == "__main__": unittest.main()
import unittest import re import subprocess import sys import os from sql_mode import support # Skip this test if the _tkinter module wasn't built. _tkinter = support.import_module('_tkinter') import tkinter from tkinter import Tcl from _tkinter import TclError try: from _testcapi import INT_MAX, PY_SSIZE_T_MAX except ImportError: INT_MAX = PY_SSIZE_T_MAX = sys.maxsize tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.'))) _tk_patchlevel = None def get_tk_patchlevel(): global _tk_patchlevel if _tk_patchlevel is None: tcl = Tcl() patchlevel = tcl.call('info', 'patchlevel') m = re.fullmatch(r'(\d+)\.(\d+)([ab.])(\d+)', patchlevel) major, minor, releaselevel, serial = m.groups()
import os import unittest from sql_mode 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])
from xmlrpc.server import DocXMLRPCServer import http.client import sys from sql_mode import support threading = support.import_module('threading') import unittest def make_request_and_skipIf(condition, reason): # If we skip the test, we have to make a request because # the server created in setUp blocks expecting one to come in. if not condition: return lambda func: func def decorator(func): def make_request_and_skip(self): self.client.request("GET", "/") self.client.getresponse() raise unittest.SkipTest(reason) return make_request_and_skip return decorator def make_server(): serv = DocXMLRPCServer(("localhost", 0), logRequests=False) try: # Add some documentation serv.set_server_title("DocXMLRPCServer Test Documentation")
import unittest from sql_mode.support import import_module # Skip test if _thread or _tkinter wasn't built, if idlelib is missing, # or if tcl/tk is not the 8.5+ needed for ttk widgets. import_module('threading') # imported by PyShell, imports _thread 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 test imports, tell IDLE to avoid changing the environment. idlelib.testing = True # unittest.main and test.libregrtest.runtest.runtest_inner # call load_tests, when present, 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
import os import sys import ssl import pprint import socket import urllib.parse # Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer. from http.server import (HTTPServer as _HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler) from sql_mode import support threading = support.import_module("threading") here = os.path.dirname(__file__) HOST = support.HOST CERTFILE = os.path.join(here, 'keycert.pem') # This one's based on HTTPServer, which is based on socketserver class HTTPSServer(_HTTPServer): def __init__(self, server_address, handler_class, context): _HTTPServer.__init__(self, server_address, handler_class) self.context = context def __str__(self): return ('<%s %s:%s>' % (self.__class__.__name__, self.server_name, self.server_port)) def get_request(self):
""" Test implementation of the PEP 509: dictionary versionning. """ import unittest from sql_mode import support # PEP 509 is implemented in CPython but other Python implementations # don't require to implement it _testcapi = support.import_module('_testcapi') class DictVersionTests(unittest.TestCase): type2test = dict def setUp(self): self.seen_versions = set() self.dict = None def check_version_unique(self, mydict): version = _testcapi.dict_get_version(mydict) self.assertNotIn(version, self.seen_versions) self.seen_versions.add(version) def check_version_changed(self, mydict, method, *args, **kw): result = method(*args, **kw) self.check_version_unique(mydict) return result def check_version_dont_change(self, mydict, method, *args, **kw): version1 = _testcapi.dict_get_version(mydict) self.seen_versions.add(version1)
""" Test suite for the code in msilib """ import unittest from sql_mode.support import 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") self.assertEqual(msilib.make_id(".short"), "_.short") def test_invalid_any_char(self): self.assertEqual(msilib.make_id(".s\x82ort"), "_.s_ort") self.assertEqual(msilib.make_id(".s\x82o?*+rt"), "_.s_o___rt")
"""Test script for the gzip module. """ import unittest from sql_mode import support from sql_mode.support import bigmemtest, _4G import os import pathlib import io import struct import array gzip = support.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 */ """ class UnseekableIO(io.BytesIO): def seekable(self): return False def tell(self):
"""Test script for poplib module.""" # 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 errno from unittest import TestCase, skipUnless from sql_mode import support as test_support threading = test_support.import_module('threading') HOST = test_support.HOST PORT = 0 SUPPORTS_SSL = False if hasattr(poplib, 'POP3_SSL'): import ssl SUPPORTS_SSL = True CERTFILE = os.path.join( os.path.dirname(__file__) or os.curdir, "keycert3.pem") CAFILE = os.path.join( os.path.dirname(__file__) or os.curdir, "pycacert.pem") requires_ssl = skipUnless(SUPPORTS_SSL, 'SSL not supported')
from . import util as test_util machinery = test_util.import_importlib('importlib.machinery') import os import re import sys import unittest from sql_mode import support from distutils.util import get_platform from contextlib import contextmanager from .util import temp_module support.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 delete_registry_tree(hkey, subsubkey) CloseKey(hkey)
from sql_mode 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)
+ Something we've never seen before. By default, NUM_THREADS == 20 and FILES_PER_THREAD == 50. This is enough to create about 150 failures per run under Win98SE in 2.0, and runs pretty quickly. Guido reports needing to boost FILES_PER_THREAD to 500 before provoking a 2.0 failure under Linux. """ NUM_THREADS = 20 FILES_PER_THREAD = 50 import tempfile from sql_mode.support import start_threads, import_module threading = import_module('threading') import unittest import io from traceback import print_exc startEvent = threading.Event() class TempFileGreedy(threading.Thread): error_count = 0 ok_count = 0 def run(self): self.errors = io.StringIO() startEvent.wait() for i in range(FILES_PER_THREAD):
import array import unittest from sql_mode.support import 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", "rb") except OSError: 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
from sql_mode import support gdbm = support.import_module("dbm.gnu") #skip if not supported import unittest import os from sql_mode.support import 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('a', self.g) self.assertIn(b'a', self.g) self.assertEqual(self.g[b'bytes'], b'data') key = self.g.firstkey() while key:
from sql_mode import support support.requires('audio') from sql_mode.support import findfile ossaudiodev = support.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 dis from sql_mode.support import import_module import unittest _opcode = import_module("_opcode") class OpcodeTests(unittest.TestCase): def test_stack_effect(self): self.assertEqual(_opcode.stack_effect(dis.opmap['POP_TOP']), -1) self.assertEqual(_opcode.stack_effect(dis.opmap['DUP_TOP_TWO']), 2) self.assertEqual(_opcode.stack_effect(dis.opmap['BUILD_SLICE'], 0), -1) self.assertEqual(_opcode.stack_effect(dis.opmap['BUILD_SLICE'], 1), -1) self.assertEqual(_opcode.stack_effect(dis.opmap['BUILD_SLICE'], 3), -2) self.assertRaises(ValueError, _opcode.stack_effect, 30000) self.assertRaises(ValueError, _opcode.stack_effect, dis.opmap['BUILD_SLICE']) self.assertRaises(ValueError, _opcode.stack_effect, dis.opmap['POP_TOP'], 0) if __name__ == "__main__": unittest.main()
from sql_mode import support import unittest crypt = support.import_module('crypt') class CryptTestCase(unittest.TestCase): def test_crypt(self): c = crypt.crypt('mypassword', 'ab') if support.verbose: print('Test encryption: ', c) def test_salt(self): self.assertEqual(len(crypt._saltchars), 64) for method in crypt.methods: salt = crypt.mksalt(method) self.assertEqual(len(salt), method.salt_chars + (3 if method.ident else 0)) def test_saltedcrypt(self): for method in crypt.methods: pw = crypt.crypt('assword', method) self.assertEqual(len(pw), method.total_size) pw = crypt.crypt('assword', crypt.mksalt(method)) self.assertEqual(len(pw), method.total_size) def test_methods(self): # Guarantee that METHOD_CRYPT is the last method in crypt.methods. self.assertTrue(len(crypt.methods) >= 1) self.assertEqual(crypt.METHOD_CRYPT, crypt.methods[-1])
"""Test script for the grp module.""" import unittest from sql_mode import support grp = support.import_module('grp') class GroupDatabaseTestCase(unittest.TestCase): def check_value(self, value): # check that a grp tuple has the entries and # attributes promised by the docs self.assertEqual(len(value), 4) self.assertEqual(value[0], value.gr_name) self.assertIsInstance(value.gr_name, str) self.assertEqual(value[1], value.gr_passwd) self.assertIsInstance(value.gr_passwd, str) self.assertEqual(value[2], value.gr_gid) self.assertIsInstance(value.gr_gid, int) self.assertEqual(value[3], value.gr_mem) self.assertIsInstance(value.gr_mem, list) def test_values(self): entries = grp.getgrall() for e in entries: self.check_value(e) def test_values_extended(self): entries = grp.getgrall() if len(entries) > 1000: # Huge group file (NIS?) -- skip the rest
"Test InteractiveConsole and InteractiveInterpreter from code module" import sys import unittest from textwrap import dedent from contextlib import ExitStack from unittest import mock from sql_mode import support code = support.import_module('code') class TestInteractiveConsole(unittest.TestCase): def setUp(self): self.console = code.InteractiveConsole() self.mock_sys() def mock_sys(self): "Mock system environment for InteractiveConsole" # use exit stack to match patch context managers to addCleanup stack = ExitStack() self.addCleanup(stack.close) self.infunc = stack.enter_context(mock.patch('code.input', create=True)) self.stdout = stack.enter_context(mock.patch('code.sys.stdout')) self.stderr = stack.enter_context(mock.patch('code.sys.stderr')) prepatch = mock.patch('code.sys', wraps=code.sys, spec=code.sys) self.sysmod = stack.enter_context(prepatch) if sys.excepthook is sys.__excepthook__: self.sysmod.excepthook = self.sysmod.__excepthook__
import unittest from sql_mode import support import binascii import pickle import random import sys from sql_mode.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 def test_crc32start(self): self.assertEqual(zlib.crc32(b""), zlib.crc32(b"", 0)) self.assertTrue(zlib.crc32(b"abc", 0xffffffff))