def test_main(): support.requires("network") support.run_unittest(AuthTests, OtherNetworkTests, CloseSocketTest, TimeoutTest, )
def setUpModule(): try: import signal # The default handler for SIGXFSZ is to abort the process. # By ignoring it, system calls exceeding the file size resource # limit will raise OSError instead of crashing the interpreter. signal.signal(signal.SIGXFSZ, signal.SIG_IGN) except (ImportError, AttributeError): pass # On Windows and Mac OSX this test consumes large resources; It # takes a long time to build the >2 GiB file and takes >2 GiB of disk # space therefore the resource must be enabled to run this test. # If not, nothing after this line stanza will be executed. if sys.platform[:3] == 'win' or sys.platform == 'darwin': requires('largefile', 'test requires %s bytes and a long time to run' % str(size)) else: # Only run if the current filesystem supports large files. # (Skip this test on Windows, since we now always support # large files.) f = open(TESTFN, 'wb', buffering=0) try: # 2**31 == 2147483648 f.seek(2147483649) # Seeking is not enough of a test: you must write and flush, too! f.write(b'x') f.flush() except (OSError, OverflowError): raise unittest.SkipTest("filesystem does not have " "largefile support") finally: f.close() unlink(TESTFN)
def setUpClass(cls): requires('gui') cls.root = Tk() cls.TV = TV = tv.TextViewer TV.transient = Func() TV.grab_set = Func() TV.wait_window = Func()
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() editor = Editor(root=cls.root) cls.text = editor.text.text # Test code does not need the wrapper. cls.formatter = pg.FormatParagraph(editor).format_paragraph_event
def test_main(): support.requires('network') with support.check_py3k_warnings( ("urllib.urlopen.. has been removed", DeprecationWarning)): support.run_unittest(URLTimeoutTest, urlopenNetworkTests, urlretrieveNetworkTests)
def test_bad_address(self): # Make sure proper exception is raised when connecting to a bogus # address. # as indicated by the comment below, this might fail with some ISP, # so we run the test only when -unetwork/-uall is specified to # mitigate the problem a bit (see #17564) support.requires('network') self.assertRaises(OSError, # Given that both VeriSign and various ISPs have in # the past or are presently hijacking various invalid # domain name requests in an attempt to boost traffic # to their own sites, finding a domain name to use # for this test is difficult. RFC2606 leads one to # believe that '.invalid' should work, but experience # seemed to indicate otherwise. Single character # TLDs are likely to remain invalid, so this seems to # be the best choice. The trailing '.' prevents a # related problem: The normal DNS resolver appends # the domain names from the search path if there is # no '.' the end and, and if one of those domains # implements a '*' rule a result is returned. # However, none of this will prevent the test from # failing if the ISP hijacks all invalid domain # requests. The real solution would be to be able to # parameterize the framework with a mock resolver. urllib.request.urlopen, "http://sadflkjsasf.i.nvali.d./")
def testPasswordProtectedSite(self): support.requires('network') with support.transient_internet('mueblesmoraleda.com'): url = 'http://mueblesmoraleda.com' robots_url = url + "/robots.txt" # First check the URL is usable for our purposes, since the # test site is a bit flaky. try: urlopen(robots_url) except HTTPError as e: if e.code not in {401, 403}: self.skipTest( "%r should return a 401 or 403 HTTP error, not %r" % (robots_url, e.code)) else: self.skipTest( "%r should return a 401 or 403 HTTP error, not succeed" % (robots_url)) parser = urllib.robotparser.RobotFileParser() parser.set_url(url) try: parser.read() except URLError: self.skipTest('%s is unavailable' % url) self.assertEqual(parser.can_fetch("*", robots_url), False)
def test_main(): support.requires('network') support.run_unittest( CreationTestCase, TCPTimeoutTestCase, UDPTimeoutTestCase, )
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() keylist = [['<Key-F12>'], ['<Control-Key-x>', '<Control-Key-X>']] cls.dialog = cls.Validator( cls.root, 'Title', '<<Test>>', keylist, _utest=True)
def setUpClass(cls): if 'tkinter' in str(Text): requires('gui') cls.tk = Tk() cls.text = Text(cls.tk) else: cls.text = Text() cls.auto_expand = AutoExpand(Dummy_Editwin(cls.text))
def testPythonOrg(self): support.requires('network') with support.transient_internet('www.python.org'): parser = urllib.robotparser.RobotFileParser( "http://www.python.org/robots.txt") parser.read() self.assertTrue( parser.can_fetch("*", "http://www.python.org/robots.txt"))
def test_networked(self): # Default settings: no cert verification is done support.requires("network") with support.transient_internet("svn.python.org"): h = client.HTTPSConnection("svn.python.org", 443) h.request("GET", "/") resp = h.getresponse() self._check_svn_python_org(resp)
def test_networked(self): # Default settings: no cert verification is done support.requires('network') with support.transient_internet('svn.python.org'): h = client.HTTPSConnection('svn.python.org', 443) h.request('GET', '/') resp = h.getresponse() self._check_svn_python_org(resp)
def setUpClass(cls): requires('gui') cls.root = tk.Tk() cls.root.withdraw() def cmd(tkpath, func): assert isinstance(tkpath, str) assert isinstance(func, type(cmd)) cls.root.createcommand = cmd
def test_networked_trusted_by_default_cert(self): # Default settings: requires a valid cert from a trusted CA support.requires('network') with support.transient_internet('www.python.org'): h = client.HTTPSConnection('www.python.org', 443) h.request('GET', '/') resp = h.getresponse() content_type = resp.getheader('content-type') self.assertIn('text/html', content_type)
def test_networked(self): # Default settings: requires a valid cert from a trusted CA import ssl support.requires('network') with support.transient_internet('self-signed.pythontest.net'): h = client.HTTPSConnection('self-signed.pythontest.net', 443) with self.assertRaises(ssl.SSLError) as exc_info: h.request('GET', '/') self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
def testPasswordProtectedSite(self): support.requires('network') with support.transient_internet('mueblesmoraleda.com'): url = 'http://mueblesmoraleda.com' parser = urllib.robotparser.RobotFileParser() parser.set_url(url) try: parser.read() except URLError: self.skipTest('%s is unavailable' % url) self.assertEqual(parser.can_fetch("*", url+"/robots.txt"), False)
def test_networked_bad_cert(self): # We feed a "CA" cert that is unrelated to the server's cert import ssl support.requires('network') with support.transient_internet('svn.python.org'): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(CERT_localhost) h = client.HTTPSConnection('svn.python.org', 443, context=context) with self.assertRaises(ssl.SSLError): h.request('GET', '/')
def test_networked_noverification(self): # Switch off cert verification import ssl support.requires('network') with support.transient_internet('self-signed.pythontest.net'): context = ssl._create_unverified_context() h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) h.request('GET', '/') resp = h.getresponse() self.assertIn('nginx', resp.getheader('server'))
def setUpClass(cls): svs = stackviewer.sys try: abc except NameError: svs.last_type, svs.last_value, svs.last_traceback = ( sys.exc_info()) requires('gui') cls.root = Tk() cls.root.withdraw()
def test_networked_good_cert(self): # We feed a CA cert that validates the server's cert import ssl support.requires('network') with support.transient_internet('svn.python.org'): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(CACERT_svn_python_org) h = client.HTTPSConnection('svn.python.org', 443, context=context) h.request('GET', '/') resp = h.getresponse() self._check_svn_python_org(resp)
def test_networked_bad_cert(self): # We feed a "CA" cert that is unrelated to the server's cert import ssl support.requires('network') with support.transient_internet('self-signed.pythontest.net'): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(CERT_localhost) h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) with self.assertRaises(ssl.SSLError) as exc_info: h.request('GET', '/') self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
def _make_test_file(self, num_zeroes, tail): if sys.platform[:3] == "win" or sys.platform == "darwin": requires("largefile", "test requires %s bytes and a long time to run" % str(0x180000000)) f = open(TESTFN, "w+b") try: f.seek(num_zeroes) f.write(tail) f.flush() except (IOError, OverflowError): f.close() raise unittest.SkipTest("filesystem does not have largefile support") return f
def get_test_tk_root(test_instance): """Helper for tests: Create a root Tk object.""" requires('gui') root = Tk() root.withdraw() def cleanup_root(): root.update_idletasks() root.destroy() test_instance.addCleanup(cleanup_root) return root
def test_large_filesize(self): if sys.platform[:3] == 'win' or sys.platform == 'darwin': requires('largefile', 'test requires %s bytes and a long time to run' % str(0x180000000)) self._working_largefile() with open(TESTFN, 'wb') as f: f.seek(0x17FFFFFFF) f.write(b" ") with open(TESTFN, 'rb') as f: with mmap.mmap(f.fileno(), 0x10000, access=mmap.ACCESS_READ) as m: self.assertEqual(m.size(), 0x180000000)
def setUpClass(cls): requires('gui') root = cls.root = Tk() root.withdraw() frame = cls.frame = Frame(root) text = cls.text = Text(frame) text.insert('1.0', code_sample) # Need to pack for creation of code context text widget. frame.pack(side='left', fill='both', expand=1) text.pack(side='top', fill='both', expand=1) cls.editor = DummyEditwin(root, frame, text) codecontext.idleConf.userCfg = testcfg
def test_networked_good_cert(self): # We feed the server's cert as a validating cert import ssl support.requires('network') with support.transient_internet('self-signed.pythontest.net'): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(CERT_selfsigned_pythontestdotnet) h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) h.request('GET', '/') resp = h.getresponse() server_string = resp.getheader('server') self.assertIn('nginx', server_string)
def get_tk_root(): requires('gui') # raise exception if tk unavailable try: root = tkinter._default_root except AttributeError: # it is possible to disable default root in Tkinter, although # I haven't seen people doing it (but apparently someone did it # here). root = None if root is None: # create a new master only if there isn't one already root = tkinter.Tk() return root
def _make_test_file(self, num_zeroes, tail): if sys.platform[:3] == 'win' or sys.platform == 'darwin': requires('largefile', 'test requires %s bytes and a long time to run' % str(0x180000000)) f = open(TESTFN, 'w+b') try: f.seek(num_zeroes) f.write(tail) f.flush() except (OSError, OverflowError, ValueError): try: f.close() except (OSError, OverflowError): pass raise unittest.SkipTest("filesystem does not have largefile support") return f
def test_main(): # On Windows and Mac OSX this test comsumes large resources; It # takes a long time to build the >2GB file and takes >2GB of disk # space therefore the resource must be enabled to run this test. # If not, nothing after this line stanza will be executed. if sys.platform[:3] == 'win' or sys.platform == 'darwin': requires('largefile', 'test requires %s bytes and a long time to run' % str(size)) else: # Only run if the current filesystem supports large files. # (Skip this test on Windows, since we now always support # large files.) f = open(TESTFN, 'wb', buffering=0) try: # 2**31 == 2147483648 f.seek(2147483649) # Seeking is not enough of a test: you must write and # flush, too! f.write(b'x') f.flush() except (IOError, OverflowError): f.close() unlink(TESTFN) raise unittest.SkipTest("filesystem does not have largefile support") else: f.close() suite = unittest.TestSuite() for _open, prefix in [(io.open, 'C'), (pyio.open, 'Py')]: class TestCase(LargeFileTest): pass TestCase.open = staticmethod(_open) TestCase.__name__ = prefix + LargeFileTest.__name__ suite.addTest(TestCase('test_seek')) suite.addTest(TestCase('test_osstat')) suite.addTest(TestCase('test_seek_read')) suite.addTest(TestCase('test_lseek')) with _open(TESTFN, 'wb') as f: if hasattr(f, 'truncate'): suite.addTest(TestCase('test_truncate')) suite.addTest(TestCase('test_seekable')) unlink(TESTFN) try: run_unittest(suite) finally: unlink(TESTFN)
def setUpClass(cls): support.requires('network') with support.transient_internet(cls.base_url): cls.parser = urllib.robotparser.RobotFileParser(cls.robots_txt) cls.parser.read()
# Tests of the full ZIP64 functionality of zipfile # The support.requires call is the only reason for keeping this separate # from test_zipfile from test import support # XXX(nnorwitz): disable this test by looking for extra largfile resource # which doesn't exist. This test takes over 30 minutes to run in general # and requires more disk space than most of the buildbots. support.requires( 'extralargefile', 'test requires loads of disk-space bytes and a long time to run') import zipfile, os, unittest import time import sys from io import StringIO from tempfile import TemporaryFile from test.support import TESTFN, requires_zlib TESTFN2 = TESTFN + "2" # How much time in seconds can pass before we print a 'Still working' message. _PRINT_WORKING_MSG_INTERVAL = 5 * 60 class TestsWithSourceFile(unittest.TestCase): def setUp(self): # Create test data. line_gen = ("Test of zipfile line %d." % i for i in range(1000000))
# import os import string import sys import tempfile import unittest from test.support import (requires, import_module, verbose, SaveSignals, cpython_only) # 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')
def setUpClass(cls): requires('gui') root = cls.root = Tk() root.withdraw() text = cls.text = Text(root) cls.percolator = Percolator(text)
def setUpClass(cls): requires('gui') root = cls.root = Tk() root.withdraw() w = cls.window = outwin.OutputWindow(None, None, None, root) cls.text = w.text = Text(root)
def setUpClass(cls): requires('gui') cls.root = Tk() editor = Editor(root=cls.root) cls.text = editor.text.text # Test code does not need the wrapper. cls.formatter = fp.FormatParagraph(editor).format_paragraph_event
def setUpClass(cls): requires('gui') root = cls.root = Tk() root.withdraw() cls.text = Text(root)
import errno import unittest from test import support from test.support import os_helper from test.support import socket_helper from test.test_urllib2 import sanepathname2url import os import socket import urllib.error import urllib.request import sys support.requires("network") def _retry_thrice(func, exc, *args, **kwargs): for i in range(3): try: return func(*args, **kwargs) except exc as e: last_exc = e continue raise last_exc def _wrap_with_retry_thrice(func, exc): def wrapped(*args, **kwargs): return _retry_thrice(func, exc, *args, **kwargs) return wrapped
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.dialog = About(cls.root, _utest=True)
# Ridiculously simple test of the winsound module for Windows. import unittest from test import support support.requires('audio') import time import os import subprocess winsound = support.import_module('winsound') ctypes = support.import_module('ctypes') 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() == 0: return False key = winreg.OpenKeyEx( winreg.HKEY_CURRENT_USER, "AppEvents\Schemes\Apps\.Default\{0}\.Default".format(sound)) return winreg.EnumValue(key, 0)[1] != "" except OSError: return False class BeepTest(unittest.TestCase):
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.text = Text(cls.root) cls.calltip = calltip_w.CalltipWindow(cls.text)
def setUpClass(cls): requires('gui') from tkinter import Tk, Text cls.Text = Text cls.root = Tk()
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.window = Editor(root=cls.root)
def test_main(): support.requires('network') support.run_unittest(URLTimeoutTest, urlopenNetworkTests, urlretrieveNetworkTests)
def setUpClass(cls): requires('gui') cls.root = Tk()
def setUpClass(cls): support.requires("network") with support.transient_internet(cls.NNTP_HOST): cls.server = cls.NNTP_CLASS(cls.NNTP_HOST, timeout=TIMEOUT, usenetrc=False)
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.text = Text(cls.root) cls.editwin = DummyEditwin(cls.text)
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.pb = pathbrowser.PathBrowser(cls.root, _utest=True)
def test_main(): support.requires("network") support.run_unittest(PythonBuildersTest)
# limit will raise IOError instead of crashing the interpreter. oldhandler = signal.signal(signal.SIGXFSZ, signal.SIG_IGN) except (ImportError, AttributeError): pass # create >2GB file (2GB = 2147483648 bytes) size = 2500000000 name = support.TESTFN # On Windows and Mac OSX this test comsumes large resources; It takes # a long time to build the >2GB file and takes >2GB of disk space # therefore the resource must be enabled to run this test. If not, # nothing after this line stanza will be executed. if sys.platform[:3] == 'win' or sys.platform == 'darwin' or support.is_jython: support.requires( 'largefile', 'test requires %s bytes and a long time to run' % str(size)) else: # Only run if the current filesystem supports large files. # (Skip this test on Windows, since we now always support large files.) f = open(support.TESTFN, 'wb') try: # 2**31 == 2147483648 f.seek(2147483649) # Seeking is not enough of a test: you must write and flush, too! f.write("x") f.flush() except (IOError, OverflowError): f.close() os.unlink(support.TESTFN) raise support.TestSkipped("filesystem does not have largefile support")
def setUpClass(cls): requires('gui') cls.root = tk.Tk() cls.root.withdraw() cls.orig_platform = macosx.platform
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.text = Text(cls.root) cls.acw = acw.AutoCompleteWindow(cls.text)
import unittest from test import support from test.test_urllib2 import sanepathname2url import os import socket import urllib.error import urllib.request import sys support.requires('network') TIMEOUT = 60 def _retry_thrice(func, exc, *args, **kwargs): for i in range(3): try: return func(*args, **kwargs) except exc as e: last_exc = e continue raise last_exc def _wrap_with_retry_thrice(func, exc): def wrapped(*args, **kwargs): return _retry_thrice(func, exc, *args, **kwargs) return wrapped _urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen, urllib.error.URLError)
"Test replace, coverage 78%." from edit.replace import ReplaceDialog import unittest from test.support import requires requires('gui') from tkinter import Tk, Text from unittest.mock import Mock from edit.edit_test.mock_tk import Mbox import edit.searchengine as se orig_mbox = se.tkMessageBox showerror = Mbox.showerror class ReplaceDialogTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.root = Tk() cls.root.withdraw() se.tkMessageBox = Mbox cls.engine = se.SearchEngine(cls.root) cls.dialog = ReplaceDialog(cls.root, cls.engine) cls.dialog.bell = lambda: None cls.dialog.ok = Mock() cls.text = Text(cls.root) cls.text.undo_block_start = Mock() cls.text.undo_block_stop = Mock() cls.dialog.text = cls.text
def setUpClass(cls): requires('gui') cls.tk = Tk() cls.text = Text(cls.tk) cls.auto_expand = AutoExpand(DummyEditwin(cls.text)) cls.auto_expand.bell = lambda: None
import os import sys import unittest import test.support as test_support from tkinter import Tcl, TclError test_support.requires('gui') class TkLoadTest(unittest.TestCase): @unittest.skipIf('DISPLAY' not in os.environ, 'No $DISPLAY set.') def testLoadTk(self): tcl = Tcl() self.assertRaises(TclError, tcl.winfo_geometry) tcl.loadtk() self.assertEqual('1x1+0+0', tcl.winfo_geometry()) tcl.destroy() def testLoadTkFailure(self): old_display = None if sys.platform.startswith(('win', 'darwin', 'cygwin', 'msys')): # no failure possible on windows? # XXX Maybe on tk older than 8.4.13 it would be possible, # see tkinter.h. return with test_support.EnvironmentVarGuard() as env: if 'DISPLAY' in os.environ: del env['DISPLAY'] # on some platforms, deleting environment variables # doesn't actually carry through to the process level
import os import unittest from test import support # Skip this test if _tkinter wasn't built. support.import_module('_tkinter') # Make sure tkinter._fix runs to set up the environment support.import_fresh_module('tkinter') # Skip test if tk cannot be initialized. support.requires('gui') from _tkinter import TclError from tkinter import ttk from tkinter.test import runtktests from tkinter.test.support import get_tk_root try: ttk.Button() except TclError as msg: # assuming ttk is not available raise unittest.SkipTest("ttk not available: %s" % msg) def test_main(enable_gui=False): if enable_gui: if support.use_resources is None: support.use_resources = ['gui'] elif 'gui' not in support.use_resources: support.use_resources.append('gui')
def setUpClass(cls): requires('gui') cls.root = Tk() tv.tkMessageBox = Mbox
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw()
def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() cls.mc = multicall.MultiCallCreator(Text)