def test_setuptools_compat(self): import distutils.core, distutils.extension, distutils.command.build_ext saved_ext = distutils.extension.Extension try: # on some platforms, it loads the deprecated "dl" module test_support.import_module('setuptools_build_ext', deprecated=True) # theses import patch Distutils' Extension class from setuptools_build_ext import build_ext as setuptools_build_ext from setuptools_extension import Extension etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') etree_ext = Extension('lxml.etree', [etree_c]) dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) cmd = setuptools_build_ext(dist) cmd.ensure_finalized() cmd.inplace = 1 cmd.distribution.package_dir = {'': 'src'} cmd.distribution.packages = ['lxml', 'lxml.html'] curdir = os.getcwd() ext = sysconfig.get_config_var("SO") wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) path = cmd.get_ext_fullpath('lxml.etree') self.assertEqual(wanted, path) finally: # restoring Distutils' Extension class otherwise its broken distutils.extension.Extension = saved_ext distutils.core.Extension = saved_ext distutils.command.build_ext.Extension = saved_ext
def test_setuptools_compat(self): import distutils.core, distutils.extension, distutils.command.build_ext saved_ext = distutils.extension.Extension try: test_support.import_module('setuptools_build_ext', deprecated=True) from setuptools_build_ext import build_ext as setuptools_build_ext from setuptools_extension import Extension etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') etree_ext = Extension('lxml.etree', [etree_c]) dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) cmd = setuptools_build_ext(dist) cmd.ensure_finalized() cmd.inplace = 1 cmd.distribution.package_dir = {'': 'src'} cmd.distribution.packages = ['lxml', 'lxml.html'] curdir = os.getcwd() ext = sysconfig.get_config_var('SO') wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) path = cmd.get_ext_fullpath('lxml.etree') self.assertEqual(wanted, path) finally: distutils.extension.Extension = saved_ext distutils.core.Extension = saved_ext distutils.command.build_ext.Extension = saved_ext
def test_pickling(self): import pickle self.pickle_test(pickle) import cPickle self.pickle_test(cPickle) # old pickles expect the _compile() reconstructor in sre module import_module("sre", deprecated=True) from sre import _compile
def test_easy(self): self.checkModule("pyclbr") self.checkModule("doctest") # Silence Py3k warning rfc822 = import_module("rfc822", deprecated=True) self.checkModule("rfc822", rfc822) self.checkModule("difflib")
def testPass(cryptPass): crypt = test_support.import_module('crypt') salt = cryptPass[0:2] try: dictFile = open('dictionary.txt','r') except Exception, e: print 'Error opening dictionary:\n\t',e
def test_easy(self): self.checkModule('pyclbr') self.checkModule('doctest', ignore=("DocTestCase",)) # Silence Py3k warning rfc822 = import_module('rfc822', deprecated=True) self.checkModule('rfc822', rfc822) self.checkModule('difflib')
def test_coverage(coverdir): trace = test_support.import_module("trace") tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=0, count=1) tracer.run("reload(cmd);test_main()") r = tracer.results() print "Writing coverage results..." r.write_results(show_missing=True, summary=True, coverdir=coverdir)
def dash_R_cleanup(fs, ps, pic, zdc, abcs): import gc, copy_reg import _strptime, linecache dircache = test_support.import_module('dircache', deprecated=True) import urlparse, urllib, urllib2, mimetypes, doctest import struct, filecmp from distutils.dir_util import _path_created # Clear the warnings registry, so they can be displayed again for mod in sys.modules.values(): if hasattr(mod, '__warningregistry__'): del mod.__warningregistry__ # Restore some original values. warnings.filters[:] = fs copy_reg.dispatch_table.clear() copy_reg.dispatch_table.update(ps) sys.path_importer_cache.clear() sys.path_importer_cache.update(pic) try: import zipimport except ImportError: pass # Run unmodified on platforms without zipimport support else: zipimport._zip_directory_cache.clear() zipimport._zip_directory_cache.update(zdc) # clear type cache sys._clear_type_cache() # Clear ABC registries, restoring previously saved ABC registries. for abc, registry in abcs.items(): abc._abc_registry = registry.copy() abc._abc_cache.clear() abc._abc_negative_cache.clear() # Clear assorted module caches. _path_created.clear() re.purge() _strptime._regex_cache.clear() urlparse.clear_cache() urllib.urlcleanup() urllib2.install_opener(None) dircache.reset() linecache.clearcache() mimetypes._default_mime_types() filecmp._cache.clear() struct._clearcache() doctest.master = None # Collect cyclic trash. gc.collect()
def test_setuptools_compat(self): try: # on some platforms, it loads the deprecated "dl" module test_support.import_module('setuptools_build_ext', deprecated=True) except test_support.TestSkipped: return from setuptools_build_ext import build_ext as setuptools_build_ext from setuptools_extension import Extension etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') etree_ext = Extension('lxml.etree', [etree_c]) dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) cmd = setuptools_build_ext(dist) cmd.ensure_finalized() cmd.inplace = 1 cmd.distribution.package_dir = {'': 'src'} cmd.distribution.packages = ['lxml', 'lxml.html'] curdir = os.getcwd() ext = sysconfig.get_config_var("SO") wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) path = cmd.get_ext_fullpath('lxml.etree') self.assertEquals(wanted, path)
def dash_R_cleanup(fs, ps, pic, abcs): import gc, copy_reg import _strptime, linecache dircache = test_support.import_module('dircache', deprecated=True) import urlparse, urllib, urllib2, mimetypes, doctest import struct, filecmp from distutils.dir_util import _path_created # Clear the warnings registry, so they can be displayed again for mod in sys.modules.values(): if hasattr(mod, '__warningregistry__'): del mod.__warningregistry__ # Restore some original values. warnings.filters[:] = fs copy_reg.dispatch_table.clear() copy_reg.dispatch_table.update(ps) sys.path_importer_cache.clear() sys.path_importer_cache.update(pic) # clear type cache sys._clear_type_cache() # Clear ABC registries, restoring previously saved ABC registries. for abc, registry in abcs.items(): abc._abc_registry = registry.copy() abc._abc_cache.clear() abc._abc_negative_cache.clear() # Clear assorted module caches. _path_created.clear() re.purge() _strptime._regex_cache.clear() urlparse.clear_cache() urllib.urlcleanup() urllib2.install_opener(None) dircache.reset() linecache.clearcache() mimetypes._default_mime_types() filecmp._cache.clear() struct._clearcache() doctest.master = None if _llvm: code_types = (types.CodeType, types.FunctionType, types.MethodType) for obj in gc.get_objects(): if isinstance(obj, code_types): _llvm.clear_feedback(obj) # Collect cyclic trash. gc.collect()
# expected: fail import unittest from test.test_support import run_unittest, import_module #Skip tests if _ctypes module does not exist import_module('_ctypes') def test_main(): import ctypes.test 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()
import sys import unittest from test import test_support pwd = test_support.import_module('pwd') class PwdTest(unittest.TestCase): def test_values(self): entries = pwd.getpwall() entriesbyname = {} entriesbyuid = {} for e in entries: self.assertEqual(len(e), 7) self.assertEqual(e[0], e.pw_name) self.assertIsInstance(e.pw_name, basestring) self.assertEqual(e[1], e.pw_passwd) self.assertIsInstance(e.pw_passwd, basestring) 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, basestring) self.assertEqual(e[5], e.pw_dir) self.assertIsInstance(e.pw_dir, basestring) self.assertEqual(e[6], e.pw_shell) self.assertIsInstance(e.pw_shell, basestring) # The following won't work, because of duplicate entries
import unittest, sys from test import test_support import binascii import random from test.test_support import precisionbigmemtest, _1G zlib = test_support.import_module('zlib') class ChecksumTestCase(unittest.TestCase): # checksum test cases def test_crc32start(self): self.assertEqual(zlib.crc32(""), zlib.crc32("", 0)) self.assertTrue(zlib.crc32("abc", 0xffffffff)) def test_crc32empty(self): self.assertEqual(zlib.crc32("", 0), 0) self.assertEqual(zlib.crc32("", 1), 1) self.assertEqual(zlib.crc32("", 432), 432) def test_adler32start(self): self.assertEqual(zlib.adler32(""), zlib.adler32("", 1)) self.assertTrue(zlib.adler32("abc", 0xffffffff)) def test_adler32empty(self): self.assertEqual(zlib.adler32("", 0), 0) self.assertEqual(zlib.adler32("", 1), 1) self.assertEqual(zlib.adler32("", 432), 432) def assertEqual32(self, seen, expected):
from test import test_support from test.test_support import TESTFN, _4G, bigmemtest, import_module, findfile import unittest from cStringIO import StringIO import os import subprocess import sys try: import threading except ImportError: threading = None bz2 = import_module('bz2') from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor has_cmdline_bunzip2 = sys.platform not in ("win32", "os2emx", "riscos") class BaseTest(unittest.TestCase): "Base for other testcases." TEXT = 'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:\ndaemon:x:2:2:daemon:/sbin:\nadm:x:3:4:adm:/var/adm:\nlp:x:4:7:lp:/var/spool/lpd:\nsync:x:5:0:sync:/sbin:/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/var/spool/mail:\nnews:x:9:13:news:/var/spool/news:\nuucp:x:10:14:uucp:/var/spool/uucp:\noperator:x:11:0:operator:/root:\ngames:x:12:100:games:/usr/games:\ngopher:x:13:30:gopher:/usr/lib/gopher-data:\nftp:x:14:50:FTP User:/var/ftp:/bin/bash\nnobody:x:65534:65534:Nobody:/home:\npostfix:x:100:101:postfix:/var/spool/postfix:\nniemeyer:x:500:500::/home/niemeyer:/bin/bash\npostgres:x:101:102:PostgreSQL Server:/var/lib/pgsql:/bin/bash\nmysql:x:102:103:MySQL server:/var/lib/mysql:/bin/bash\nwww:x:103:104::/var/www:/bin/false\n' DATA = 'BZh91AY&SY.\xc8N\x18\x00\x01>_\x80\x00\x10@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe00\x01\x99\xaa\x00\xc0\x03F\x86\x8c#&\x83F\x9a\x03\x06\xa6\xd0\xa6\x93M\x0fQ\xa7\xa8\x06\x804hh\x12$\x11\xa4i4\xf14S\xd2<Q\xb5\x0fH\xd3\xd4\xdd\xd5\x87\xbb\xf8\x94\r\x8f\xafI\x12\xe1\xc9\xf8/E\x00pu\x89\x12]\xc9\xbbDL\nQ\x0e\t1\x12\xdf\xa0\xc0\x97\xac2O9\x89\x13\x94\x0e\x1c7\x0ed\x95I\x0c\xaaJ\xa4\x18L\x10\x05#\x9c\xaf\xba\xbc/\x97\x8a#C\xc8\xe1\x8cW\xf9\xe2\xd0\xd6M\xa7\x8bXa<e\x84t\xcbL\xb3\xa7\xd9\xcd\xd1\xcb\x84.\xaf\xb3\xab\xab\xad`n}\xa0lh\tE,\x8eZ\x15\x17VH>\x88\xe5\xcd9gd6\x0b\n\xe9\x9b\xd5\x8a\x99\xf7\x08.K\x8ev\xfb\xf7xw\xbb\xdf\xa1\x92\xf1\xdd|/";\xa2\xba\x9f\xd5\xb1#A\xb6\xf6\xb3o\xc9\xc5y\\\xebO\xe7\x85\x9a\xbc\xb6f8\x952\xd5\xd7"%\x89>V,\xf7\xa6z\xe2\x9f\xa3\xdf\x11\x11"\xd6E)I\xa9\x13^\xca\xf3r\xd0\x03U\x922\xf26\xec\xb6\xed\x8b\xc3U\x13\x9d\xc5\x170\xa4\xfa^\x92\xacDF\x8a\x97\xd6\x19\xfe\xdd\xb8\xbd\x1a\x9a\x19\xa3\x80ankR\x8b\xe5\xd83]\xa9\xc6\x08\x82f\xf6\xb9"6l$\xb8j@\xc0\x8a\xb0l1..\xbak\x83ls\x15\xbc\xf4\xc1\x13\xbe\xf8E\xb8\x9d\r\xa8\x9dk\x84\xd3n\xfa\xacQ\x07\xb1%y\xaav\xb4\x08\xe0z\x1b\x16\xf5\x04\xe9\xcc\xb9\x08z\x1en7.G\xfc]\xc9\x14\xe1B@\xbb!8`' DATA_CRLF = 'BZh91AY&SY\xaez\xbbN\x00\x01H\xdf\x80\x00\x12@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe0@\x01\xbc\xc6`\x86*\x8d=M\xa9\x9a\x86\xd0L@\x0fI\xa6!\xa1\x13\xc8\x88jdi\x8d@\x03@\x1a\x1a\x0c\x0c\x83 \x00\xc4h2\x19\x01\x82D\x84e\t\xe8\x99\x89\x19\x1ah\x00\r\x1a\x11\xaf\x9b\x0fG\xf5(\x1b\x1f?\t\x12\xcf\xb5\xfc\x95E\x00ps\x89\x12^\xa4\xdd\xa2&\x05(\x87\x04\x98\x89u\xe40%\xb6\x19\'\x8c\xc4\x89\xca\x07\x0e\x1b!\x91UIFU%C\x994!DI\xd2\xfa\xf0\xf1N8W\xde\x13A\xf5\x9cr%?\x9f3;I45A\xd1\x8bT\xb1<l\xba\xcb_\xc00xY\x17r\x17\x88\x08\x08@\xa0\ry@\x10\x04$)`\xf2\xce\x89z\xb0s\xec\x9b.iW\x9d\x81\xb5-+t\x9f\x1a\'\x97dB\xf5x\xb5\xbe.[.\xd7\x0e\x81\xe7\x08\x1cN`\x88\x10\xca\x87\xc3!"\x80\x92R\xa1/\xd1\xc0\xe6mf\xac\xbd\x99\xcca\xb3\x8780>\xa4\xc7\x8d\x1a\\"\xad\xa1\xabyBg\x15\xb9l\x88\x88\x91k"\x94\xa4\xd4\x89\xae*\xa6\x0b\x10\x0c\xd6\xd4m\xe86\xec\xb5j\x8a\x86j\';\xca.\x01I\xf2\xaaJ\xe8\x88\x8cU+t3\xfb\x0c\n\xa33\x13r2\r\x16\xe0\xb3(\xbf\x1d\x83r\xe7M\xf0D\x1365\xd8\x88\xd3\xa4\x92\xcb2\x06\x04\\\xc1\xb0\xea//\xbek&\xd8\xe6+t\xe5\xa1\x13\xada\x16\xder5"w]\xa2i\xb7[\x97R \xe2IT\xcd;Z\x04dk4\xad\x8a\t\xd3\x81z\x10\xf1:^`\xab\x1f\xc5\xdc\x91N\x14$+\x9e\xae\xd3\x80' EMPTY_DATA = 'BZh9\x17rE8P\x90\x00\x00\x00\x00' if has_cmdline_bunzip2: def decompress(self, data): pop = subprocess.Popen("bunzip2", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
#!/usr/bin/env python import unittest from test import test_support import socket import urllib import sys import os import time mimetools = test_support.import_module("mimetools", deprecated=True) def _open_with_retry(func, host, *args, **kwargs): # Connecting to remote hosts is flaky. Make it more robust # by retrying the connection several times. for i in range(3): try: return func(host, *args, **kwargs) except IOError, last_exc: continue except: raise raise last_exc class URLTimeoutTest(unittest.TestCase): TIMEOUT = 10.0
from test.test_support import run_unittest, import_module # Skip test if _sqlite3 module was not built. import_module('_sqlite3') from sqlite3.test import (dbapi, types, userfunctions, py25tests, factory, transactions, hooks, regression, dump) def test_main(): run_unittest(dbapi.suite(), types.suite(), userfunctions.suite(), py25tests.suite(), factory.suite(), transactions.suite(), hooks.suite(), regression.suite(), dump.suite()) if __name__ == "__main__": test_main()
import unittest from doctest import DocTestSuite from test import test_support threading = test_support.import_module('threading') import weakref import gc class Weak(object): pass def target(local, weaklist): weak = Weak() local.weak = weak weaklist.append(weakref.ref(weak)) class ThreadingLocalTest(unittest.TestCase): def test_local_refs(self): self._local_refs(20) self._local_refs(50) self._local_refs(100) def _local_refs(self, n): local = threading.local() weaklist = [] for i in range(n): t = threading.Thread(target=target, args=(local, weaklist)) t.start() t.join() del t
from random import choice, randrange import re import string import sys from test import test_support import unittest from collections import namedtuple, Counter, OrderedDict from collections import Hashable, Iterable, Iterator from collections import Sized, Container, Callable from collections import Set, MutableSet from collections import Mapping, MutableMapping from collections import Sequence, MutableSequence # Silence deprecation warning sets = test_support.import_module('sets', deprecated=True) TestNT = namedtuple('TestNT', 'x y z') # type used for pickle tests py273_named_tuple_pickle = '''\ ccopy_reg _reconstructor p0 (ctest.test_collections TestNT p1 c__builtin__ tuple p2 (I10 I20
"""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.test_support import (verbose, TESTFN, unlink, run_unittest, import_module, cpython_only) # Skip test if no fcntl module. fcntl = import_module('fcntl') # TODO - Write tests for flock() and lockf(). def get_lockdata(): if sys.platform.startswith('atheos'): start_len = "qq" else: try: os.O_LARGEFILE except AttributeError: start_len = "ll" else: start_len = "qq" if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd', 'bsdos')) or sys.platform == 'darwin'):
# expected: fail # Copyright (C) 2003 Python Software Foundation import unittest import os import sys from test import test_support MacOS = test_support.import_module('MacOS') #The following modules should exist if MacOS exists. import Carbon.File import macostools TESTFN2 = test_support.TESTFN + '2' requires_32bit = unittest.skipUnless(sys.maxint < 2**32, '32-bit only test') class TestMacostools(unittest.TestCase): def setUp(self): fp = open(test_support.TESTFN, 'w') fp.write('hello world\n') fp.close() rfp = MacOS.openrf(test_support.TESTFN, '*wb') rfp.write('goodbye world\n') rfp.close() def tearDown(self): test_support.unlink(test_support.TESTFN) test_support.unlink(TESTFN2)
#! /usr/bin/env python """Simple test script for imgfile.c Roger E. Masse """ from test.test_support import verbose, unlink, findfile, import_module imgfile = import_module('imgfile', deprecated=True) import uu def testimage(name): """Run through the imgfile's battery of possible methods on the image passed in name. """ import sys import os outputfile = '/tmp/deleteme' # try opening the name directly try: # This function returns a tuple (x, y, z) where x and y are the size # of the image in pixels and z is the number of bytes per pixel. Only # 3 byte RGB pixels and 1 byte greyscale pixels are supported. sizes = imgfile.getsizes(name) except imgfile.error: # get a more qualified path component of the script... if __name__ == '__main__': ourname = sys.argv[0]
""" Tests for the mhlib module Nick Mathewson """ ### BUG: This suite doesn't currently test the mime functionality of ### mhlib. It should. import unittest from test.test_support import run_unittest, TESTFN, import_module import os, StringIO import sys mhlib = import_module('mhlib', deprecated=True) if (sys.platform.startswith("win") or sys.platform == "riscos" or sys.platform.startswith("atheos")): # mhlib.updateline() renames a file to the name of a file that already # exists. That causes a reasonable OS <wink> to complain in test_sequence # here, like the "OSError: [Errno 17] File exists" raised on Windows. # mhlib's listsubfolders() and listallfolders() do something with # link counts, and that causes test_listfolders() here to get back # an empty list from its call of listallfolders(). # The other tests here pass on Windows. raise unittest.SkipTest("skipped on %s -- " % sys.platform + "too many Unix assumptions") _mhroot = TESTFN + "_MH" _mhpath = os.path.join(_mhroot, "MH") _mhprofile = os.path.join(_mhroot, ".mh_profile")
import unittest from test import test_support rfc822 = test_support.import_module("rfc822", deprecated=True) try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class MessageTestCase(unittest.TestCase): def create_message(self, msg): return rfc822.Message(StringIO(msg)) def test_get(self): msg = self.create_message( 'To: "last, first" <*****@*****.**>\n\ntest\n') self.assertTrue(msg.get("to") == '"last, first" <*****@*****.**>') self.assertTrue(msg.get("TO") == '"last, first" <*****@*****.**>') self.assertTrue(msg.get("No-Such-Header") is None) self.assertTrue(msg.get("No-Such-Header", "No-Such-Value") == "No-Such-Value") def test_setdefault(self): msg = self.create_message( 'To: "last, first" <*****@*****.**>\n\ntest\n') self.assertTrue(not msg.has_key("New-Header")) self.assertTrue(msg.setdefault("New-Header", "New-Value") == "New-Value") self.assertTrue(msg.setdefault("New-Header", "Different-Value") == "New-Value")
import ftplib import asyncore import asynchat import socket import StringIO import errno import os try: import ssl except ImportError: ssl = None from unittest import TestCase, SkipTest, skipUnless from test import test_support from test.test_support import HOST, HOSTv6 threading = test_support.import_module('threading') TIMEOUT = 3 # the dummy data returned by server over the data channel when # RETR, LIST and NLST commands are issued RETR_DATA = 'abcde12345\r\n' * 1000 LIST_DATA = 'foo\r\nbar\r\n' NLST_DATA = 'foo\r\nbar\r\n' class DummyDTPHandler(asynchat.async_chat): dtp_conn_closed = False def __init__(self, conn, baseclass): asynchat.async_chat.__init__(self, conn) self.baseclass = baseclass
# Copyright (C) 2003 Python Software Foundation import unittest from test import test_support # Skip this test if aetools does not exist. test_support.import_module('aetools') class TestScriptpackages(unittest.TestCase): def _test_scriptpackage(self, package, testobject=1): # Check that we can import the package mod = __import__(package) # Test that we can get the main event class klass = getattr(mod, package) # Test that we can instantiate that class talker = klass() if testobject: # Test that we can get an application object obj = mod.application(0) def test__builtinSuites(self): self._test_scriptpackage('_builtinSuites', testobject=0) def test_StdSuites(self): self._test_scriptpackage('StdSuites') def test_SystemEvents(self): self._test_scriptpackage('SystemEvents') def test_Finder(self):
# Ridiculously simple test of the winsound module for Windows. import unittest from test import test_support import time import os import subprocess import ctypes winsound = test_support.import_module('winsound') import _winreg def has_sound(sound): """Find out if a particular event is configured with a default sound""" try: # Ask the mixer API for the number of devices it knows about. # When there are no devices, PlaySound will fail. if ctypes.windll.winmm.mixerGetNumDevs() is 0: return False key = _winreg.OpenKeyEx( _winreg.HKEY_CURRENT_USER, "AppEvents\Schemes\Apps\.Default\{0}\.Default".format(sound)) value = _winreg.EnumValue(key, 0)[1] if value is not u"": return True else: return False except WindowsError: return False
"Test posix functions" from test import test_support # Skip these tests if there is no posix module. posix = test_support.import_module('posix') import errno import sys import time import os import platform import pwd import shutil import stat import sys import tempfile import unittest import warnings _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(), test_support.TESTFN + '-dummy-symlink') warnings.filterwarnings('ignore', '.* potential security risk .*', RuntimeWarning) class PosixTester(unittest.TestCase): def setUp(self): # create empty file fp = open(test_support.TESTFN, 'w+')
# expected: fail import unittest from test import test_support import time resource = test_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: self.skipTest('RLIMIT_FSIZE not available') # 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):
"""Test program for the fcntl C module. OS/2+EMX doesn't support the file locking operations. """ import os import struct import sys import _testcapi import unittest from test.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(): if sys.platform.startswith('atheos'): start_len = "qq" else: try: os.O_LARGEFILE except AttributeError: start_len = "ll" else: start_len = "qq" if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd', 'bsdos'))
import os import unittest import random from test import test_support thread = test_support.import_module('thread') import time import sys import weakref import lock_tests NUMTASKS = 10 NUMTRIPS = 3 _print_mutex = thread.allocate_lock() def verbose_print(arg): """Helper function for printing out debugging output.""" if test_support.verbose: with _print_mutex: print arg class BasicThreadTest(unittest.TestCase): def setUp(self): self.done_mutex = thread.allocate_lock() self.done_mutex.acquire() self.running_mutex = thread.allocate_lock() self.random_mutex = thread.allocate_lock() self.created = 0
import unittest import os from test.test_support import TESTFN, run_unittest, unlink, import_module gdbm = import_module('gdbm') 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' key_set = set(self.g.keys()) self.assertEqual(key_set, frozenset(['a', '12345678910'])) self.assertTrue(self.g.has_key('a')) key = self.g.firstkey() while key: self.assertIn(key, key_set) key_set.remove(key) key = self.g.nextkey(key) self.assertRaises(KeyError, lambda: self.g['xxx'])
import unittest, operator, copy, pickle, random from test import test_support test_support.import_module("sets", deprecated=True) from sets import Set, ImmutableSet empty_set = Set() #============================================================================== class TestBasicOps(unittest.TestCase): def test_repr(self): if self.repr is not None: self.assertEqual(repr(self.set), self.repr) def test_length(self): self.assertEqual(len(self.set), self.length) def test_self_equality(self): self.assertEqual(self.set, self.set) def test_equivalent_equality(self): self.assertEqual(self.set, self.dup) def test_copy(self): self.assertEqual(self.set.copy(), self.dup) def test_self_union(self): result = self.set | self.set self.assertEqual(result, self.dup)
"""Test script for the grp module.""" import unittest from test import test_support grp = test_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, basestring) self.assertEqual(value[1], value.gr_passwd) self.assertIsInstance(value.gr_passwd, basestring) 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) if len(entries) > 1000: # Huge group file (NIS?) -- skip the rest return
from test.test_support import (TESTFN, run_unittest, import_module, unlink, requires, _2G, _4G, gc_collect, cpython_only) import unittest import os, re, itertools, socket, sys 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 # Create a file to be mmap'ed. f = open(TESTFN, 'w+') try: # Write 2 pages worth of data to the file f.write('\0' * PAGESIZE) f.write('foo') f.write('\0' * (PAGESIZE - 3))
#! /usr/bin/env python """Whimpy test script for the cl module Roger E. Masse """ from test.test_support import verbose, import_module cl = import_module('cl') clattrs = ['ADDED_ALGORITHM_ERROR', 'ALAW', 'ALGORITHM_ID', 'ALGORITHM_VERSION', 'AUDIO', 'AWARE_ERROR', 'AWARE_MPEG_AUDIO', 'AWARE_MULTIRATE', 'AWCMP_CONST_QUAL', 'AWCMP_FIXED_RATE', 'AWCMP_INDEPENDENT', 'AWCMP_JOINT_STEREO', 'AWCMP_LOSSLESS', 'AWCMP_MPEG_LAYER_I', 'AWCMP_MPEG_LAYER_II', 'AWCMP_STEREO', 'Algorithm', 'AlgorithmNumber', 'AlgorithmType', 'AudioFormatName', 'BAD_ALGORITHM_NAME', 'BAD_ALGORITHM_TYPE', 'BAD_BLOCK_SIZE', 'BAD_BOARD', 'BAD_BUFFERING', 'BAD_BUFFERLENGTH_NEG', 'BAD_BUFFERLENGTH_ODD', 'BAD_BUFFER_EXISTS', 'BAD_BUFFER_HANDLE', 'BAD_BUFFER_POINTER', 'BAD_BUFFER_QUERY_SIZE', 'BAD_BUFFER_SIZE', 'BAD_BUFFER_SIZE_POINTER', 'BAD_BUFFER_TYPE', 'BAD_COMPRESSION_SCHEME', 'BAD_COMPRESSOR_HANDLE', 'BAD_COMPRESSOR_HANDLE_POINTER', 'BAD_FRAME_SIZE', 'BAD_FUNCTIONALITY', 'BAD_FUNCTION_POINTER', 'BAD_HEADER_SIZE', 'BAD_INITIAL_VALUE', 'BAD_INTERNAL_FORMAT', 'BAD_LICENSE', 'BAD_MIN_GT_MAX', 'BAD_NO_BUFFERSPACE', 'BAD_NUMBER_OF_BLOCKS', 'BAD_PARAM', 'BAD_PARAM_ID_POINTER', 'BAD_PARAM_TYPE', 'BAD_POINTER', 'BAD_PVBUFFER', 'BAD_SCHEME_POINTER', 'BAD_STREAM_HEADER', 'BAD_STRING_POINTER', 'BAD_TEXT_STRING_PTR', 'BEST_FIT', 'BIDIRECTIONAL', 'BITRATE_POLICY', 'BITRATE_TARGET', 'BITS_PER_COMPONENT', 'BLENDING', 'BLOCK_SIZE', 'BOTTOM_UP', 'BUFFER_NOT_CREATED', 'BUF_DATA', 'BUF_FRAME', 'BytesPerPixel', 'BytesPerSample', 'CHANNEL_POLICY', 'CHROMA_THRESHOLD', 'CODEC',
# 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 test_support threading = test_support.import_module("threading") from platform import machine # Do this first so test will be skipped if module doesn't exist test_support.import_module('_winreg') # 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
import unittest import math import sys from test import test_support # Skip this test if the _testcapi module isn't available. test_support.import_module('_testcapi') from _testcapi import getargs_keywords import warnings """ > How about the following counterproposal. This also changes some of > the other format codes to be a little more regular. > > Code C type Range check > > b unsigned char 0..UCHAR_MAX > h signed short SHRT_MIN..SHRT_MAX > B unsigned char none ** > H unsigned short none ** > k * unsigned long none > I * unsigned int 0..UINT_MAX > i int INT_MIN..INT_MAX > l long LONG_MIN..LONG_MAX > K * unsigned long long none > L long long LLONG_MIN..LLONG_MAX > Notes: > > * New format codes.
import socket import urllib import sys import os import time try: import ssl except ImportError: ssl = None here = os.path.dirname(__file__) # Self-signed cert file for self-signed.pythontest.net CERT_selfsigned_pythontestdotnet = os.path.join(here, "selfsigned_pythontestdotnet.pem") mimetools = test_support.import_module("mimetools", deprecated=True) def _open_with_retry(func, host, *args, **kwargs): # Connecting to remote hosts is flaky. Make it more robust # by retrying the connection several times. for i in range(3): try: return func(host, *args, **kwargs) except IOError, last_exc: continue except: raise raise last_exc
from __future__ import print_function import unittest from test import test_support as support import os import sys # Setup bsddb warnings try: bsddb = support.import_module('bsddb', deprecated=True) except unittest.SkipTest: pass class NoAll(RuntimeError): pass class FailedImport(RuntimeError): pass class AllTest(unittest.TestCase): def check_all(self, modname): names = {} with support.check_warnings( (".* (module|package)", DeprecationWarning), quiet=True): try: exec "import %s" % modname in names except: # Silent fail here seems the best route since some modules
"Test posix functions" from test import test_support # Add alias for tests backported from Py3 after gratuitous rename in bpo-2621 support = test_support # Skip these tests if there is no posix module. posix = test_support.import_module('posix') import errno import sys import time import os import platform import pwd import shutil import stat import sys import tempfile import unittest import warnings _DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(), test_support.TESTFN + '-dummy-symlink') warnings.filterwarnings('ignore', '.* potential security risk .*', RuntimeWarning) class PosixTester(unittest.TestCase):
from test import test_support import unittest crypt = test_support.import_module('crypt') class CryptTestCase(unittest.TestCase): def test_crypt(self): c = crypt.crypt('mypassword', 'ab') if test_support.verbose: print 'Test encryption: ', c def test_main(): test_support.run_unittest(CryptTestCase) if __name__ == "__main__": test_main()
''' Test cases for pyclbr.py Nick Mathewson ''' from test.test_support import run_unittest, import_module import sys from types import ClassType, FunctionType, MethodType, BuiltinFunctionType import pyclbr from unittest import TestCase StaticMethodType = type(staticmethod(lambda: None)) ClassMethodType = type(classmethod(lambda c: None)) # Silence Py3k warning import_module('commands', deprecated=True) # This next line triggers an error on old versions of pyclbr. from commands import getstatus # Here we test the python class browser code. # # The main function in this suite, 'testModule', compares the output # of pyclbr with the introspected members of a module. Because pyclbr # is imperfect (as designed), testModule is called with a set of # members to ignore. class PyclbrTest(TestCase): def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' missing = (set(l1) ^ set(l2)) - set(ignore)
""" Tests for the mhlib module Nick Mathewson """ ### BUG: This suite doesn't currently test the mime functionality of ### mhlib. It should. import unittest from test.test_support import run_unittest, TESTFN, import_module import os, StringIO import sys mhlib = import_module('mhlib', deprecated=True) if (sys.platform.startswith("win") or sys.platform=="riscos" or sys.platform.startswith("atheos")): # mhlib.updateline() renames a file to the name of a file that already # exists. That causes a reasonable OS <wink> to complain in test_sequence # here, like the "OSError: [Errno 17] File exists" raised on Windows. # mhlib's listsubfolders() and listallfolders() do something with # link counts, and that causes test_listfolders() here to get back # an empty list from its call of listallfolders(). # The other tests here pass on Windows. raise unittest.SkipTest("skipped on %s -- " % sys.platform + "too many Unix assumptions") _mhroot = TESTFN+"_MH" _mhpath = os.path.join(_mhroot, "MH") _mhprofile = os.path.join(_mhroot, ".mh_profile") def normF(f):
from test import test_support as support from test.test_support import TESTFN, _4G, bigmemtest, import_module import unittest from cStringIO import StringIO import os import subprocess import sys try: import threading except ImportError: threading = None bz2 = import_module('bz2') from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor has_cmdline_bunzip2 = sys.platform not in ("win32", "os2emx", "riscos") class BaseTest(unittest.TestCase): "Base for other testcases." TEXT = 'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:\ndaemon:x:2:2:daemon:/sbin:\nadm:x:3:4:adm:/var/adm:\nlp:x:4:7:lp:/var/spool/lpd:\nsync:x:5:0:sync:/sbin:/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/var/spool/mail:\nnews:x:9:13:news:/var/spool/news:\nuucp:x:10:14:uucp:/var/spool/uucp:\noperator:x:11:0:operator:/root:\ngames:x:12:100:games:/usr/games:\ngopher:x:13:30:gopher:/usr/lib/gopher-data:\nftp:x:14:50:FTP User:/var/ftp:/bin/bash\nnobody:x:65534:65534:Nobody:/home:\npostfix:x:100:101:postfix:/var/spool/postfix:\nniemeyer:x:500:500::/home/niemeyer:/bin/bash\npostgres:x:101:102:PostgreSQL Server:/var/lib/pgsql:/bin/bash\nmysql:x:102:103:MySQL server:/var/lib/mysql:/bin/bash\nwww:x:103:104::/var/www:/bin/false\n' DATA = 'BZh91AY&SY.\xc8N\x18\x00\x01>_\x80\x00\x10@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe00\x01\x99\xaa\x00\xc0\x03F\x86\x8c#&\x83F\x9a\x03\x06\xa6\xd0\xa6\x93M\x0fQ\xa7\xa8\x06\x804hh\x12$\x11\xa4i4\xf14S\xd2<Q\xb5\x0fH\xd3\xd4\xdd\xd5\x87\xbb\xf8\x94\r\x8f\xafI\x12\xe1\xc9\xf8/E\x00pu\x89\x12]\xc9\xbbDL\nQ\x0e\t1\x12\xdf\xa0\xc0\x97\xac2O9\x89\x13\x94\x0e\x1c7\x0ed\x95I\x0c\xaaJ\xa4\x18L\x10\x05#\x9c\xaf\xba\xbc/\x97\x8a#C\xc8\xe1\x8cW\xf9\xe2\xd0\xd6M\xa7\x8bXa<e\x84t\xcbL\xb3\xa7\xd9\xcd\xd1\xcb\x84.\xaf\xb3\xab\xab\xad`n}\xa0lh\tE,\x8eZ\x15\x17VH>\x88\xe5\xcd9gd6\x0b\n\xe9\x9b\xd5\x8a\x99\xf7\x08.K\x8ev\xfb\xf7xw\xbb\xdf\xa1\x92\xf1\xdd|/";\xa2\xba\x9f\xd5\xb1#A\xb6\xf6\xb3o\xc9\xc5y\\\xebO\xe7\x85\x9a\xbc\xb6f8\x952\xd5\xd7"%\x89>V,\xf7\xa6z\xe2\x9f\xa3\xdf\x11\x11"\xd6E)I\xa9\x13^\xca\xf3r\xd0\x03U\x922\xf26\xec\xb6\xed\x8b\xc3U\x13\x9d\xc5\x170\xa4\xfa^\x92\xacDF\x8a\x97\xd6\x19\xfe\xdd\xb8\xbd\x1a\x9a\x19\xa3\x80ankR\x8b\xe5\xd83]\xa9\xc6\x08\x82f\xf6\xb9"6l$\xb8j@\xc0\x8a\xb0l1..\xbak\x83ls\x15\xbc\xf4\xc1\x13\xbe\xf8E\xb8\x9d\r\xa8\x9dk\x84\xd3n\xfa\xacQ\x07\xb1%y\xaav\xb4\x08\xe0z\x1b\x16\xf5\x04\xe9\xcc\xb9\x08z\x1en7.G\xfc]\xc9\x14\xe1B@\xbb!8`' DATA_CRLF = 'BZh91AY&SY\xaez\xbbN\x00\x01H\xdf\x80\x00\x12@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe0@\x01\xbc\xc6`\x86*\x8d=M\xa9\x9a\x86\xd0L@\x0fI\xa6!\xa1\x13\xc8\x88jdi\x8d@\x03@\x1a\x1a\x0c\x0c\x83 \x00\xc4h2\x19\x01\x82D\x84e\t\xe8\x99\x89\x19\x1ah\x00\r\x1a\x11\xaf\x9b\x0fG\xf5(\x1b\x1f?\t\x12\xcf\xb5\xfc\x95E\x00ps\x89\x12^\xa4\xdd\xa2&\x05(\x87\x04\x98\x89u\xe40%\xb6\x19\'\x8c\xc4\x89\xca\x07\x0e\x1b!\x91UIFU%C\x994!DI\xd2\xfa\xf0\xf1N8W\xde\x13A\xf5\x9cr%?\x9f3;I45A\xd1\x8bT\xb1<l\xba\xcb_\xc00xY\x17r\x17\x88\x08\x08@\xa0\ry@\x10\x04$)`\xf2\xce\x89z\xb0s\xec\x9b.iW\x9d\x81\xb5-+t\x9f\x1a\'\x97dB\xf5x\xb5\xbe.[.\xd7\x0e\x81\xe7\x08\x1cN`\x88\x10\xca\x87\xc3!"\x80\x92R\xa1/\xd1\xc0\xe6mf\xac\xbd\x99\xcca\xb3\x8780>\xa4\xc7\x8d\x1a\\"\xad\xa1\xabyBg\x15\xb9l\x88\x88\x91k"\x94\xa4\xd4\x89\xae*\xa6\x0b\x10\x0c\xd6\xd4m\xe86\xec\xb5j\x8a\x86j\';\xca.\x01I\xf2\xaaJ\xe8\x88\x8cU+t3\xfb\x0c\n\xa33\x13r2\r\x16\xe0\xb3(\xbf\x1d\x83r\xe7M\xf0D\x1365\xd8\x88\xd3\xa4\x92\xcb2\x06\x04\\\xc1\xb0\xea//\xbek&\xd8\xe6+t\xe5\xa1\x13\xada\x16\xder5"w]\xa2i\xb7[\x97R \xe2IT\xcd;Z\x04dk4\xad\x8a\t\xd3\x81z\x10\xf1:^`\xab\x1f\xc5\xdc\x91N\x14$+\x9e\xae\xd3\x80' EMPTY_DATA = 'BZh9\x17rE8P\x90\x00\x00\x00\x00' if has_cmdline_bunzip2: def decompress(self, data): pop = subprocess.Popen("bunzip2",
""" Test cases for the dircache module Nick Mathewson """ import unittest from test.test_support import run_unittest, TESTFN, import_module dircache = import_module('dircache', deprecated=True) import os, time, sys, tempfile class DircacheTests(unittest.TestCase): def setUp(self): self.tempdir = tempfile.mkdtemp() def tearDown(self): for fname in os.listdir(self.tempdir): self.delTemp(fname) os.rmdir(self.tempdir) def writeTemp(self, fname): f = open(os.path.join(self.tempdir, fname), 'w') f.close() def mkdirTemp(self, fname): os.mkdir(os.path.join(self.tempdir, fname)) def delTemp(self, fname): fname = os.path.join(self.tempdir, fname) if os.path.isdir(fname): os.rmdir(fname)
import unittest from doctest import DocTestSuite from test import test_support as 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 = [] for i in range(n):
def test_get_config_h_filename(self): config_h = sysconfig.get_config_h_filename() # import_module skips the test when the CPython C Extension API # appears to not be supported self.assertTrue(os.path.isfile(config_h) or not import_module('_testcapi'), config_h)
""" Very minimal unittests for parts of the readline module. """ import os import unittest from test.test_support import run_unittest, import_module from test.script_helper import assert_python_ok # Skip tests if there is no readline module readline = import_module('readline') class TestHistoryManipulation (unittest.TestCase): """These tests were added to check that the libedit emulation on OSX and the "real" readline have the same interface for history manipulation. That's why the tests cover only a small subset of the interface. """ @unittest.skipIf(not hasattr(readline, 'clear_history'), "The history update test cannot be run because the " "clear_history method is not available.") def testHistoryUpdates(self): readline.clear_history() readline.add_history("first line") readline.add_history("second line") self.assertEqual(readline.get_history_item(0), None) self.assertEqual(readline.get_history_item(1), "first line") self.assertEqual(readline.get_history_item(2), "second line") readline.replace_history_item(0, "replaced line")
import os import pprint import unittest import tempfile import _hotshot import gc from test import test_support # Silence Py3k warning hotshot = test_support.import_module('hotshot', deprecated=True) from hotshot.log import ENTER, EXIT, LINE from hotshot import stats def shortfilename(fn): # We use a really shortened filename since an exact match is made, # and the source may be either a Python source file or a # pre-compiled bytecode file. if fn: return os.path.splitext(os.path.basename(fn))[0] else: return fn class UnlinkingLogReader(hotshot.log.LogReader): """Extend the LogReader so the log file is unlinked when we're done with it.""" def __init__(self, logfn): self.__logfn = logfn
from __future__ import with_statement import string import sys import time import random import unittest from test import test_support as support try: import thread import threading except ImportError: thread = None threading = None # Skip this test if the _testcapi module isn't available. _testcapi = support.import_module('_testcapi') class CAPITest(unittest.TestCase): @support.impl_detail("Currently broken on pypy", pypy=False) def test_buildvalue_N(self): _testcapi.test_buildvalue_N() skips = [] if support.check_impl_detail(pypy=True): skips += [ 'test_buildvalue_N', 'test_capsule', 'test_lazy_hash_inheritance', 'test_widechar',
from test import test_support as 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 from test_support import reap_threads, verbose, transient_internet import unittest try: import ssl except ImportError: ssl = None CERTFILE = None class TestImaplib(unittest.TestCase): def test_that_Time2Internaldate_returns_a_result(self): # We can check only that it successfully produces a result, # not the correctness of the result itself, since the result # depends on the timezone the machine is in. timevalues = [2000000000, 2000000000.0, time.localtime(2000000000), '"18-May-2033 05:33:20 +0200"']
import os import unittest from test import test_support # Skip this test if _tkinter wasn't built or gui resource is not available. test_support.import_module('_tkinter') test_support.requires('gui') this_dir = os.path.dirname(os.path.abspath(__file__)) lib_tk_test = os.path.abspath( os.path.join(this_dir, os.path.pardir, 'lib-tk', 'test')) with test_support.DirsOnSysPath(lib_tk_test): import runtktests import Tkinter as tkinter import ttk from _tkinter import TclError root = None try: root = tkinter.Tk() button = ttk.Button(root) button.destroy() del button except TclError as msg: # assuming ttk is not available raise unittest.SkipTest("ttk not available: %s" % msg) finally: if root is not None: root.destroy()
#!/Applications/Plone/Python-2.7/bin/python """Whimpy test script for the cd module Roger E. Masse """ from test.test_support import verbose, import_module cd = import_module('cd') cdattrs = ['BLOCKSIZE', 'CDROM', 'DATASIZE', 'ERROR', 'NODISC', 'PAUSED', 'PLAYING', 'READY', 'STILL', '__doc__', '__name__', 'atime', 'audio', 'catalog', 'control', 'createparser', 'error', 'ident', 'index', 'msftoframe', 'open', 'pnum', 'ptime'] # This is a very inobtrusive test for the existence of the cd module and all its # attributes. More comprehensive examples can be found in Demo/cd and # require that you have a CD and a CD ROM drive def test_main(): # touch all the attributes of cd without doing anything if verbose: print 'Touching cd module attributes...' for attr in cdattrs: if verbose: print 'touching: ', attr getattr(cd, attr) if __name__ == '__main__': test_main()
#! /usr/bin/env python """Test script for the imageop module. This has the side effect of partially testing the imgfile module as well. Roger E. Masse """ from test.test_support import verbose, unlink, import_module, run_unittest imageop = import_module('imageop', deprecated=True) import uu, os, unittest SIZES = (1, 2, 3, 4) _VALUES = (1, 2, 2**10, 2**15 - 1, 2**15, 2**15 + 1, 2**31 - 2, 2**31 - 1) VALUES = tuple(-x for x in reversed(_VALUES)) + (0, ) + _VALUES AAAAA = "A" * 1024 MAX_LEN = 2**20 class InputValidationTests(unittest.TestCase): def _check(self, name, size=None, *extra): func = getattr(imageop, name) for height in VALUES: for width in VALUES: strlen = abs(width * height) if size: strlen *= size if strlen < MAX_LEN: data = "A" * strlen else: data = AAAAA if size:
# Test driver for bsddb package. """ Run all test cases. """ import os import sys import tempfile import time import unittest from test.test_support import requires, run_unittest, import_module # Skip test if _bsddb module was not built. import_module('_bsddb') # Silence Py3k warning import_module('bsddb', deprecated=True) # When running as a script instead of within the regrtest framework, skip the # requires test, since it's obvious we want to run them. if __name__ != '__main__': requires('bsddb') verbose = False if 'verbose' in sys.argv: verbose = True sys.argv.remove('verbose') if 'silent' in sys.argv: # take care of old flag, just in case verbose = False sys.argv.remove('silent')
#! /usr/bin/env python """Test dlmodule.c Roger E. Masse revised strategy by Barry Warsaw """ import unittest from test.test_support import verbose, import_module dl = import_module('dl', deprecated=True) sharedlibs = [ ('/usr/lib/libc.so', 'getpid'), ('/lib/libc.so.6', 'getpid'), ('/usr/bin/cygwin1.dll', 'getpid'), ('/usr/lib/libc.dylib', 'getpid'), ] def test_main(): for s, func in sharedlibs: try: if verbose: print 'trying to open:', s, l = dl.open(s) except dl.error, err: if verbose: print 'failed', repr(str(err)) pass else: if verbose: print 'succeeded...', l.call(func)
# expected: fail import unittest from test import test_support import os import subprocess MacOS = test_support.import_module('MacOS') TESTFN2 = test_support.TESTFN + '2' class TestMacOS(unittest.TestCase): @unittest.skipUnless(os.path.exists('/Developer/Tools/SetFile'), '/Developer/Tools/SetFile does not exist') def testGetCreatorAndType(self): try: fp = open(test_support.TESTFN, 'w') fp.write('\n') fp.close() subprocess.call( ['/Developer/Tools/SetFile', '-t', 'ABCD', '-c', 'EFGH', test_support.TESTFN]) cr, tp = MacOS.GetCreatorAndType(test_support.TESTFN) self.assertEqual(tp, 'ABCD') self.assertEqual(cr, 'EFGH') finally: os.unlink(test_support.TESTFN) @unittest.skipUnless(os.path.exists('/Developer/Tools/GetFileInfo'),
import os import base64 import urlparse import urllib2 import BaseHTTPServer import unittest import hashlib from test import test_support mimetools = test_support.import_module('mimetools', deprecated=True) threading = test_support.import_module('threading') try: import ssl except ImportError: ssl = None here = os.path.dirname(__file__) # Self-signed cert file for 'localhost' CERT_localhost = os.path.join(here, 'keycert.pem') # Self-signed cert file for 'fakehostname' CERT_fakehostname = os.path.join(here, 'keycert2.pem') # Loopback http server infrastructure class LoopbackHttpServer(BaseHTTPServer.HTTPServer): """HTTP server w/ a few modifications that make it useful for loopback testing purposes. """
import unittest import re import sys import os from test import test_support from subprocess import Popen, PIPE # Skip this test if the _tkinter module wasn't built. _tkinter = test_support.import_module('_tkinter') import Tkinter as 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.match(r'(\d+)\.(\d+)([ab.])(\d+)$', patchlevel) major, minor, releaselevel, serial = m.groups() major, minor, serial = int(major), int(minor), int(serial) releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel]
"""Test script for the gzip module. """ import unittest from test import test_support import os import io import struct import tempfile gzip = test_support.import_module('gzip') data1 = """ int length=DEFAULTALLOC, err = Z_OK; PyObject *RetVal; int flushmode = Z_FINISH; unsigned long start_total_out; """ data2 = """/* zlibmodule.c -- gzip-compatible data compression */ /* See http://www.gzip.org/zlib/ /* See http://www.winimage.com/zLibDll for Windows */ """ class TestGzip(unittest.TestCase): filename = test_support.TESTFN def setUp(self): test_support.unlink(self.filename) def tearDown(self):