You can use :meth:`str.maketrans` to create a translation map from
character-to-character mappings in different formats.
- You can use the :func:`~string.maketrans` helper function in the :mod:`string`
- module to create a translation table. For string objects, set the *table*
- argument to ``None`` for translations that only delete characters:
-
.. note::
An even more flexible approach is to create a custom character mapping
result = integrate(0.0, 1.0, CALLBACK(func), 10)
diff = abs(result - 1./3.)
- self.assertTrue(diff < 0.01, "%s not less than 0.01" % diff)
+ self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)
################################################################
yield 'true'
elif o is False:
yield 'false'
- elif isinstance(o, (int, int)):
+ elif isinstance(o, int):
yield str(o)
elif isinstance(o, float):
yield _floatstr(o)
pyinteger_or_bool = StackObject(
name='int_or_bool',
- obtype=(int, int, bool),
+ obtype=(int, bool),
doc="A Python integer object (short or long), or "
"a Python bool.")
def isnum(x):
"""Test whether an object is an instance of a built-in numeric type."""
- for T in int, int, float, complex:
+ for T in int, float, complex:
if isinstance(x, T):
return 1
return 0
try:
tty = open("/dev/tty", "r")
- tty.close()
except IOError:
raise unittest.SkipTest("Unable to open /dev/tty")
+else:
+ # Skip if another process is in foreground
+ r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ")
+ tty.close()
+ rpgrp = struct.unpack("i", r)[0]
+ if rpgrp not in (os.getpgrp(), os.getsid(0)):
+ raise unittest.SkipTest("Neither the process group nor the session "
+ "are attached to /dev/tty")
+ del tty, r, rpgrp
try:
import pty
import gc
import signal
import array
-import copy
import socket
import random
import logging
#
try:
- from ctypes import Structure, Value, copy, c_int, c_double
+ from ctypes import Structure, c_int, c_double
except ImportError:
Structure = object
c_int = c_double = None
+try:
+ from ctypes import Value
+except ImportError:
+ Value = None
+
+try:
+ from ctypes import copy as ctypes_copy
+except ImportError:
+ ctypes_copy = None
+
#
# Creates a wrapper for a function which records the time it takes to finish
#
yield i*i
class IteratorProxy(BaseProxy):
- _exposed_ = ('next', '__next__')
+ _exposed_ = ('__next__',)
def __iter__(self):
return self
- def __next__(self):
- return self._callmethod('next')
def __next__(self):
return self._callmethod('__next__')
for i in range(len(arr)):
arr[i] *= 2
- @unittest.skipIf(c_int is None, "requires _ctypes")
+ @unittest.skipIf(Value is None, "requires ctypes.Value")
def test_sharedctypes(self, lock=False):
x = Value('i', 7, lock=lock)
y = Value(ctypes.c_double, 1.0/3.0, lock=lock)
self.assertAlmostEqual(arr[i], i*2)
self.assertEqual(string.value, latin('hellohello'))
+ @unittest.skipIf(Value is None, "requires ctypes.Value")
def test_synchronize(self):
self.test_sharedctypes(lock=True)
- @unittest.skipIf(c_int is None, "requires _ctypes")
+ @unittest.skipIf(ctypes_copy is None, "requires ctypes.copy")
def test_copy(self):
foo = _Foo(2, 5.0)
- bar = copy(foo)
+ bar = ctypes_copy(foo)
foo.x = 0
foo.y = 0
self.assertEqual(bar.x, 2)
self.assertEquals(pow(2, i), pow2)
if i != 30 : pow2 = pow2*2
- for othertype in int, int:
+ for othertype in (int,):
for i in list(range(-10, 0)) + list(range(1, 10)):
ii = type(i)
for j in range(1, 11):
jj = -othertype(j)
pow(ii, jj)
- for othertype in int, int, float:
+ for othertype in int, float:
for i in range(1, 100):
zero = type(0)
exp = -othertype(i/10.0)
# Python/pythonrun.c::PyErr_PrintEx() is tricky.
def test_exit(self):
- import subprocess
self.assertRaises(TypeError, sys.exit, 42, 42)
sys._clear_type_cache()
def test_ioencoding(self):
- import subprocess,os
env = dict(os.environ)
# Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
# Issue #7774: Ensure that sys.executable is an empty string if argv[0]
# has been set to an non existent program name and Python is unable to
# retrieve the real program name
- import subprocess
+
# For a normal installation, it should work without 'cwd'
# argument. For test runs in the build directory, see #7774.
python_dir = os.path.dirname(os.path.realpath(sys.executable))
self.assertEqual(self.returned_obj.geturl(), self.pathname)
def test_getcode(self):
- self.assertEqual(self.returned_obj.getcode(), None)
+ self.assertIsNone(self.returned_obj.getcode())
def test_iter(self):
# Test iterator
self.env.set('NO_PROXY', 'localhost')
proxies = urllib.request.getproxies_environment()
# getproxies_environment use lowered case truncated (no '_proxy') keys
- self.assertEquals('localhost', proxies['no'])
+ self.assertEqual('localhost', proxies['no'])
class urlopen_HttpTests(unittest.TestCase):
('a="b\\"c", d="e\\,f", g="h\\\\i"',
['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
for string, list in tests:
- self.assertEquals(urllib.request.parse_http_list(string), list)
+ self.assertEqual(urllib.request.parse_http_list(string), list)
def test_request_headers_dict():
h.file_open(req)
# XXXX remove OSError when bug fixed
except (urllib.error.URLError, OSError):
- self.assertTrue(not ftp)
+ self.assertFalse(ftp)
else:
- self.assertTrue(o.req is req)
+ self.assertIs(o.req, req)
self.assertEqual(req.type, "ftp")
self.assertEqual(req.type is "ftp", ftp)
# all 2xx are passed through
r = MockResponse(200, "OK", {}, "", url)
newr = h.http_response(req, r)
- self.assertTrue(r is newr)
- self.assertTrue(not hasattr(o, "proto")) # o.error not called
+ self.assertIs(r, newr)
+ self.assertFalse(hasattr(o, "proto")) # o.error not called
r = MockResponse(202, "Accepted", {}, "", url)
newr = h.http_response(req, r)
- self.assertTrue(r is newr)
- self.assertTrue(not hasattr(o, "proto")) # o.error not called
+ self.assertIs(r, newr)
+ self.assertFalse(hasattr(o, "proto")) # o.error not called
r = MockResponse(206, "Partial content", {}, "", url)
newr = h.http_response(req, r)
- self.assertTrue(r is newr)
- self.assertTrue(not hasattr(o, "proto")) # o.error not called
+ self.assertIs(r, newr)
+ self.assertFalse(hasattr(o, "proto")) # o.error not called
# anything else calls o.error (and MockOpener returns None, here)
r = MockResponse(502, "Bad gateway", {}, "", url)
- self.assertTrue(h.http_response(req, r) is None)
+ self.assertIsNone(h.http_response(req, r))
self.assertEqual(o.proto, "http") # o.error called
self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
req = Request("http://example.com/")
r = MockResponse(200, "OK", {}, "")
newreq = h.http_request(req)
- self.assertTrue(cj.ach_req is req is newreq)
- self.assertEquals(req.get_origin_req_host(), "example.com")
- self.assertTrue(not req.is_unverifiable())
+ self.assertIs(cj.ach_req, req)
+ self.assertIs(cj.ach_req, newreq)
+ self.assertEqual(req.get_origin_req_host(), "example.com")
+ self.assertFalse(req.is_unverifiable())
newr = h.http_response(req, r)
- self.assertTrue(cj.ec_req is req)
- self.assertTrue(cj.ec_r is r is newr)
+ self.assertIs(cj.ec_req, req)
+ self.assertIs(cj.ec_r, r)
+ self.assertIs(r, newr)
def test_redirect(self):
from_url = "http://example.com/a.html"
try:
self.assertEqual(o.req.get_method(), "GET")
except AttributeError:
- self.assertTrue(not o.req.has_data())
+ self.assertFalse(o.req.has_data())
# now it's a GET, there should not be headers regarding content
# (possibly dragged from before being a POST)
cp = urllib.request.HTTPCookieProcessor(cj)
o = build_test_opener(hh, hdeh, hrh, cp)
o.open("http://www.example.com/")
- self.assertTrue(not hh.req.has_header("Cookie"))
+ self.assertFalse(hh.req.has_header("Cookie"))
def test_proxy(self):
o = OpenerDirector()
self.opener_has_handler(o, MyOtherHTTPHandler)
def opener_has_handler(self, opener, handler_class):
- for h in opener.handlers:
- if h.__class__ == handler_class:
- break
- else:
- self.assertTrue(False)
+ self.assertTrue(any(h.__class__ == handler_class
+ for h in opener.handlers))
class RequestTests(unittest.TestCase):
self.assertEqual("GET", self.get.get_method())
def test_add_data(self):
- self.assertTrue(not self.get.has_data())
+ self.assertFalse(self.get.has_data())
self.assertEqual("GET", self.get.get_method())
self.get.add_data("spam")
self.assertTrue(self.get.has_data())
self.assertEqual("www.python.org", req.get_host())
def test_proxy(self):
- self.assertTrue(not self.get.has_proxy())
+ self.assertFalse(self.get.has_proxy())
self.get.set_proxy("www.perl.org", "http")
self.assertTrue(self.get.has_proxy())
self.assertEqual("www.python.org", self.get.get_origin_req_host())
auth_validated = False
# MSIE uses short_path in its validation, but Python's
- # urllib2 uses the full path, so we're going to see if
+ # urllib.request uses the full path, so we're going to see if
# either of them works here.
for path in [request_handler.path, request_handler.short_path]:
def do_GET(self):
body = self.send_head()
- if body:
- self.wfile.write(body)
+ while body:
+ done = self.wfile.write(body)
+ body = body[done:]
def do_POST(self):
content_length = self.headers["Content-Length"]
class TestUrlopen(unittest.TestCase):
- """Tests urllib2.urlopen using the network.
+ """Tests urllib.request.urlopen using the network.
These tests are not exhaustive. Assuming that testing using files does a
good job overall of some of the basic interface features. There are no
handler = self.start_server(responses)
data = self.urlopen("http://localhost:%s/" % handler.port)
- self.assertEquals(data, expected_response)
- self.assertEquals(handler.requests, ["/", "/somewhere_else"])
+ self.assertEqual(data, expected_response)
+ self.assertEqual(handler.requests, ["/", "/somewhere_else"])
def test_chunked(self):
expected_response = b"hello world"
response = [(200, [("Transfer-Encoding", "chunked")], chunked_start)]
handler = self.start_server(response)
data = self.urlopen("http://localhost:%s/" % handler.port)
- self.assertEquals(data, expected_response)
+ self.assertEqual(data, expected_response)
def test_404(self):
expected_response = b"Bad bad bad..."
else:
self.fail("404 should raise URLError")
- self.assertEquals(data, expected_response)
- self.assertEquals(handler.requests, ["/weeble"])
+ self.assertEqual(data, expected_response)
+ self.assertEqual(handler.requests, ["/weeble"])
def test_200(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = self.urlopen("http://localhost:%s/bizarre" % handler.port)
- self.assertEquals(data, expected_response)
- self.assertEquals(handler.requests, ["/bizarre"])
+ self.assertEqual(data, expected_response)
+ self.assertEqual(handler.requests, ["/bizarre"])
def test_200_with_parameters(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = self.urlopen("http://localhost:%s/bizarre" % handler.port,
b"get=with_feeling")
- self.assertEquals(data, expected_response)
- self.assertEquals(handler.requests, ["/bizarre", b"get=with_feeling"])
+ self.assertEqual(data, expected_response)
+ self.assertEqual(handler.requests, ["/bizarre", b"get=with_feeling"])
def test_sending_headers(self):
handler = self.start_server()
urllib.request.urlopen,
"http://sadflkjsasf.i.nvali.d./")
+ def test_iteration(self):
+ expected_response = b"pycon 2008..."
+ handler = self.start_server([(200, [], expected_response)])
+ data = urllib.request.urlopen("http://localhost:%s" % handler.port)
+ for line in data:
+ self.assertEqual(line, expected_response)
+
+ def test_line_iteration(self):
+ lines = [b"We\n", b"got\n", b"here\n", b"verylong " * 8192 + b"\n"]
+ expected_response = b"".join(lines)
+ handler = self.start_server([(200, [], expected_response)])
+ data = urllib.request.urlopen("http://localhost:%s" % handler.port)
+ for index, line in enumerate(data):
+ self.assertEqual(line, lines[index],
+ "Fetched line number %s doesn't match expected:\n"
+ " Expected length was %s, got %s" %
+ (index, len(lines[index]), len(line)))
+ self.assertEqual(index + 1, len(lines))
+
def test_main():
support.run_unittest(ProxyAuthTests, TestUrlopen)
Tests
-----
+- Issue #7564: Skip test_ioctl if another process is attached to /dev/tty.
+
- Issue #8857: Provide a test case for socket.getaddrinfo.
- Issue #8433: Fix test_curses failure with newer versions of ncurses.
Files found here
----------------
-ACKS Acknowledgements
-AIX-NOTES Notes for building Python on AIX
-build.sh Script to build and test latest Python from the repository
-cheatsheet Quick summary of Python by Ken Manheimer
-developers.txt A history of who got developer permissions, and why
-gdbinit Handy stuff to put in your .gdbinit file, if you use gdb
-HISTORY News from previous releases -- oldest last
-indent.pro GNU indent profile approximating my C style
-maintainers.txt A list of maintainers for library modules
-NEWS News for this release (for some meaning of "this")
-NEWS.help How to edit NEWS
-Porting Mini-FAQ on porting to new platforms
-PURIFY.README Information for Purify users
-pymemcompat.h Memory interface compatibility file.
-python.man UNIX man page for the python interpreter
-python-mode.el Emacs mode for editing Python programs
-python.pc.in Package configuration info template for pkg-config
-python-wing.wpr Wing IDE project file
-README The file you're reading now
-README.coverity Information about running Coverity's Prevent on Python
-README.klocwork Information about running Klocwork's K7 on Python
-README.OpenBSD Help for building problems on OpenBSD
-README.valgrind Information for Valgrind users, see valgrind-python.supp
-RFD Request For Discussion about a Python newsgroup
-RPM (Old) tools to build RPMs
-setuid-prog.c C helper program for set-uid Python scripts
-SpecialBuilds.txt Describes extra symbols you can set for debug builds
-TextMate A TextMate bundle for Python development
-valgrind-python.supp Valgrind suppression file, see README.valgrind
-vgrindefs Python configuration for vgrind (a generic pretty printer)
-Vim Python development utilities for the Vim editor
\ No newline at end of file
+ACKS Acknowledgements
+AIX-NOTES Notes for building Python on AIX
+build.sh Script to build and test latest Python from the repository
+cheatsheet Quick summary of Python by Ken Manheimer
+developers.txt A history of who got developer permissions, and why
+gdbinit Handy stuff to put in your .gdbinit file, if you use gdb
+HISTORY News from previous releases -- oldest last
+indent.pro GNU indent profile approximating my C style
+maintainers.rst A list of maintainers for library modules
+NEWS News for this release (for some meaning of "this")
+NEWS.help How to edit NEWS
+Porting Mini-FAQ on porting to new platforms
+PURIFY.README Information for Purify users
+pymemcompat.h Memory interface compatibility file.
+python-config.in Python script template for python-config
+python.man UNIX man page for the python interpreter
+python-mode.el Emacs mode for editing Python programs
+python.pc.in Package configuration info template for pkg-config
+python-wing.wpr Wing IDE project file
+README The file you're reading now
+README.coverity Information about running Coverity's Prevent on Python
+README.klocwork Information about running Klocwork's K7 on Python
+README.OpenBSD Help for building problems on OpenBSD
+README.valgrind Information for Valgrind users, see valgrind-python.supp
+RFD Request For Discussion about a Python newsgroup
+RPM (Old) tools to build RPMs
+setuid-prog.c C helper program for set-uid Python scripts
+SpecialBuilds.txt Describes extra symbols you can set for debug builds
+TextMate A TextMate bundle for Python development
+valgrind-python.supp Valgrind suppression file, see README.valgrind
+vgrindefs Python configuration for vgrind (a generic pretty printer)
+Vim Python development utilities for the Vim editor
a given module, then questionable changes should go to python-dev, while
any other issues can and should be decided by any committer.
+Unless a name is followed by a '*', you should never assign an issue to
+that person, only make them nosy. Names followed by a '*' may be assigned
+issues involving the module or topic for which the name has a '*'.
+
The Platform and Interest Area tables list broader fields in which various
people have expertise. These people can also be contacted for help,
opinions, and decisions when issues involve their areas.
tracker id. They are of course free to remove that inactive mark at
any time.
-Committers should update this table as their areas of expertise widen.
-New topics may be added to the third table at will.
+Committers should update these tables as their areas of expertise widen.
+New topics may be added to the Interest Area table at will.
The existence of this list is not meant to indicate that these people
*must* be contacted for decisions; it is, rather, a resource to be used
decimal facundobatista, rhettinger, mark.dickinson
difflib tim_one
dis
-distutils tarek
+distutils tarek*, eric.araujo*
doctest tim_one (inactive)
dummy_threading brett.cannon
-email barry, r.david.murray
+email barry, r.david.murray*
encodings lemburg, loewis
errno
exceptions
os loewis
ossaudiodev
parser
-pdb georg.brandl
+pdb georg.brandl*
pickle alexandre.vassalotti, pitrou
pickletools alexandre.vassalotti
pipes
poplib
posix
pprint fdrake
-pstats
+profile georg.brandl
+pstats georg.brandl
pty
pwd
py_compile
queue rhettinger
quopri
random rhettinger
-re effbot (inactive), pitrou
+re effbot (inactive), pitrou, ezio.melotti
readline
reprlib
resource
sqlite3 ghaering
ssl janssen, pitrou, giampaolo.rodola
stat
-string
+string georg.brandl*
stringprep
struct mark.dickinson
subprocess astrand (inactive)
tabnanny tim_one
tarfile lars.gustaebel
telnetlib
-tempfile
+tempfile georg.brandl
termios
test
-textwrap
+textwrap georg.brandl
threading pitrou
time alexander.belopolsky
-timeit
+timeit georg.brandl
tkinter gpolo
token georg.brandl
tokenize
trace alexander.belopolsky
-traceback georg.brandl
+traceback georg.brandl*
tty
turtle gregorlingl
types
wave
weakref fdrake, pitrou
webbrowser georg.brandl
-winreg
+winreg brian.curtin
winsound effbot (inactive)
wsgiref pje
xdrlib
-xml loewis
+xml.dom
+xml.dom.minidom
+xml.dom.pulldom
xml.etree effbot (inactive)
+xml.parsers.expat
+xml.sax
+xml.sax.handler
+xml.sax.saxutils
+xml.sax.xmlreader
xmlrpc loewis
-zipfile
+zipfile alanmcintyre
zipimport
zlib
================== ===========
Tool Maintainers
------------------ -----------
pybench lemburg
+================== ===========
================== ===========
ast/compiler ncoghlan, benjamin.peterson, brett.cannon, georg.brandl
autoconf/makefiles
bsd
+bug tracker ezio.melotti
buildbots
bytecode pitrou
data formats mark.dickinson, georg.brandl
release management tarek, lemburg, benjamin.peterson, barry, loewis,
gvanrossum, anthonybaxter
str.format eric.smith
+testing michael.foord, pitrou, giampaolo.rodola
+threads pitrou
time and dates lemburg
-testing michael.foord, pitrou
-threads
-tracker
unicode lemburg, ezio.melotti, haypo
version control
================== ===========
#!/usr/bin/env python
-from lib2to3.main import main
import sys
-import os
+from lib2to3.main import main
sys.exit(main("lib2to3.fixes"))