Update Darwin to Python 3.5 (64bit)
This commit is contained in:
parent
1f23120cc3
commit
c8252cce16
2576 changed files with 138841 additions and 63771 deletions
BIN
Darwin/lib/libcrypto.1.0.0.dylib
Normal file
BIN
Darwin/lib/libcrypto.1.0.0.dylib
Normal file
Binary file not shown.
BIN
Darwin/lib/libexslt.0.dylib
Normal file
BIN
Darwin/lib/libexslt.0.dylib
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Darwin/lib/liblzma.5.dylib
Normal file
BIN
Darwin/lib/liblzma.5.dylib
Normal file
Binary file not shown.
Binary file not shown.
1
Darwin/lib/libreadline.6.dylib
Symbolic link
1
Darwin/lib/libreadline.6.dylib
Symbolic link
|
|
@ -0,0 +1 @@
|
|||
libreadline.6.3.dylib
|
||||
BIN
Darwin/lib/libsqlite3.0.dylib
Normal file
BIN
Darwin/lib/libsqlite3.0.dylib
Normal file
Binary file not shown.
BIN
Darwin/lib/libssl.1.0.0.dylib
Normal file
BIN
Darwin/lib/libssl.1.0.0.dylib
Normal file
Binary file not shown.
BIN
Darwin/lib/libxml2.2.dylib
Normal file
BIN
Darwin/lib/libxml2.2.dylib
Normal file
Binary file not shown.
BIN
Darwin/lib/libxslt.1.dylib
Normal file
BIN
Darwin/lib/libxslt.1.dylib
Normal file
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
|||
libz.1.2.8.dylib
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
# This module is used to map the old Python 2 names to the new names used in
|
||||
# Python 3 for the pickle module. This needed to make pickle streams
|
||||
# generated with Python 2 loadable by Python 3.
|
||||
|
||||
# This is a copy of lib2to3.fixes.fix_imports.MAPPING. We cannot import
|
||||
# lib2to3 and use the mapping defined there, because lib2to3 uses pickle.
|
||||
# Thus, this could cause the module to be imported recursively.
|
||||
IMPORT_MAPPING = {
|
||||
'StringIO': 'io',
|
||||
'cStringIO': 'io',
|
||||
'cPickle': 'pickle',
|
||||
'__builtin__' : 'builtins',
|
||||
'copy_reg': 'copyreg',
|
||||
'Queue': 'queue',
|
||||
'SocketServer': 'socketserver',
|
||||
'ConfigParser': 'configparser',
|
||||
'repr': 'reprlib',
|
||||
'FileDialog': 'tkinter.filedialog',
|
||||
'tkFileDialog': 'tkinter.filedialog',
|
||||
'SimpleDialog': 'tkinter.simpledialog',
|
||||
'tkSimpleDialog': 'tkinter.simpledialog',
|
||||
'tkColorChooser': 'tkinter.colorchooser',
|
||||
'tkCommonDialog': 'tkinter.commondialog',
|
||||
'Dialog': 'tkinter.dialog',
|
||||
'Tkdnd': 'tkinter.dnd',
|
||||
'tkFont': 'tkinter.font',
|
||||
'tkMessageBox': 'tkinter.messagebox',
|
||||
'ScrolledText': 'tkinter.scrolledtext',
|
||||
'Tkconstants': 'tkinter.constants',
|
||||
'Tix': 'tkinter.tix',
|
||||
'ttk': 'tkinter.ttk',
|
||||
'Tkinter': 'tkinter',
|
||||
'markupbase': '_markupbase',
|
||||
'_winreg': 'winreg',
|
||||
'thread': '_thread',
|
||||
'dummy_thread': '_dummy_thread',
|
||||
'dbhash': 'dbm.bsd',
|
||||
'dumbdbm': 'dbm.dumb',
|
||||
'dbm': 'dbm.ndbm',
|
||||
'gdbm': 'dbm.gnu',
|
||||
'xmlrpclib': 'xmlrpc.client',
|
||||
'DocXMLRPCServer': 'xmlrpc.server',
|
||||
'SimpleXMLRPCServer': 'xmlrpc.server',
|
||||
'httplib': 'http.client',
|
||||
'htmlentitydefs' : 'html.entities',
|
||||
'HTMLParser' : 'html.parser',
|
||||
'Cookie': 'http.cookies',
|
||||
'cookielib': 'http.cookiejar',
|
||||
'BaseHTTPServer': 'http.server',
|
||||
'SimpleHTTPServer': 'http.server',
|
||||
'CGIHTTPServer': 'http.server',
|
||||
'test.test_support': 'test.support',
|
||||
'commands': 'subprocess',
|
||||
'UserString' : 'collections',
|
||||
'UserList' : 'collections',
|
||||
'urlparse' : 'urllib.parse',
|
||||
'robotparser' : 'urllib.robotparser',
|
||||
'whichdb': 'dbm',
|
||||
'anydbm': 'dbm'
|
||||
}
|
||||
|
||||
|
||||
# This contains rename rules that are easy to handle. We ignore the more
|
||||
# complex stuff (e.g. mapping the names in the urllib and types modules).
|
||||
# These rules should be run before import names are fixed.
|
||||
NAME_MAPPING = {
|
||||
('__builtin__', 'xrange'): ('builtins', 'range'),
|
||||
('__builtin__', 'reduce'): ('functools', 'reduce'),
|
||||
('__builtin__', 'intern'): ('sys', 'intern'),
|
||||
('__builtin__', 'unichr'): ('builtins', 'chr'),
|
||||
('__builtin__', 'basestring'): ('builtins', 'str'),
|
||||
('__builtin__', 'long'): ('builtins', 'int'),
|
||||
('itertools', 'izip'): ('builtins', 'zip'),
|
||||
('itertools', 'imap'): ('builtins', 'map'),
|
||||
('itertools', 'ifilter'): ('builtins', 'filter'),
|
||||
('itertools', 'ifilterfalse'): ('itertools', 'filterfalse'),
|
||||
}
|
||||
|
||||
PYTHON2_EXCEPTIONS = (
|
||||
"ArithmeticError",
|
||||
"AssertionError",
|
||||
"AttributeError",
|
||||
"BaseException",
|
||||
"BufferError",
|
||||
"BytesWarning",
|
||||
"DeprecationWarning",
|
||||
"EOFError",
|
||||
"EnvironmentError",
|
||||
"Exception",
|
||||
"FloatingPointError",
|
||||
"FutureWarning",
|
||||
"GeneratorExit",
|
||||
"IOError",
|
||||
"ImportError",
|
||||
"ImportWarning",
|
||||
"IndentationError",
|
||||
"IndexError",
|
||||
"KeyError",
|
||||
"KeyboardInterrupt",
|
||||
"LookupError",
|
||||
"MemoryError",
|
||||
"NameError",
|
||||
"NotImplementedError",
|
||||
"OSError",
|
||||
"OverflowError",
|
||||
"PendingDeprecationWarning",
|
||||
"ReferenceError",
|
||||
"RuntimeError",
|
||||
"RuntimeWarning",
|
||||
# StandardError is gone in Python 3, so we map it to Exception
|
||||
"StopIteration",
|
||||
"SyntaxError",
|
||||
"SyntaxWarning",
|
||||
"SystemError",
|
||||
"SystemExit",
|
||||
"TabError",
|
||||
"TypeError",
|
||||
"UnboundLocalError",
|
||||
"UnicodeDecodeError",
|
||||
"UnicodeEncodeError",
|
||||
"UnicodeError",
|
||||
"UnicodeTranslateError",
|
||||
"UnicodeWarning",
|
||||
"UserWarning",
|
||||
"ValueError",
|
||||
"Warning",
|
||||
"ZeroDivisionError",
|
||||
)
|
||||
|
||||
for excname in PYTHON2_EXCEPTIONS:
|
||||
NAME_MAPPING[("exceptions", excname)] = ("builtins", excname)
|
||||
|
||||
NAME_MAPPING[("exceptions", "StandardError")] = ("builtins", "Exception")
|
||||
|
||||
# Same, but for 3.x to 2.x
|
||||
REVERSE_IMPORT_MAPPING = dict((v, k) for (k, v) in IMPORT_MAPPING.items())
|
||||
REVERSE_NAME_MAPPING = dict((v, k) for (k, v) in NAME_MAPPING.items())
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
import collections
|
||||
import subprocess
|
||||
|
||||
from . import protocols
|
||||
from . import tasks
|
||||
from . import transports
|
||||
|
||||
|
||||
class BaseSubprocessTransport(transports.SubprocessTransport):
|
||||
|
||||
def __init__(self, loop, protocol, args, shell,
|
||||
stdin, stdout, stderr, bufsize,
|
||||
extra=None, **kwargs):
|
||||
super().__init__(extra)
|
||||
self._protocol = protocol
|
||||
self._loop = loop
|
||||
|
||||
self._pipes = {}
|
||||
if stdin == subprocess.PIPE:
|
||||
self._pipes[0] = None
|
||||
if stdout == subprocess.PIPE:
|
||||
self._pipes[1] = None
|
||||
if stderr == subprocess.PIPE:
|
||||
self._pipes[2] = None
|
||||
self._pending_calls = collections.deque()
|
||||
self._finished = False
|
||||
self._returncode = None
|
||||
self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
|
||||
stderr=stderr, bufsize=bufsize, **kwargs)
|
||||
self._extra['subprocess'] = self._proc
|
||||
|
||||
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
|
||||
raise NotImplementedError
|
||||
|
||||
def _make_write_subprocess_pipe_proto(self, fd):
|
||||
raise NotImplementedError
|
||||
|
||||
def _make_read_subprocess_pipe_proto(self, fd):
|
||||
raise NotImplementedError
|
||||
|
||||
def close(self):
|
||||
for proto in self._pipes.values():
|
||||
proto.pipe.close()
|
||||
if self._returncode is None:
|
||||
self.terminate()
|
||||
|
||||
def get_pid(self):
|
||||
return self._proc.pid
|
||||
|
||||
def get_returncode(self):
|
||||
return self._returncode
|
||||
|
||||
def get_pipe_transport(self, fd):
|
||||
if fd in self._pipes:
|
||||
return self._pipes[fd].pipe
|
||||
else:
|
||||
return None
|
||||
|
||||
def send_signal(self, signal):
|
||||
self._proc.send_signal(signal)
|
||||
|
||||
def terminate(self):
|
||||
self._proc.terminate()
|
||||
|
||||
def kill(self):
|
||||
self._proc.kill()
|
||||
|
||||
@tasks.coroutine
|
||||
def _post_init(self):
|
||||
proc = self._proc
|
||||
loop = self._loop
|
||||
if proc.stdin is not None:
|
||||
_, pipe = yield from loop.connect_write_pipe(
|
||||
lambda: WriteSubprocessPipeProto(self, 0),
|
||||
proc.stdin)
|
||||
self._pipes[0] = pipe
|
||||
if proc.stdout is not None:
|
||||
_, pipe = yield from loop.connect_read_pipe(
|
||||
lambda: ReadSubprocessPipeProto(self, 1),
|
||||
proc.stdout)
|
||||
self._pipes[1] = pipe
|
||||
if proc.stderr is not None:
|
||||
_, pipe = yield from loop.connect_read_pipe(
|
||||
lambda: ReadSubprocessPipeProto(self, 2),
|
||||
proc.stderr)
|
||||
self._pipes[2] = pipe
|
||||
|
||||
assert self._pending_calls is not None
|
||||
|
||||
self._loop.call_soon(self._protocol.connection_made, self)
|
||||
for callback, data in self._pending_calls:
|
||||
self._loop.call_soon(callback, *data)
|
||||
self._pending_calls = None
|
||||
|
||||
def _call(self, cb, *data):
|
||||
if self._pending_calls is not None:
|
||||
self._pending_calls.append((cb, data))
|
||||
else:
|
||||
self._loop.call_soon(cb, *data)
|
||||
|
||||
def _pipe_connection_lost(self, fd, exc):
|
||||
self._call(self._protocol.pipe_connection_lost, fd, exc)
|
||||
self._try_finish()
|
||||
|
||||
def _pipe_data_received(self, fd, data):
|
||||
self._call(self._protocol.pipe_data_received, fd, data)
|
||||
|
||||
def _process_exited(self, returncode):
|
||||
assert returncode is not None, returncode
|
||||
assert self._returncode is None, self._returncode
|
||||
self._returncode = returncode
|
||||
self._call(self._protocol.process_exited)
|
||||
self._try_finish()
|
||||
|
||||
def _try_finish(self):
|
||||
assert not self._finished
|
||||
if self._returncode is None:
|
||||
return
|
||||
if all(p is not None and p.disconnected
|
||||
for p in self._pipes.values()):
|
||||
self._finished = True
|
||||
self._loop.call_soon(self._call_connection_lost, None)
|
||||
|
||||
def _call_connection_lost(self, exc):
|
||||
try:
|
||||
self._protocol.connection_lost(exc)
|
||||
finally:
|
||||
self._proc = None
|
||||
self._protocol = None
|
||||
self._loop = None
|
||||
|
||||
|
||||
class WriteSubprocessPipeProto(protocols.BaseProtocol):
|
||||
|
||||
def __init__(self, proc, fd):
|
||||
self.proc = proc
|
||||
self.fd = fd
|
||||
self.pipe = None
|
||||
self.disconnected = False
|
||||
|
||||
def connection_made(self, transport):
|
||||
self.pipe = transport
|
||||
|
||||
def connection_lost(self, exc):
|
||||
self.disconnected = True
|
||||
self.proc._pipe_connection_lost(self.fd, exc)
|
||||
|
||||
def pause_writing(self):
|
||||
self.proc._protocol.pause_writing()
|
||||
|
||||
def resume_writing(self):
|
||||
self.proc._protocol.resume_writing()
|
||||
|
||||
|
||||
class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
|
||||
protocols.Protocol):
|
||||
|
||||
def data_received(self, data):
|
||||
self.proc._pipe_data_received(self.fd, data)
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,208 +0,0 @@
|
|||
import os, sys, unittest, getopt, time
|
||||
|
||||
use_resources = []
|
||||
|
||||
class ResourceDenied(Exception):
|
||||
"""Test skipped because it requested a disallowed resource.
|
||||
|
||||
This is raised when a test calls requires() for a resource that
|
||||
has not be enabled. Resources are defined by test modules.
|
||||
"""
|
||||
|
||||
def is_resource_enabled(resource):
|
||||
"""Test whether a resource is enabled.
|
||||
|
||||
If the caller's module is __main__ then automatically return True."""
|
||||
if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
|
||||
return True
|
||||
result = use_resources is not None and \
|
||||
(resource in use_resources or "*" in use_resources)
|
||||
if not result:
|
||||
_unavail[resource] = None
|
||||
return result
|
||||
|
||||
_unavail = {}
|
||||
def requires(resource, msg=None):
|
||||
"""Raise ResourceDenied if the specified resource is not available.
|
||||
|
||||
If the caller's module is __main__ then automatically return True."""
|
||||
# see if the caller's module is __main__ - if so, treat as if
|
||||
# the resource was set
|
||||
if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
|
||||
return
|
||||
if not is_resource_enabled(resource):
|
||||
if msg is None:
|
||||
msg = "Use of the `%s' resource not enabled" % resource
|
||||
raise ResourceDenied(msg)
|
||||
|
||||
def find_package_modules(package, mask):
|
||||
import fnmatch
|
||||
if (package.__loader__ is not None and
|
||||
hasattr(package.__loader__, '_files')):
|
||||
path = package.__name__.replace(".", os.path.sep)
|
||||
mask = os.path.join(path, mask)
|
||||
for fnm in package.__loader__._files.keys():
|
||||
if fnmatch.fnmatchcase(fnm, mask):
|
||||
yield os.path.splitext(fnm)[0].replace(os.path.sep, ".")
|
||||
else:
|
||||
path = package.__path__[0]
|
||||
for fnm in os.listdir(path):
|
||||
if fnmatch.fnmatchcase(fnm, mask):
|
||||
yield "%s.%s" % (package.__name__, os.path.splitext(fnm)[0])
|
||||
|
||||
def get_tests(package, mask, verbosity, exclude=()):
|
||||
"""Return a list of skipped test modules, and a list of test cases."""
|
||||
tests = []
|
||||
skipped = []
|
||||
for modname in find_package_modules(package, mask):
|
||||
if modname.split(".")[-1] in exclude:
|
||||
skipped.append(modname)
|
||||
if verbosity > 1:
|
||||
print("Skipped %s: excluded" % modname, file=sys.stderr)
|
||||
continue
|
||||
try:
|
||||
mod = __import__(modname, globals(), locals(), ['*'])
|
||||
except (ResourceDenied, unittest.SkipTest) as detail:
|
||||
skipped.append(modname)
|
||||
if verbosity > 1:
|
||||
print("Skipped %s: %s" % (modname, detail), file=sys.stderr)
|
||||
continue
|
||||
for name in dir(mod):
|
||||
if name.startswith("_"):
|
||||
continue
|
||||
o = getattr(mod, name)
|
||||
if type(o) is type(unittest.TestCase) and issubclass(o, unittest.TestCase):
|
||||
tests.append(o)
|
||||
return skipped, tests
|
||||
|
||||
def usage():
|
||||
print(__doc__)
|
||||
return 1
|
||||
|
||||
def test_with_refcounts(runner, verbosity, testcase):
|
||||
"""Run testcase several times, tracking reference counts."""
|
||||
import gc
|
||||
import ctypes
|
||||
ptc = ctypes._pointer_type_cache.copy()
|
||||
cfc = ctypes._c_functype_cache.copy()
|
||||
wfc = ctypes._win_functype_cache.copy()
|
||||
|
||||
# when searching for refcount leaks, we have to manually reset any
|
||||
# caches that ctypes has.
|
||||
def cleanup():
|
||||
ctypes._pointer_type_cache = ptc.copy()
|
||||
ctypes._c_functype_cache = cfc.copy()
|
||||
ctypes._win_functype_cache = wfc.copy()
|
||||
gc.collect()
|
||||
|
||||
test = unittest.makeSuite(testcase)
|
||||
for i in range(5):
|
||||
rc = sys.gettotalrefcount()
|
||||
runner.run(test)
|
||||
cleanup()
|
||||
COUNT = 5
|
||||
refcounts = [None] * COUNT
|
||||
for i in range(COUNT):
|
||||
rc = sys.gettotalrefcount()
|
||||
runner.run(test)
|
||||
cleanup()
|
||||
refcounts[i] = sys.gettotalrefcount() - rc
|
||||
if filter(None, refcounts):
|
||||
print("%s leaks:\n\t" % testcase, refcounts)
|
||||
elif verbosity:
|
||||
print("%s: ok." % testcase)
|
||||
|
||||
class TestRunner(unittest.TextTestRunner):
|
||||
def run(self, test, skipped):
|
||||
"Run the given test case or test suite."
|
||||
# Same as unittest.TextTestRunner.run, except that it reports
|
||||
# skipped tests.
|
||||
result = self._makeResult()
|
||||
startTime = time.time()
|
||||
test(result)
|
||||
stopTime = time.time()
|
||||
timeTaken = stopTime - startTime
|
||||
result.printErrors()
|
||||
self.stream.writeln(result.separator2)
|
||||
run = result.testsRun
|
||||
if _unavail: #skipped:
|
||||
requested = list(_unavail.keys())
|
||||
requested.sort()
|
||||
self.stream.writeln("Ran %d test%s in %.3fs (%s module%s skipped)" %
|
||||
(run, run != 1 and "s" or "", timeTaken,
|
||||
len(skipped),
|
||||
len(skipped) != 1 and "s" or ""))
|
||||
self.stream.writeln("Unavailable resources: %s" % ", ".join(requested))
|
||||
else:
|
||||
self.stream.writeln("Ran %d test%s in %.3fs" %
|
||||
(run, run != 1 and "s" or "", timeTaken))
|
||||
self.stream.writeln()
|
||||
if not result.wasSuccessful():
|
||||
self.stream.write("FAILED (")
|
||||
failed, errored = map(len, (result.failures, result.errors))
|
||||
if failed:
|
||||
self.stream.write("failures=%d" % failed)
|
||||
if errored:
|
||||
if failed: self.stream.write(", ")
|
||||
self.stream.write("errors=%d" % errored)
|
||||
self.stream.writeln(")")
|
||||
else:
|
||||
self.stream.writeln("OK")
|
||||
return result
|
||||
|
||||
|
||||
def main(*packages):
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "rqvu:x:")
|
||||
except getopt.error:
|
||||
return usage()
|
||||
|
||||
verbosity = 1
|
||||
search_leaks = False
|
||||
exclude = []
|
||||
for flag, value in opts:
|
||||
if flag == "-q":
|
||||
verbosity -= 1
|
||||
elif flag == "-v":
|
||||
verbosity += 1
|
||||
elif flag == "-r":
|
||||
try:
|
||||
sys.gettotalrefcount
|
||||
except AttributeError:
|
||||
print("-r flag requires Python debug build", file=sys.stderr)
|
||||
return -1
|
||||
search_leaks = True
|
||||
elif flag == "-u":
|
||||
use_resources.extend(value.split(","))
|
||||
elif flag == "-x":
|
||||
exclude.extend(value.split(","))
|
||||
|
||||
mask = "test_*.py"
|
||||
if args:
|
||||
mask = args[0]
|
||||
|
||||
for package in packages:
|
||||
run_tests(package, mask, verbosity, search_leaks, exclude)
|
||||
|
||||
|
||||
def run_tests(package, mask, verbosity, search_leaks, exclude):
|
||||
skipped, testcases = get_tests(package, mask, verbosity, exclude)
|
||||
runner = TestRunner(verbosity=verbosity)
|
||||
|
||||
suites = [unittest.makeSuite(o) for o in testcases]
|
||||
suite = unittest.TestSuite(suites)
|
||||
result = runner.run(suite, skipped)
|
||||
|
||||
if search_leaks:
|
||||
# hunt for refcount leaks
|
||||
runner = BasicTestRunner()
|
||||
for t in testcases:
|
||||
test_with_refcounts(runner, verbosity, t)
|
||||
|
||||
return bool(result.errors)
|
||||
|
||||
class BasicTestRunner:
|
||||
def run(self, test):
|
||||
result = unittest.TestResult()
|
||||
test(result)
|
||||
return result
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
"""Usage: runtests.py [-q] [-r] [-v] [-u resources] [mask]
|
||||
|
||||
Run all tests found in this directory, and print a summary of the results.
|
||||
Command line flags:
|
||||
-q quiet mode: don't print anything while the tests are running
|
||||
-r run tests repeatedly, look for refcount leaks
|
||||
-u<resources>
|
||||
Add resources to the lits of allowed resources. '*' allows all
|
||||
resources.
|
||||
-v verbose mode: print the test currently executed
|
||||
-x<test1[,test2...]>
|
||||
Exclude specified tests.
|
||||
mask mask to select filenames containing testcases, wildcards allowed
|
||||
"""
|
||||
import sys
|
||||
import ctypes.test
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(ctypes.test.main(ctypes.test))
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
from ctypes import *
|
||||
import unittest
|
||||
|
||||
class StringBufferTestCase(unittest.TestCase):
|
||||
|
||||
def test_buffer(self):
|
||||
b = create_string_buffer(32)
|
||||
self.assertEqual(len(b), 32)
|
||||
self.assertEqual(sizeof(b), 32 * sizeof(c_char))
|
||||
self.assertIs(type(b[0]), bytes)
|
||||
|
||||
b = create_string_buffer(b"abc")
|
||||
self.assertEqual(len(b), 4) # trailing nul char
|
||||
self.assertEqual(sizeof(b), 4 * sizeof(c_char))
|
||||
self.assertIs(type(b[0]), bytes)
|
||||
self.assertEqual(b[0], b"a")
|
||||
self.assertEqual(b[:], b"abc\0")
|
||||
self.assertEqual(b[::], b"abc\0")
|
||||
self.assertEqual(b[::-1], b"\0cba")
|
||||
self.assertEqual(b[::2], b"ac")
|
||||
self.assertEqual(b[::5], b"a")
|
||||
|
||||
def test_buffer_interface(self):
|
||||
self.assertEqual(len(bytearray(create_string_buffer(0))), 0)
|
||||
self.assertEqual(len(bytearray(create_string_buffer(1))), 1)
|
||||
|
||||
try:
|
||||
c_wchar
|
||||
except NameError:
|
||||
pass
|
||||
else:
|
||||
def test_unicode_buffer(self):
|
||||
b = create_unicode_buffer(32)
|
||||
self.assertEqual(len(b), 32)
|
||||
self.assertEqual(sizeof(b), 32 * sizeof(c_wchar))
|
||||
self.assertIs(type(b[0]), str)
|
||||
|
||||
b = create_unicode_buffer("abc")
|
||||
self.assertEqual(len(b), 4) # trailing nul char
|
||||
self.assertEqual(sizeof(b), 4 * sizeof(c_wchar))
|
||||
self.assertIs(type(b[0]), str)
|
||||
self.assertEqual(b[0], "a")
|
||||
self.assertEqual(b[:], "abc\0")
|
||||
self.assertEqual(b[::], "abc\0")
|
||||
self.assertEqual(b[::-1], "\0cba")
|
||||
self.assertEqual(b[::2], "ac")
|
||||
self.assertEqual(b[::5], "a")
|
||||
|
||||
def test_unicode_conversion(self):
|
||||
b = create_unicode_buffer("abc")
|
||||
self.assertEqual(len(b), 4) # trailing nul char
|
||||
self.assertEqual(sizeof(b), 4 * sizeof(c_wchar))
|
||||
self.assertIs(type(b[0]), str)
|
||||
self.assertEqual(b[0], "a")
|
||||
self.assertEqual(b[:], "abc\0")
|
||||
self.assertEqual(b[::], "abc\0")
|
||||
self.assertEqual(b[::-1], "\0cba")
|
||||
self.assertEqual(b[::2], "ac")
|
||||
self.assertEqual(b[::5], "a")
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
import sys
|
||||
from ctypes import *
|
||||
|
||||
##class HMODULE(Structure):
|
||||
## _fields_ = [("value", c_void_p)]
|
||||
|
||||
## def __repr__(self):
|
||||
## return "<HMODULE %s>" % self.value
|
||||
|
||||
##windll.kernel32.GetModuleHandleA.restype = HMODULE
|
||||
|
||||
##print windll.kernel32.GetModuleHandleA("python23.dll")
|
||||
##print hex(sys.dllhandle)
|
||||
|
||||
##def nonzero(handle):
|
||||
## return (GetLastError(), handle)
|
||||
|
||||
##windll.kernel32.GetModuleHandleA.errcheck = nonzero
|
||||
##print windll.kernel32.GetModuleHandleA("spam")
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
import unittest
|
||||
import sys
|
||||
from ctypes import *
|
||||
from ctypes.util import find_library
|
||||
from ctypes.test import is_resource_enabled
|
||||
|
||||
if sys.platform == "win32":
|
||||
lib_gl = find_library("OpenGL32")
|
||||
lib_glu = find_library("Glu32")
|
||||
lib_gle = None
|
||||
elif sys.platform == "darwin":
|
||||
lib_gl = lib_glu = find_library("OpenGL")
|
||||
lib_gle = None
|
||||
else:
|
||||
lib_gl = find_library("GL")
|
||||
lib_glu = find_library("GLU")
|
||||
lib_gle = find_library("gle")
|
||||
|
||||
## print, for debugging
|
||||
if is_resource_enabled("printing"):
|
||||
if lib_gl or lib_glu or lib_gle:
|
||||
print("OpenGL libraries:")
|
||||
for item in (("GL", lib_gl),
|
||||
("GLU", lib_glu),
|
||||
("gle", lib_gle)):
|
||||
print("\t", item)
|
||||
|
||||
|
||||
# On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode.
|
||||
class Test_OpenGL_libs(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.gl = self.glu = self.gle = None
|
||||
if lib_gl:
|
||||
self.gl = CDLL(lib_gl, mode=RTLD_GLOBAL)
|
||||
if lib_glu:
|
||||
self.glu = CDLL(lib_glu, RTLD_GLOBAL)
|
||||
if lib_gle:
|
||||
try:
|
||||
self.gle = CDLL(lib_gle)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
if lib_gl:
|
||||
def test_gl(self):
|
||||
if self.gl:
|
||||
self.gl.glClearIndex
|
||||
|
||||
if lib_glu:
|
||||
def test_glu(self):
|
||||
if self.glu:
|
||||
self.glu.gluBeginCurve
|
||||
|
||||
if lib_gle:
|
||||
def test_gle(self):
|
||||
if self.gle:
|
||||
self.gle.gleGetJoinStyle
|
||||
|
||||
##if os.name == "posix" and sys.platform != "darwin":
|
||||
|
||||
## # On platforms where the default shared library suffix is '.so',
|
||||
## # at least some libraries can be loaded as attributes of the cdll
|
||||
## # object, since ctypes now tries loading the lib again
|
||||
## # with '.so' appended of the first try fails.
|
||||
## #
|
||||
## # Won't work for libc, unfortunately. OTOH, it isn't
|
||||
## # needed for libc since this is already mapped into the current
|
||||
## # process (?)
|
||||
## #
|
||||
## # On MAC OSX, it won't work either, because dlopen() needs a full path,
|
||||
## # and the default suffix is either none or '.dylib'.
|
||||
|
||||
## class LoadLibs(unittest.TestCase):
|
||||
## def test_libm(self):
|
||||
## import math
|
||||
## libm = cdll.libm
|
||||
## sqrt = libm.sqrt
|
||||
## sqrt.argtypes = (c_double,)
|
||||
## sqrt.restype = c_double
|
||||
## self.assertEqual(sqrt(2), math.sqrt(2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
# superseded by test_numbers.py
|
||||
import unittest
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
from ctypes import *
|
||||
import sys, unittest
|
||||
import os
|
||||
from ctypes.util import find_library
|
||||
from ctypes.test import is_resource_enabled
|
||||
|
||||
libc_name = None
|
||||
if os.name == "nt":
|
||||
libc_name = find_library("c")
|
||||
elif os.name == "ce":
|
||||
libc_name = "coredll"
|
||||
elif sys.platform == "cygwin":
|
||||
libc_name = "cygwin1.dll"
|
||||
else:
|
||||
libc_name = find_library("c")
|
||||
|
||||
if is_resource_enabled("printing"):
|
||||
print("libc_name is", libc_name)
|
||||
|
||||
class LoaderTest(unittest.TestCase):
|
||||
|
||||
unknowndll = "xxrandomnamexx"
|
||||
|
||||
if libc_name is not None:
|
||||
def test_load(self):
|
||||
CDLL(libc_name)
|
||||
CDLL(os.path.basename(libc_name))
|
||||
self.assertRaises(OSError, CDLL, self.unknowndll)
|
||||
|
||||
if libc_name is not None and os.path.basename(libc_name) == "libc.so.6":
|
||||
def test_load_version(self):
|
||||
cdll.LoadLibrary("libc.so.6")
|
||||
# linux uses version, libc 9 should not exist
|
||||
self.assertRaises(OSError, cdll.LoadLibrary, "libc.so.9")
|
||||
self.assertRaises(OSError, cdll.LoadLibrary, self.unknowndll)
|
||||
|
||||
def test_find(self):
|
||||
for name in ("c", "m"):
|
||||
lib = find_library(name)
|
||||
if lib:
|
||||
cdll.LoadLibrary(lib)
|
||||
CDLL(lib)
|
||||
|
||||
if os.name in ("nt", "ce"):
|
||||
def test_load_library(self):
|
||||
self.assertIsNotNone(libc_name)
|
||||
if is_resource_enabled("printing"):
|
||||
print(find_library("kernel32"))
|
||||
print(find_library("user32"))
|
||||
|
||||
if os.name == "nt":
|
||||
windll.kernel32.GetModuleHandleW
|
||||
windll["kernel32"].GetModuleHandleW
|
||||
windll.LoadLibrary("kernel32").GetModuleHandleW
|
||||
WinDLL("kernel32").GetModuleHandleW
|
||||
elif os.name == "ce":
|
||||
windll.coredll.GetModuleHandleW
|
||||
windll["coredll"].GetModuleHandleW
|
||||
windll.LoadLibrary("coredll").GetModuleHandleW
|
||||
WinDLL("coredll").GetModuleHandleW
|
||||
|
||||
def test_load_ordinal_functions(self):
|
||||
import _ctypes_test
|
||||
dll = WinDLL(_ctypes_test.__file__)
|
||||
# We load the same function both via ordinal and name
|
||||
func_ord = dll[2]
|
||||
func_name = dll.GetString
|
||||
# addressof gets the address where the function pointer is stored
|
||||
a_ord = addressof(func_ord)
|
||||
a_name = addressof(func_name)
|
||||
f_ord_addr = c_void_p.from_address(a_ord).value
|
||||
f_name_addr = c_void_p.from_address(a_name).value
|
||||
self.assertEqual(hex(f_ord_addr), hex(f_name_addr))
|
||||
|
||||
self.assertRaises(AttributeError, dll.__getitem__, 1234)
|
||||
|
||||
if os.name == "nt":
|
||||
def test_1703286_A(self):
|
||||
from _ctypes import LoadLibrary, FreeLibrary
|
||||
# On winXP 64-bit, advapi32 loads at an address that does
|
||||
# NOT fit into a 32-bit integer. FreeLibrary must be able
|
||||
# to accept this address.
|
||||
|
||||
# These are tests for http://www.python.org/sf/1703286
|
||||
handle = LoadLibrary("advapi32")
|
||||
FreeLibrary(handle)
|
||||
|
||||
def test_1703286_B(self):
|
||||
# Since on winXP 64-bit advapi32 loads like described
|
||||
# above, the (arbitrarily selected) CloseEventLog function
|
||||
# also has a high address. 'call_function' should accept
|
||||
# addresses so large.
|
||||
from _ctypes import call_function
|
||||
advapi32 = windll.advapi32
|
||||
# Calling CloseEventLog with a NULL argument should fail,
|
||||
# but the call should not segfault or so.
|
||||
self.assertEqual(0, advapi32.CloseEventLog(None))
|
||||
windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
|
||||
windll.kernel32.GetProcAddress.restype = c_void_p
|
||||
proc = windll.kernel32.GetProcAddress(advapi32._handle, b"CloseEventLog")
|
||||
self.assertTrue(proc)
|
||||
# This is the real test: call the function via 'call_function'
|
||||
self.assertEqual(0, call_function(proc, (None,)))
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
import unittest
|
||||
import ctypes
|
||||
|
||||
try:
|
||||
ctypes.c_wchar
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
import _ctypes_test
|
||||
|
||||
class UnicodeTestCase(unittest.TestCase):
|
||||
def test_wcslen(self):
|
||||
dll = ctypes.CDLL(_ctypes_test.__file__)
|
||||
wcslen = dll.my_wcslen
|
||||
wcslen.argtypes = [ctypes.c_wchar_p]
|
||||
|
||||
self.assertEqual(wcslen("abc"), 3)
|
||||
self.assertEqual(wcslen("ab\u2070"), 3)
|
||||
self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4")
|
||||
|
||||
def test_buffers(self):
|
||||
buf = ctypes.create_unicode_buffer("abc")
|
||||
self.assertEqual(len(buf), 3+1)
|
||||
|
||||
buf = ctypes.create_unicode_buffer("ab\xe4\xf6\xfc")
|
||||
self.assertEqual(buf[:], "ab\xe4\xf6\xfc\0")
|
||||
self.assertEqual(buf[::], "ab\xe4\xf6\xfc\0")
|
||||
self.assertEqual(buf[::-1], '\x00\xfc\xf6\xe4ba')
|
||||
self.assertEqual(buf[::2], 'a\xe4\xfc')
|
||||
self.assertEqual(buf[6:5:-1], "")
|
||||
|
||||
func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p
|
||||
|
||||
class StringTestCase(UnicodeTestCase):
|
||||
def setUp(self):
|
||||
func.argtypes = [ctypes.c_char_p]
|
||||
func.restype = ctypes.c_char_p
|
||||
|
||||
def tearDown(self):
|
||||
func.argtypes = None
|
||||
func.restype = ctypes.c_int
|
||||
|
||||
def test_func(self):
|
||||
self.assertEqual(func(b"abc\xe4"), b"abc\xe4")
|
||||
|
||||
def test_buffers(self):
|
||||
buf = ctypes.create_string_buffer(b"abc")
|
||||
self.assertEqual(len(buf), 3+1)
|
||||
|
||||
buf = ctypes.create_string_buffer(b"ab\xe4\xf6\xfc")
|
||||
self.assertEqual(buf[:], b"ab\xe4\xf6\xfc\0")
|
||||
self.assertEqual(buf[::], b"ab\xe4\xf6\xfc\0")
|
||||
self.assertEqual(buf[::-1], b'\x00\xfc\xf6\xe4ba')
|
||||
self.assertEqual(buf[::2], b'a\xe4\xfc')
|
||||
self.assertEqual(buf[6:5:-1], b"")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
"""
|
||||
A testcase which accesses *values* in a dll.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
from ctypes import *
|
||||
|
||||
import _ctypes_test
|
||||
|
||||
class ValuesTestCase(unittest.TestCase):
|
||||
|
||||
def test_an_integer(self):
|
||||
# This test checks and changes an integer stored inside the
|
||||
# _ctypes_test dll/shared lib.
|
||||
ctdll = CDLL(_ctypes_test.__file__)
|
||||
an_integer = c_int.in_dll(ctdll, "an_integer")
|
||||
x = an_integer.value
|
||||
self.assertEqual(x, ctdll.get_an_integer())
|
||||
an_integer.value *= 2
|
||||
self.assertEqual(x*2, ctdll.get_an_integer())
|
||||
# To avoid test failures when this test is repeated several
|
||||
# times the original value must be restored
|
||||
an_integer.value = x
|
||||
self.assertEqual(x, ctdll.get_an_integer())
|
||||
|
||||
def test_undefined(self):
|
||||
ctdll = CDLL(_ctypes_test.__file__)
|
||||
self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol")
|
||||
|
||||
class Win_ValuesTestCase(unittest.TestCase):
|
||||
"""This test only works when python itself is a dll/shared library"""
|
||||
|
||||
def test_optimizeflag(self):
|
||||
# This test accesses the Py_OptimizeFlag intger, which is
|
||||
# exported by the Python dll.
|
||||
|
||||
# It's value is set depending on the -O and -OO flags:
|
||||
# if not given, it is 0 and __debug__ is 1.
|
||||
# If -O is given, the flag is 1, for -OO it is 2.
|
||||
# docstrings are also removed in the latter case.
|
||||
opt = c_int.in_dll(pydll, "Py_OptimizeFlag").value
|
||||
if __debug__:
|
||||
self.assertEqual(opt, 0)
|
||||
elif ValuesTestCase.__doc__ is not None:
|
||||
self.assertEqual(opt, 1)
|
||||
else:
|
||||
self.assertEqual(opt, 2)
|
||||
|
||||
def test_frozentable(self):
|
||||
# Python exports a PyImport_FrozenModules symbol. This is a
|
||||
# pointer to an array of struct _frozen entries. The end of the
|
||||
# array is marked by an entry containing a NULL name and zero
|
||||
# size.
|
||||
|
||||
# In standard Python, this table contains a __hello__
|
||||
# module, and a __phello__ package containing a spam
|
||||
# module.
|
||||
class struct_frozen(Structure):
|
||||
_fields_ = [("name", c_char_p),
|
||||
("code", POINTER(c_ubyte)),
|
||||
("size", c_int)]
|
||||
FrozenTable = POINTER(struct_frozen)
|
||||
|
||||
ft = FrozenTable.in_dll(pydll, "PyImport_FrozenModules")
|
||||
# ft is a pointer to the struct_frozen entries:
|
||||
items = []
|
||||
for entry in ft:
|
||||
# This is dangerous. We *can* iterate over a pointer, but
|
||||
# the loop will not terminate (maybe with an access
|
||||
# violation;-) because the pointer instance has no size.
|
||||
if entry.name is None:
|
||||
break
|
||||
items.append((entry.name, entry.size))
|
||||
import sys
|
||||
if sys.version_info[:2] >= (2, 3):
|
||||
expected = [("__hello__", 104), ("__phello__", -104), ("__phello__.spam", 104)]
|
||||
else:
|
||||
expected = [("__hello__", 100), ("__phello__", -100), ("__phello__.spam", 100)]
|
||||
self.assertEqual(items, expected)
|
||||
|
||||
from ctypes import _pointer_type_cache
|
||||
del _pointer_type_cache[struct_frozen]
|
||||
|
||||
def test_undefined(self):
|
||||
self.assertRaises(ValueError, c_int.in_dll, pydll, "Undefined_Symbol")
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
# Windows specific tests
|
||||
|
||||
from ctypes import *
|
||||
from ctypes.test import is_resource_enabled
|
||||
import unittest, sys
|
||||
from test import support
|
||||
|
||||
import _ctypes_test
|
||||
|
||||
if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int):
|
||||
# Only windows 32-bit has different calling conventions.
|
||||
|
||||
class WindowsTestCase(unittest.TestCase):
|
||||
def test_callconv_1(self):
|
||||
# Testing stdcall function
|
||||
|
||||
IsWindow = windll.user32.IsWindow
|
||||
# ValueError: Procedure probably called with not enough arguments (4 bytes missing)
|
||||
self.assertRaises(ValueError, IsWindow)
|
||||
|
||||
# This one should succeed...
|
||||
self.assertEqual(0, IsWindow(0))
|
||||
|
||||
# ValueError: Procedure probably called with too many arguments (8 bytes in excess)
|
||||
self.assertRaises(ValueError, IsWindow, 0, 0, 0)
|
||||
|
||||
def test_callconv_2(self):
|
||||
# Calling stdcall function as cdecl
|
||||
|
||||
IsWindow = cdll.user32.IsWindow
|
||||
|
||||
# ValueError: Procedure called with not enough arguments (4 bytes missing)
|
||||
# or wrong calling convention
|
||||
self.assertRaises(ValueError, IsWindow, None)
|
||||
|
||||
if sys.platform == "win32":
|
||||
class FunctionCallTestCase(unittest.TestCase):
|
||||
|
||||
if is_resource_enabled("SEH"):
|
||||
def test_SEH(self):
|
||||
# Call functions with invalid arguments, and make sure
|
||||
# that access violations are trapped and raise an
|
||||
# exception.
|
||||
self.assertRaises(OSError, windll.kernel32.GetModuleHandleA, 32)
|
||||
|
||||
def test_noargs(self):
|
||||
# This is a special case on win32 x64
|
||||
windll.user32.GetDesktopWindow()
|
||||
|
||||
class TestWintypes(unittest.TestCase):
|
||||
def test_HWND(self):
|
||||
from ctypes import wintypes
|
||||
self.assertEqual(sizeof(wintypes.HWND), sizeof(c_void_p))
|
||||
|
||||
def test_PARAM(self):
|
||||
from ctypes import wintypes
|
||||
self.assertEqual(sizeof(wintypes.WPARAM),
|
||||
sizeof(c_void_p))
|
||||
self.assertEqual(sizeof(wintypes.LPARAM),
|
||||
sizeof(c_void_p))
|
||||
|
||||
def test_COMError(self):
|
||||
from _ctypes import COMError
|
||||
if support.HAVE_DOCSTRINGS:
|
||||
self.assertEqual(COMError.__doc__,
|
||||
"Raised when a COM method call failed.")
|
||||
|
||||
ex = COMError(-1, "text", ("details",))
|
||||
self.assertEqual(ex.hresult, -1)
|
||||
self.assertEqual(ex.text, "text")
|
||||
self.assertEqual(ex.details, ("details",))
|
||||
|
||||
class TestWinError(unittest.TestCase):
|
||||
def test_winerror(self):
|
||||
# see Issue 16169
|
||||
import errno
|
||||
ERROR_INVALID_PARAMETER = 87
|
||||
msg = FormatError(ERROR_INVALID_PARAMETER).strip()
|
||||
args = (errno.EINVAL, msg, None, ERROR_INVALID_PARAMETER)
|
||||
|
||||
e = WinError(ERROR_INVALID_PARAMETER)
|
||||
self.assertEqual(e.args, args)
|
||||
self.assertEqual(e.errno, errno.EINVAL)
|
||||
self.assertEqual(e.winerror, ERROR_INVALID_PARAMETER)
|
||||
|
||||
windll.kernel32.SetLastError(ERROR_INVALID_PARAMETER)
|
||||
try:
|
||||
raise WinError()
|
||||
except OSError as exc:
|
||||
e = exc
|
||||
self.assertEqual(e.args, args)
|
||||
self.assertEqual(e.errno, errno.EINVAL)
|
||||
self.assertEqual(e.winerror, ERROR_INVALID_PARAMETER)
|
||||
|
||||
class Structures(unittest.TestCase):
|
||||
|
||||
def test_struct_by_value(self):
|
||||
class POINT(Structure):
|
||||
_fields_ = [("x", c_long),
|
||||
("y", c_long)]
|
||||
|
||||
class RECT(Structure):
|
||||
_fields_ = [("left", c_long),
|
||||
("top", c_long),
|
||||
("right", c_long),
|
||||
("bottom", c_long)]
|
||||
|
||||
dll = CDLL(_ctypes_test.__file__)
|
||||
|
||||
pt = POINT(10, 10)
|
||||
rect = RECT(0, 0, 20, 20)
|
||||
self.assertEqual(1, dll.PointInRect(byref(rect), pt))
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
"""Tests for distutils.file_util."""
|
||||
import unittest
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from distutils.file_util import move_file
|
||||
from distutils import log
|
||||
from distutils.tests import support
|
||||
from test.support import run_unittest
|
||||
|
||||
class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
|
||||
|
||||
def _log(self, msg, *args):
|
||||
if len(args) > 0:
|
||||
self._logs.append(msg % args)
|
||||
else:
|
||||
self._logs.append(msg)
|
||||
|
||||
def setUp(self):
|
||||
super(FileUtilTestCase, self).setUp()
|
||||
self._logs = []
|
||||
self.old_log = log.info
|
||||
log.info = self._log
|
||||
tmp_dir = self.mkdtemp()
|
||||
self.source = os.path.join(tmp_dir, 'f1')
|
||||
self.target = os.path.join(tmp_dir, 'f2')
|
||||
self.target_dir = os.path.join(tmp_dir, 'd1')
|
||||
|
||||
def tearDown(self):
|
||||
log.info = self.old_log
|
||||
super(FileUtilTestCase, self).tearDown()
|
||||
|
||||
def test_move_file_verbosity(self):
|
||||
f = open(self.source, 'w')
|
||||
try:
|
||||
f.write('some content')
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
move_file(self.source, self.target, verbose=0)
|
||||
wanted = []
|
||||
self.assertEqual(self._logs, wanted)
|
||||
|
||||
# back to original state
|
||||
move_file(self.target, self.source, verbose=0)
|
||||
|
||||
move_file(self.source, self.target, verbose=1)
|
||||
wanted = ['moving %s -> %s' % (self.source, self.target)]
|
||||
self.assertEqual(self._logs, wanted)
|
||||
|
||||
# back to original state
|
||||
move_file(self.target, self.source, verbose=0)
|
||||
|
||||
self._logs = []
|
||||
# now the target is a dir
|
||||
os.mkdir(self.target_dir)
|
||||
move_file(self.source, self.target_dir, verbose=1)
|
||||
wanted = ['moving %s -> %s' % (self.source, self.target_dir)]
|
||||
self.assertEqual(self._logs, wanted)
|
||||
|
||||
|
||||
def test_suite():
|
||||
return unittest.makeSuite(FileUtilTestCase)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_unittest(test_suite())
|
||||
Binary file not shown.
|
|
@ -1,246 +0,0 @@
|
|||
"""
|
||||
HyperParser
|
||||
===========
|
||||
This module defines the HyperParser class, which provides advanced parsing
|
||||
abilities for the ParenMatch and other extensions.
|
||||
The HyperParser uses PyParser. PyParser is intended mostly to give information
|
||||
on the proper indentation of code. HyperParser gives some information on the
|
||||
structure of code, used by extensions to help the user.
|
||||
"""
|
||||
|
||||
import string
|
||||
import keyword
|
||||
from idlelib import PyParse
|
||||
|
||||
class HyperParser:
|
||||
|
||||
def __init__(self, editwin, index):
|
||||
"""Initialize the HyperParser to analyze the surroundings of the given
|
||||
index.
|
||||
"""
|
||||
|
||||
self.editwin = editwin
|
||||
self.text = text = editwin.text
|
||||
|
||||
parser = PyParse.Parser(editwin.indentwidth, editwin.tabwidth)
|
||||
|
||||
def index2line(index):
|
||||
return int(float(index))
|
||||
lno = index2line(text.index(index))
|
||||
|
||||
if not editwin.context_use_ps1:
|
||||
for context in editwin.num_context_lines:
|
||||
startat = max(lno - context, 1)
|
||||
startatindex = repr(startat) + ".0"
|
||||
stopatindex = "%d.end" % lno
|
||||
# We add the newline because PyParse requires a newline at end.
|
||||
# We add a space so that index won't be at end of line, so that
|
||||
# its status will be the same as the char before it, if should.
|
||||
parser.set_str(text.get(startatindex, stopatindex)+' \n')
|
||||
bod = parser.find_good_parse_start(
|
||||
editwin._build_char_in_string_func(startatindex))
|
||||
if bod is not None or startat == 1:
|
||||
break
|
||||
parser.set_lo(bod or 0)
|
||||
else:
|
||||
r = text.tag_prevrange("console", index)
|
||||
if r:
|
||||
startatindex = r[1]
|
||||
else:
|
||||
startatindex = "1.0"
|
||||
stopatindex = "%d.end" % lno
|
||||
# We add the newline because PyParse requires a newline at end.
|
||||
# We add a space so that index won't be at end of line, so that
|
||||
# its status will be the same as the char before it, if should.
|
||||
parser.set_str(text.get(startatindex, stopatindex)+' \n')
|
||||
parser.set_lo(0)
|
||||
|
||||
# We want what the parser has, except for the last newline and space.
|
||||
self.rawtext = parser.str[:-2]
|
||||
# As far as I can see, parser.str preserves the statement we are in,
|
||||
# so that stopatindex can be used to synchronize the string with the
|
||||
# text box indices.
|
||||
self.stopatindex = stopatindex
|
||||
self.bracketing = parser.get_last_stmt_bracketing()
|
||||
# find which pairs of bracketing are openers. These always correspond
|
||||
# to a character of rawtext.
|
||||
self.isopener = [i>0 and self.bracketing[i][1] > self.bracketing[i-1][1]
|
||||
for i in range(len(self.bracketing))]
|
||||
|
||||
self.set_index(index)
|
||||
|
||||
def set_index(self, index):
|
||||
"""Set the index to which the functions relate. Note that it must be
|
||||
in the same statement.
|
||||
"""
|
||||
indexinrawtext = \
|
||||
len(self.rawtext) - len(self.text.get(index, self.stopatindex))
|
||||
if indexinrawtext < 0:
|
||||
raise ValueError("The index given is before the analyzed statement")
|
||||
self.indexinrawtext = indexinrawtext
|
||||
# find the rightmost bracket to which index belongs
|
||||
self.indexbracket = 0
|
||||
while self.indexbracket < len(self.bracketing)-1 and \
|
||||
self.bracketing[self.indexbracket+1][0] < self.indexinrawtext:
|
||||
self.indexbracket += 1
|
||||
if self.indexbracket < len(self.bracketing)-1 and \
|
||||
self.bracketing[self.indexbracket+1][0] == self.indexinrawtext and \
|
||||
not self.isopener[self.indexbracket+1]:
|
||||
self.indexbracket += 1
|
||||
|
||||
def is_in_string(self):
|
||||
"""Is the index given to the HyperParser is in a string?"""
|
||||
# The bracket to which we belong should be an opener.
|
||||
# If it's an opener, it has to have a character.
|
||||
return self.isopener[self.indexbracket] and \
|
||||
self.rawtext[self.bracketing[self.indexbracket][0]] in ('"', "'")
|
||||
|
||||
def is_in_code(self):
|
||||
"""Is the index given to the HyperParser is in a normal code?"""
|
||||
return not self.isopener[self.indexbracket] or \
|
||||
self.rawtext[self.bracketing[self.indexbracket][0]] not in \
|
||||
('#', '"', "'")
|
||||
|
||||
def get_surrounding_brackets(self, openers='([{', mustclose=False):
|
||||
"""If the index given to the HyperParser is surrounded by a bracket
|
||||
defined in openers (or at least has one before it), return the
|
||||
indices of the opening bracket and the closing bracket (or the
|
||||
end of line, whichever comes first).
|
||||
If it is not surrounded by brackets, or the end of line comes before
|
||||
the closing bracket and mustclose is True, returns None.
|
||||
"""
|
||||
bracketinglevel = self.bracketing[self.indexbracket][1]
|
||||
before = self.indexbracket
|
||||
while not self.isopener[before] or \
|
||||
self.rawtext[self.bracketing[before][0]] not in openers or \
|
||||
self.bracketing[before][1] > bracketinglevel:
|
||||
before -= 1
|
||||
if before < 0:
|
||||
return None
|
||||
bracketinglevel = min(bracketinglevel, self.bracketing[before][1])
|
||||
after = self.indexbracket + 1
|
||||
while after < len(self.bracketing) and \
|
||||
self.bracketing[after][1] >= bracketinglevel:
|
||||
after += 1
|
||||
|
||||
beforeindex = self.text.index("%s-%dc" %
|
||||
(self.stopatindex, len(self.rawtext)-self.bracketing[before][0]))
|
||||
if after >= len(self.bracketing) or \
|
||||
self.bracketing[after][0] > len(self.rawtext):
|
||||
if mustclose:
|
||||
return None
|
||||
afterindex = self.stopatindex
|
||||
else:
|
||||
# We are after a real char, so it is a ')' and we give the index
|
||||
# before it.
|
||||
afterindex = self.text.index("%s-%dc" %
|
||||
(self.stopatindex,
|
||||
len(self.rawtext)-(self.bracketing[after][0]-1)))
|
||||
|
||||
return beforeindex, afterindex
|
||||
|
||||
# This string includes all chars that may be in a white space
|
||||
_whitespace_chars = " \t\n\\"
|
||||
# This string includes all chars that may be in an identifier
|
||||
_id_chars = string.ascii_letters + string.digits + "_"
|
||||
# This string includes all chars that may be the first char of an identifier
|
||||
_id_first_chars = string.ascii_letters + "_"
|
||||
|
||||
# Given a string and pos, return the number of chars in the identifier
|
||||
# which ends at pos, or 0 if there is no such one. Saved words are not
|
||||
# identifiers.
|
||||
def _eat_identifier(self, str, limit, pos):
|
||||
i = pos
|
||||
while i > limit and str[i-1] in self._id_chars:
|
||||
i -= 1
|
||||
if i < pos and (str[i] not in self._id_first_chars or \
|
||||
keyword.iskeyword(str[i:pos])):
|
||||
i = pos
|
||||
return pos - i
|
||||
|
||||
def get_expression(self):
|
||||
"""Return a string with the Python expression which ends at the given
|
||||
index, which is empty if there is no real one.
|
||||
"""
|
||||
if not self.is_in_code():
|
||||
raise ValueError("get_expression should only be called if index "\
|
||||
"is inside a code.")
|
||||
|
||||
rawtext = self.rawtext
|
||||
bracketing = self.bracketing
|
||||
|
||||
brck_index = self.indexbracket
|
||||
brck_limit = bracketing[brck_index][0]
|
||||
pos = self.indexinrawtext
|
||||
|
||||
last_identifier_pos = pos
|
||||
postdot_phase = True
|
||||
|
||||
while 1:
|
||||
# Eat whitespaces, comments, and if postdot_phase is False - one dot
|
||||
while 1:
|
||||
if pos>brck_limit and rawtext[pos-1] in self._whitespace_chars:
|
||||
# Eat a whitespace
|
||||
pos -= 1
|
||||
elif not postdot_phase and \
|
||||
pos > brck_limit and rawtext[pos-1] == '.':
|
||||
# Eat a dot
|
||||
pos -= 1
|
||||
postdot_phase = True
|
||||
# The next line will fail if we are *inside* a comment, but we
|
||||
# shouldn't be.
|
||||
elif pos == brck_limit and brck_index > 0 and \
|
||||
rawtext[bracketing[brck_index-1][0]] == '#':
|
||||
# Eat a comment
|
||||
brck_index -= 2
|
||||
brck_limit = bracketing[brck_index][0]
|
||||
pos = bracketing[brck_index+1][0]
|
||||
else:
|
||||
# If we didn't eat anything, quit.
|
||||
break
|
||||
|
||||
if not postdot_phase:
|
||||
# We didn't find a dot, so the expression end at the last
|
||||
# identifier pos.
|
||||
break
|
||||
|
||||
ret = self._eat_identifier(rawtext, brck_limit, pos)
|
||||
if ret:
|
||||
# There is an identifier to eat
|
||||
pos = pos - ret
|
||||
last_identifier_pos = pos
|
||||
# Now, in order to continue the search, we must find a dot.
|
||||
postdot_phase = False
|
||||
# (the loop continues now)
|
||||
|
||||
elif pos == brck_limit:
|
||||
# We are at a bracketing limit. If it is a closing bracket,
|
||||
# eat the bracket, otherwise, stop the search.
|
||||
level = bracketing[brck_index][1]
|
||||
while brck_index > 0 and bracketing[brck_index-1][1] > level:
|
||||
brck_index -= 1
|
||||
if bracketing[brck_index][0] == brck_limit:
|
||||
# We were not at the end of a closing bracket
|
||||
break
|
||||
pos = bracketing[brck_index][0]
|
||||
brck_index -= 1
|
||||
brck_limit = bracketing[brck_index][0]
|
||||
last_identifier_pos = pos
|
||||
if rawtext[pos] in "([":
|
||||
# [] and () may be used after an identifier, so we
|
||||
# continue. postdot_phase is True, so we don't allow a dot.
|
||||
pass
|
||||
else:
|
||||
# We can't continue after other types of brackets
|
||||
if rawtext[pos] in "'\"":
|
||||
# Scan a string prefix
|
||||
while pos > 0 and rawtext[pos - 1] in "rRbBuU":
|
||||
pos -= 1
|
||||
last_identifier_pos = pos
|
||||
break
|
||||
|
||||
else:
|
||||
# We've found an operator or something.
|
||||
break
|
||||
|
||||
return rawtext[last_identifier_pos:self.indexinrawtext]
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
from tkinter import *
|
||||
|
||||
class MultiStatusBar(Frame):
|
||||
|
||||
def __init__(self, master=None, **kw):
|
||||
if master is None:
|
||||
master = Tk()
|
||||
Frame.__init__(self, master, **kw)
|
||||
self.labels = {}
|
||||
|
||||
def set_label(self, name, text='', side=LEFT):
|
||||
if name not in self.labels:
|
||||
label = Label(self, bd=1, relief=SUNKEN, anchor=W)
|
||||
label.pack(side=side)
|
||||
self.labels[name] = label
|
||||
else:
|
||||
label = self.labels[name]
|
||||
label.config(text=text)
|
||||
|
||||
def _test():
|
||||
b = Frame()
|
||||
c = Text(b)
|
||||
c.pack(side=TOP)
|
||||
a = MultiStatusBar(b)
|
||||
a.set_label("one", "hello")
|
||||
a.set_label("two", "world")
|
||||
a.pack(side=BOTTOM, fill=X)
|
||||
b.pack()
|
||||
b.mainloop()
|
||||
|
||||
if __name__ == '__main__':
|
||||
_test()
|
||||
|
|
@ -1,157 +0,0 @@
|
|||
'''Define SearchDialogBase used by Search, Replace, and Grep dialogs.'''
|
||||
from tkinter import *
|
||||
|
||||
class SearchDialogBase:
|
||||
'''Create most of a modal search dialog (make_frame, create_widgets).
|
||||
|
||||
The wide left column contains:
|
||||
1 or 2 text entry lines (create_entries, make_entry);
|
||||
a row of standard radiobuttons (create_option_buttons);
|
||||
a row of dialog specific radiobuttons (create_other_buttons).
|
||||
|
||||
The narrow right column contains command buttons
|
||||
(create_command_buttons, make_button).
|
||||
These are bound to functions that execute the command.
|
||||
|
||||
Except for command buttons, this base class is not limited to
|
||||
items common to all three subclasses. Rather, it is the Find dialog
|
||||
minus the "Find Next" command and its execution function.
|
||||
The other dialogs override methods to replace and add widgets.
|
||||
'''
|
||||
|
||||
title = "Search Dialog"
|
||||
icon = "Search"
|
||||
needwrapbutton = 1
|
||||
|
||||
def __init__(self, root, engine):
|
||||
self.root = root
|
||||
self.engine = engine
|
||||
self.top = None
|
||||
|
||||
def open(self, text, searchphrase=None):
|
||||
self.text = text
|
||||
if not self.top:
|
||||
self.create_widgets()
|
||||
else:
|
||||
self.top.deiconify()
|
||||
self.top.tkraise()
|
||||
if searchphrase:
|
||||
self.ent.delete(0,"end")
|
||||
self.ent.insert("end",searchphrase)
|
||||
self.ent.focus_set()
|
||||
self.ent.selection_range(0, "end")
|
||||
self.ent.icursor(0)
|
||||
self.top.grab_set()
|
||||
|
||||
def close(self, event=None):
|
||||
if self.top:
|
||||
self.top.grab_release()
|
||||
self.top.withdraw()
|
||||
|
||||
def create_widgets(self):
|
||||
top = Toplevel(self.root)
|
||||
top.bind("<Return>", self.default_command)
|
||||
top.bind("<Escape>", self.close)
|
||||
top.protocol("WM_DELETE_WINDOW", self.close)
|
||||
top.wm_title(self.title)
|
||||
top.wm_iconname(self.icon)
|
||||
self.top = top
|
||||
|
||||
self.row = 0
|
||||
self.top.grid_columnconfigure(0, pad=2, weight=0)
|
||||
self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100)
|
||||
|
||||
self.create_entries()
|
||||
self.create_option_buttons()
|
||||
self.create_other_buttons()
|
||||
return self.create_command_buttons()
|
||||
|
||||
def make_entry(self, label, var):
|
||||
l = Label(self.top, text=label)
|
||||
l.grid(row=self.row, column=0, sticky="nw")
|
||||
e = Entry(self.top, textvariable=var, exportselection=0)
|
||||
e.grid(row=self.row, column=1, sticky="nwe")
|
||||
self.row = self.row + 1
|
||||
return e
|
||||
|
||||
def make_frame(self,labeltext=None):
|
||||
if labeltext:
|
||||
l = Label(self.top, text=labeltext)
|
||||
l.grid(row=self.row, column=0, sticky="nw")
|
||||
f = Frame(self.top)
|
||||
f.grid(row=self.row, column=1, columnspan=1, sticky="nwe")
|
||||
self.row = self.row + 1
|
||||
return f
|
||||
|
||||
def make_button(self, label, command, isdef=0):
|
||||
b = Button(self.buttonframe,
|
||||
text=label, command=command,
|
||||
default=isdef and "active" or "normal")
|
||||
cols,rows=self.buttonframe.grid_size()
|
||||
b.grid(pady=1,row=rows,column=0,sticky="ew")
|
||||
self.buttonframe.grid(rowspan=rows+1)
|
||||
return b
|
||||
|
||||
def create_entries(self):
|
||||
self.ent = self.make_entry("Find:", self.engine.patvar)
|
||||
|
||||
def create_option_buttons(self):
|
||||
f = self.make_frame("Options")
|
||||
|
||||
btn = Checkbutton(f, anchor="w",
|
||||
variable=self.engine.revar,
|
||||
text="Regular expression")
|
||||
btn.pack(side="left", fill="both")
|
||||
if self.engine.isre():
|
||||
btn.select()
|
||||
|
||||
btn = Checkbutton(f, anchor="w",
|
||||
variable=self.engine.casevar,
|
||||
text="Match case")
|
||||
btn.pack(side="left", fill="both")
|
||||
if self.engine.iscase():
|
||||
btn.select()
|
||||
|
||||
btn = Checkbutton(f, anchor="w",
|
||||
variable=self.engine.wordvar,
|
||||
text="Whole word")
|
||||
btn.pack(side="left", fill="both")
|
||||
if self.engine.isword():
|
||||
btn.select()
|
||||
|
||||
if self.needwrapbutton:
|
||||
btn = Checkbutton(f, anchor="w",
|
||||
variable=self.engine.wrapvar,
|
||||
text="Wrap around")
|
||||
btn.pack(side="left", fill="both")
|
||||
if self.engine.iswrap():
|
||||
btn.select()
|
||||
|
||||
def create_other_buttons(self):
|
||||
f = self.make_frame("Direction")
|
||||
|
||||
#lbl = Label(f, text="Direction: ")
|
||||
#lbl.pack(side="left")
|
||||
|
||||
btn = Radiobutton(f, anchor="w",
|
||||
variable=self.engine.backvar, value=1,
|
||||
text="Up")
|
||||
btn.pack(side="left", fill="both")
|
||||
if self.engine.isback():
|
||||
btn.select()
|
||||
|
||||
btn = Radiobutton(f, anchor="w",
|
||||
variable=self.engine.backvar, value=0,
|
||||
text="Down")
|
||||
btn.pack(side="left", fill="both")
|
||||
if not self.engine.isback():
|
||||
btn.select()
|
||||
|
||||
def create_command_buttons(self):
|
||||
#
|
||||
# place button frame on the right
|
||||
f = self.buttonframe = Frame(self.top)
|
||||
f.grid(row=0,column=2,padx=2,pady=2,ipadx=2,ipady=2)
|
||||
|
||||
b = self.make_button("close", self.close)
|
||||
b.lower()
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
from tkinter import *
|
||||
|
||||
class WidgetRedirector:
|
||||
|
||||
"""Support for redirecting arbitrary widget subcommands.
|
||||
|
||||
Some Tk operations don't normally pass through Tkinter. For example, if a
|
||||
character is inserted into a Text widget by pressing a key, a default Tk
|
||||
binding to the widget's 'insert' operation is activated, and the Tk library
|
||||
processes the insert without calling back into Tkinter.
|
||||
|
||||
Although a binding to <Key> could be made via Tkinter, what we really want
|
||||
to do is to hook the Tk 'insert' operation itself.
|
||||
|
||||
When a widget is instantiated, a Tcl command is created whose name is the
|
||||
same as the pathname widget._w. This command is used to invoke the various
|
||||
widget operations, e.g. insert (for a Text widget). We are going to hook
|
||||
this command and provide a facility ('register') to intercept the widget
|
||||
operation.
|
||||
|
||||
In IDLE, the function being registered provides access to the top of a
|
||||
Percolator chain. At the bottom of the chain is a call to the original
|
||||
Tk widget operation.
|
||||
|
||||
"""
|
||||
def __init__(self, widget):
|
||||
self._operations = {}
|
||||
self.widget = widget # widget instance
|
||||
self.tk = tk = widget.tk # widget's root
|
||||
w = widget._w # widget's (full) Tk pathname
|
||||
self.orig = w + "_orig"
|
||||
# Rename the Tcl command within Tcl:
|
||||
tk.call("rename", w, self.orig)
|
||||
# Create a new Tcl command whose name is the widget's pathname, and
|
||||
# whose action is to dispatch on the operation passed to the widget:
|
||||
tk.createcommand(w, self.dispatch)
|
||||
|
||||
def __repr__(self):
|
||||
return "WidgetRedirector(%s<%s>)" % (self.widget.__class__.__name__,
|
||||
self.widget._w)
|
||||
|
||||
def close(self):
|
||||
for operation in list(self._operations):
|
||||
self.unregister(operation)
|
||||
widget = self.widget; del self.widget
|
||||
orig = self.orig; del self.orig
|
||||
tk = widget.tk
|
||||
w = widget._w
|
||||
tk.deletecommand(w)
|
||||
# restore the original widget Tcl command:
|
||||
tk.call("rename", orig, w)
|
||||
|
||||
def register(self, operation, function):
|
||||
self._operations[operation] = function
|
||||
setattr(self.widget, operation, function)
|
||||
return OriginalCommand(self, operation)
|
||||
|
||||
def unregister(self, operation):
|
||||
if operation in self._operations:
|
||||
function = self._operations[operation]
|
||||
del self._operations[operation]
|
||||
if hasattr(self.widget, operation):
|
||||
delattr(self.widget, operation)
|
||||
return function
|
||||
else:
|
||||
return None
|
||||
|
||||
def dispatch(self, operation, *args):
|
||||
'''Callback from Tcl which runs when the widget is referenced.
|
||||
|
||||
If an operation has been registered in self._operations, apply the
|
||||
associated function to the args passed into Tcl. Otherwise, pass the
|
||||
operation through to Tk via the original Tcl function.
|
||||
|
||||
Note that if a registered function is called, the operation is not
|
||||
passed through to Tk. Apply the function returned by self.register()
|
||||
to *args to accomplish that. For an example, see ColorDelegator.py.
|
||||
|
||||
'''
|
||||
m = self._operations.get(operation)
|
||||
try:
|
||||
if m:
|
||||
return m(*args)
|
||||
else:
|
||||
return self.tk.call((self.orig, operation) + args)
|
||||
except TclError:
|
||||
return ""
|
||||
|
||||
|
||||
class OriginalCommand:
|
||||
|
||||
def __init__(self, redir, operation):
|
||||
self.redir = redir
|
||||
self.operation = operation
|
||||
self.tk = redir.tk
|
||||
self.orig = redir.orig
|
||||
self.tk_call = self.tk.call
|
||||
self.orig_and_operation = (self.orig, self.operation)
|
||||
|
||||
def __repr__(self):
|
||||
return "OriginalCommand(%r, %r)" % (self.redir, self.operation)
|
||||
|
||||
def __call__(self, *args):
|
||||
return self.tk_call(self.orig_and_operation + args)
|
||||
|
||||
|
||||
def main():
|
||||
root = Tk()
|
||||
root.wm_protocol("WM_DELETE_WINDOW", root.quit)
|
||||
text = Text()
|
||||
text.pack()
|
||||
text.focus_set()
|
||||
redir = WidgetRedirector(text)
|
||||
global previous_tcl_fcn
|
||||
def my_insert(*args):
|
||||
print("insert", args)
|
||||
previous_tcl_fcn(*args)
|
||||
previous_tcl_fcn = redir.register("insert", my_insert)
|
||||
root.mainloop()
|
||||
redir.unregister("insert") # runs after first 'close window'
|
||||
redir.close()
|
||||
root.mainloop()
|
||||
root.destroy()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,21 +0,0 @@
|
|||
try:
|
||||
import idlelib.PyShell
|
||||
except ImportError:
|
||||
# IDLE is not installed, but maybe PyShell is on sys.path:
|
||||
try:
|
||||
from . import PyShell
|
||||
except ImportError:
|
||||
raise
|
||||
else:
|
||||
import os
|
||||
idledir = os.path.dirname(os.path.abspath(PyShell.__file__))
|
||||
if idledir != os.getcwd():
|
||||
# We're not in the IDLE directory, help the subprocess find run.py
|
||||
pypath = os.environ.get('PYTHONPATH', '')
|
||||
if pypath:
|
||||
os.environ['PYTHONPATH'] = pypath + ':' + idledir
|
||||
else:
|
||||
os.environ['PYTHONPATH'] = idledir
|
||||
PyShell.main()
|
||||
else:
|
||||
idlelib.PyShell.main()
|
||||
|
|
@ -1,110 +0,0 @@
|
|||
README FOR IDLE TESTS IN IDLELIB.IDLE_TEST
|
||||
|
||||
|
||||
1. Test Files
|
||||
|
||||
The idle directory, idlelib, has over 60 xyz.py files. The idle_test
|
||||
subdirectory should contain a test_xyy.py for each. (For test modules, make
|
||||
'xyz' lower case, and possibly shorten it.) Each file should start with the
|
||||
something like the following template, with the blanks after after '.' and 'as',
|
||||
and before and after '_' filled in.
|
||||
---
|
||||
import unittest
|
||||
from test.support import requires
|
||||
import idlelib. as
|
||||
|
||||
class _Test(unittest.TestCase):
|
||||
|
||||
def test_(self):
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2, exit=2)
|
||||
---
|
||||
Idle tests are run with unittest; do not use regrtest's test_main.
|
||||
|
||||
Once test_xyy is written, the following should go at the end of xyy.py,
|
||||
with xyz (lowercased) added after 'test_'.
|
||||
---
|
||||
if __name__ == "__main__":
|
||||
from test import support; support.use_resources = ['gui']
|
||||
import unittest
|
||||
unittest.main('idlelib.idle_test.test_', verbosity=2, exit=False)
|
||||
---
|
||||
|
||||
|
||||
2. Gui Tests
|
||||
|
||||
Gui tests need 'requires' and 'use_resources' from test.support
|
||||
(test.test_support in 2.7). A test is a gui test if it creates a Tk root or
|
||||
master object either directly or indirectly by instantiating a tkinter or
|
||||
idle class. For the benefit of buildbot machines that do not have a graphics
|
||||
screen, gui tests must be 'guarded' by "requires('gui')" in a setUp
|
||||
function or method. This will typically be setUpClass.
|
||||
|
||||
To avoid interfering with other gui tests, all gui objects must be destroyed
|
||||
and deleted by the end of the test. If a widget, such as a Tk root, is created
|
||||
in a setUpX function, destroy it in the corresponding tearDownX. For module
|
||||
and class attributes, also delete the widget.
|
||||
---
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
requires('gui')
|
||||
cls.root = tk.Tk()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.root.destroy()
|
||||
del cls.root
|
||||
---
|
||||
|
||||
Support.requires('gui') returns true if it is either called in a main module
|
||||
(which never happens on buildbots) or if use_resources contains 'gui'.
|
||||
Use_resources is set by test.regrtest but not by unittest. So when running
|
||||
tests in another module with unittest, we set it ourselves, as in the xyz.py
|
||||
template above.
|
||||
|
||||
Since non-gui tests always run, but gui tests only sometimes, tests of non-gui
|
||||
operations should best avoid needing a gui. Methods that make incidental use of
|
||||
tkinter (tk) variables and messageboxes can do this by using the mock classes in
|
||||
idle_test/mock_tk.py. There is also a mock text that will handle some uses of the
|
||||
tk Text widget.
|
||||
|
||||
|
||||
3. Running Tests
|
||||
|
||||
Assume that xyz.py and test_xyz.py end with the "if __name__" statements given
|
||||
above. In Idle, pressing F5 in an editor window with either loaded will run all
|
||||
tests in the test_xyz file with the version of Python running Idle. The test
|
||||
report and any tracebacks will appear in the Shell window. The options in these
|
||||
"if __name__" statements are appropriate for developers running (as opposed to
|
||||
importing) either of the files during development: verbosity=2 lists all test
|
||||
methods in the file; exit=False avoids a spurious sys.exit traceback that would
|
||||
otherwise occur when running in Idle. The following command lines also run
|
||||
all test methods, including gui tests, in test_xyz.py. (The exceptions are that
|
||||
idlelib and idlelib.idle start Idle and idlelib.PyShell should (issue 18330).)
|
||||
|
||||
python -m idlelib.xyz # With the capitalization of the xyz module
|
||||
python -m idlelib.idle_test.test_xyz
|
||||
|
||||
To run all idle_test/test_*.py tests, either interactively
|
||||
('>>>', with unittest imported) or from a command line, use one of the
|
||||
following. (Notes: unittest does not run gui tests; in 2.7, 'test ' (with the
|
||||
space) is 'test.regrtest '; where present, -v and -ugui can be omitted.)
|
||||
|
||||
>>> unittest.main('idlelib.idle_test', verbosity=2, exit=False)
|
||||
python -m unittest -v idlelib.idle_test
|
||||
python -m test -v -ugui test_idle
|
||||
python -m test.test_idle
|
||||
|
||||
The idle tests are 'discovered' by idlelib.idle_test.__init__.load_tests,
|
||||
which is also imported into test.test_idle. Normally, neither file should be
|
||||
changed when working on individual test modules. The third command runs runs
|
||||
unittest indirectly through regrtest. The same happens when the entire test
|
||||
suite is run with 'python -m test'. So that command must work for buildbots
|
||||
to stay green. Idle tests must not disturb the environment in a way that
|
||||
makes other tests fail (issue 18081).
|
||||
|
||||
To run an individual Testcase or test method, extend the dotted name given to
|
||||
unittest on the command line. (But gui tests will not this way.)
|
||||
|
||||
python -m unittest -v idlelib.idle_test.test_xyz.Test_case.test_meth
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
'''Run human tests of Idle's window, dialog, and popup widgets.
|
||||
|
||||
run(test): run *test*, a callable that causes a widget to be displayed.
|
||||
runall(): run all tests defined in this file.
|
||||
|
||||
Let X be a global name bound to a widget callable. End the module with
|
||||
|
||||
if __name__ == '__main__':
|
||||
<unittest, if there is one>
|
||||
from idlelib.idle_test.htest import run
|
||||
run(X)
|
||||
|
||||
The X object must have a .__name__ attribute and a 'parent' parameter.
|
||||
X will often be a widget class, but a callable instance with .__name__
|
||||
or a wrapper function also work. The name of wrapper functions, like
|
||||
'_Editor_Window', should start with '_'.
|
||||
|
||||
This file must contain a matching instance of the folling template,
|
||||
with X.__name__ prepended, as in '_Editor_window_spec ...'.
|
||||
|
||||
_spec = {
|
||||
'file': '',
|
||||
'kwds': {'title': ''},
|
||||
'msg': ""
|
||||
}
|
||||
|
||||
file (no .py): used in runall() to import the file and get X.
|
||||
kwds: passed to X (**kwds), after 'parent' is added, to initialize X.
|
||||
title: an example; used for some widgets, delete if not.
|
||||
msg: displayed in a master window. Hints as to how the user might
|
||||
test the widget. Close the window to skip or end the test.
|
||||
'''
|
||||
from importlib import import_module
|
||||
import tkinter as tk
|
||||
|
||||
|
||||
_Editor_window_spec = {
|
||||
'file': 'EditorWindow',
|
||||
'kwds': {},
|
||||
'msg': "Test editor functions of interest"
|
||||
}
|
||||
|
||||
_Help_dialog_spec = {
|
||||
'file': 'EditorWindow',
|
||||
'kwds': {},
|
||||
'msg': "If the help text displays, this works"
|
||||
}
|
||||
|
||||
AboutDialog_spec = {
|
||||
'file': 'aboutDialog',
|
||||
'kwds': {'title': 'About test'},
|
||||
'msg': "Try each button"
|
||||
}
|
||||
|
||||
|
||||
GetCfgSectionNameDialog_spec = {
|
||||
'file': 'configSectionNameDialog',
|
||||
'kwds': {'title':'Get Name',
|
||||
'message':'Enter something',
|
||||
'used_names': {'abc'},
|
||||
'_htest': True},
|
||||
'msg': "After the text entered with [Ok] is stripped, <nothing>, "
|
||||
"'abc', or more that 30 chars are errors.\n"
|
||||
"Close 'Get Name' with a valid entry (printed to Shell), [Cancel], or [X]",
|
||||
}
|
||||
|
||||
def run(test):
|
||||
"Display a widget with callable *test* using a _spec dict"
|
||||
root = tk.Tk()
|
||||
test_spec = globals()[test.__name__ + '_spec']
|
||||
test_kwds = test_spec['kwds']
|
||||
test_kwds['parent'] = root
|
||||
|
||||
def run_test():
|
||||
widget = test(**test_kwds)
|
||||
try:
|
||||
print(widget.result)
|
||||
except AttributeError:
|
||||
pass
|
||||
tk.Label(root, text=test_spec['msg'], justify='left').pack()
|
||||
tk.Button(root, text='Test ' + test.__name__, command=run_test).pack()
|
||||
root.mainloop()
|
||||
|
||||
def runall():
|
||||
"Run all tests. Quick and dirty version."
|
||||
for k, d in globals().items():
|
||||
if k.endswith('_spec'):
|
||||
mod = import_module('idlelib.' + d['file'])
|
||||
test = getattr(mod, k[:-5])
|
||||
run(test)
|
||||
|
||||
if __name__ == '__main__':
|
||||
runall()
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
'''Mock classes that imitate idlelib modules or classes.
|
||||
|
||||
Attributes and methods will be added as needed for tests.
|
||||
'''
|
||||
|
||||
from idlelib.idle_test.mock_tk import Text
|
||||
|
||||
class Editor:
|
||||
'''Minimally imitate EditorWindow.EditorWindow class.
|
||||
'''
|
||||
def __init__(self, flist=None, filename=None, key=None, root=None):
|
||||
self.text = Text()
|
||||
self.undo = UndoDelegator()
|
||||
|
||||
def get_selection_indices(self):
|
||||
first = self.text.index('1.0')
|
||||
last = self.text.index('end')
|
||||
return first, last
|
||||
|
||||
class UndoDelegator:
|
||||
'''Minimally imitate UndoDelegator,UndoDelegator class.
|
||||
'''
|
||||
# A real undo block is only needed for user interaction.
|
||||
def undo_block_start(*args):
|
||||
pass
|
||||
def undo_block_stop(*args):
|
||||
pass
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
import unittest
|
||||
import idlelib.PathBrowser as PathBrowser
|
||||
|
||||
class PathBrowserTest(unittest.TestCase):
|
||||
|
||||
def test_DirBrowserTreeItem(self):
|
||||
# Issue16226 - make sure that getting a sublist works
|
||||
d = PathBrowser.DirBrowserTreeItem('')
|
||||
d.GetSubList()
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2, exit=False)
|
||||
|
|
@ -1 +0,0 @@
|
|||
IDLE_VERSION = "3.4.1"
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
import string
|
||||
|
||||
def f():
|
||||
a = 0
|
||||
b = 1
|
||||
c = 2
|
||||
d = 3
|
||||
e = 4
|
||||
g()
|
||||
|
||||
def g():
|
||||
h()
|
||||
|
||||
def h():
|
||||
i()
|
||||
|
||||
def i():
|
||||
j()
|
||||
|
||||
def j():
|
||||
k()
|
||||
|
||||
def k():
|
||||
l()
|
||||
|
||||
l = lambda: test()
|
||||
|
||||
def test():
|
||||
string.capwords(1)
|
||||
|
||||
f()
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
"""The machinery of importlib: finders, loaders, hooks, etc."""
|
||||
|
||||
import _imp
|
||||
|
||||
from ._bootstrap import (SOURCE_SUFFIXES, DEBUG_BYTECODE_SUFFIXES,
|
||||
OPTIMIZED_BYTECODE_SUFFIXES, BYTECODE_SUFFIXES,
|
||||
EXTENSION_SUFFIXES)
|
||||
from ._bootstrap import ModuleSpec
|
||||
from ._bootstrap import BuiltinImporter
|
||||
from ._bootstrap import FrozenImporter
|
||||
from ._bootstrap import WindowsRegistryFinder
|
||||
from ._bootstrap import PathFinder
|
||||
from ._bootstrap import FileFinder
|
||||
from ._bootstrap import SourceFileLoader
|
||||
from ._bootstrap import SourcelessFileLoader
|
||||
from ._bootstrap import ExtensionFileLoader
|
||||
|
||||
|
||||
def all_suffixes():
|
||||
"""Returns a list of all recognized module suffixes for this process"""
|
||||
return SOURCE_SUFFIXES + BYTECODE_SUFFIXES + EXTENSION_SUFFIXES
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
r"""Command-line tool to validate and pretty-print JSON
|
||||
|
||||
Usage::
|
||||
|
||||
$ echo '{"json":"obj"}' | python -m json.tool
|
||||
{
|
||||
"json": "obj"
|
||||
}
|
||||
$ echo '{ 1.2:3.4}' | python -m json.tool
|
||||
Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
|
||||
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
|
||||
def main():
|
||||
if len(sys.argv) == 1:
|
||||
infile = sys.stdin
|
||||
outfile = sys.stdout
|
||||
elif len(sys.argv) == 2:
|
||||
infile = open(sys.argv[1], 'r')
|
||||
outfile = sys.stdout
|
||||
elif len(sys.argv) == 3:
|
||||
infile = open(sys.argv[1], 'r')
|
||||
outfile = open(sys.argv[2], 'w')
|
||||
else:
|
||||
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
|
||||
with infile:
|
||||
try:
|
||||
obj = json.load(infile)
|
||||
except ValueError as e:
|
||||
raise SystemExit(e)
|
||||
with outfile:
|
||||
json.dump(obj, outfile, sort_keys=True, indent=4)
|
||||
outfile.write('\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue