summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/test_asynchat.py46
-rw-r--r--Lib/test/test_dict.py8
-rw-r--r--Lib/test/test_generators.py20
-rw-r--r--Lib/test/test_rational.py40
-rw-r--r--Lib/test/test_resource.py10
-rw-r--r--Lib/test/test_telnetlib.py11
-rw-r--r--Lib/test/test_urllibnet.py40
-rw-r--r--Lib/test/test_xmlrpc.py42
-rw-r--r--Lib/test/test_zipfile.py1
9 files changed, 146 insertions, 72 deletions
diff --git a/Lib/test/test_asynchat.py b/Lib/test/test_asynchat.py
index 83b0972..2912057 100644
--- a/Lib/test/test_asynchat.py
+++ b/Lib/test/test_asynchat.py
@@ -15,12 +15,17 @@ class echo_server(threading.Thread):
# client each send
chunk_size = 1
+ def __init__(self, event):
+ threading.Thread.__init__(self)
+ self.event = event
+
def run(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
global PORT
PORT = test_support.bind_port(sock, HOST, PORT)
sock.listen(1)
+ self.event.set()
conn, client = sock.accept()
self.buffer = b""
# collect data until quit message is seen
@@ -74,6 +79,16 @@ class echo_client(asynchat.async_chat):
self.buffer = b""
+def start_echo_server():
+ event = threading.Event()
+ s = echo_server(event)
+ s.start()
+ event.wait()
+ event.clear()
+ time.sleep(0.01) # Give server time to start accepting.
+ return s, event
+
+
class TestAsynchat(unittest.TestCase):
usepoll = False
@@ -84,10 +99,13 @@ class TestAsynchat(unittest.TestCase):
pass
def line_terminator_check(self, term, server_chunk):
- s = echo_server()
+ event = threading.Event()
+ s = echo_server(event)
s.chunk_size = server_chunk
s.start()
- time.sleep(0.5) # Give server time to initialize
+ event.wait()
+ event.clear()
+ time.sleep(0.01) # Give server time to start accepting.
c = echo_client(term)
c.push(b"hello ")
c.push(bytes("world%s" % term, "ascii"))
@@ -119,9 +137,7 @@ class TestAsynchat(unittest.TestCase):
def numeric_terminator_check(self, termlen):
# Try reading a fixed number of bytes
- s = echo_server()
- s.start()
- time.sleep(0.5) # Give server time to initialize
+ s, event = start_echo_server()
c = echo_client(termlen)
data = b"hello world, I'm not dead yet!\n"
c.push(data)
@@ -141,9 +157,7 @@ class TestAsynchat(unittest.TestCase):
def test_none_terminator(self):
# Try reading a fixed number of bytes
- s = echo_server()
- s.start()
- time.sleep(0.5) # Give server time to initialize
+ s, event = start_echo_server()
c = echo_client(None)
data = b"hello world, I'm not dead yet!\n"
c.push(data)
@@ -155,9 +169,7 @@ class TestAsynchat(unittest.TestCase):
self.assertEqual(c.buffer, data)
def test_simple_producer(self):
- s = echo_server()
- s.start()
- time.sleep(0.5) # Give server time to initialize
+ s, event = start_echo_server()
c = echo_client(b'\n')
data = b"hello world\nI'm not dead yet!\n"
p = asynchat.simple_producer(data+SERVER_QUIT, buffer_size=8)
@@ -168,9 +180,7 @@ class TestAsynchat(unittest.TestCase):
self.assertEqual(c.contents, [b"hello world", b"I'm not dead yet!"])
def test_string_producer(self):
- s = echo_server()
- s.start()
- time.sleep(0.5) # Give server time to initialize
+ s, event = start_echo_server()
c = echo_client(b'\n')
data = b"hello world\nI'm not dead yet!\n"
c.push_with_producer(data+SERVER_QUIT)
@@ -181,9 +191,7 @@ class TestAsynchat(unittest.TestCase):
def test_empty_line(self):
# checks that empty lines are handled correctly
- s = echo_server()
- s.start()
- time.sleep(0.5) # Give server time to initialize
+ s, event = start_echo_server()
c = echo_client(b'\n')
c.push(b"hello world\n\nI'm not dead yet!\n")
c.push(SERVER_QUIT)
@@ -194,9 +202,7 @@ class TestAsynchat(unittest.TestCase):
[b"hello world", b"", b"I'm not dead yet!"])
def test_close_when_done(self):
- s = echo_server()
- s.start()
- time.sleep(0.5) # Give server time to initialize
+ s, event = start_echo_server()
c = echo_client(b'\n')
c.push(b"hello world\nI'm not dead yet!\n")
c.push(SERVER_QUIT)
diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 53e6446..6a0b3c1 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -191,14 +191,6 @@ class DictTest(unittest.TestCase):
self.assertRaises(ValueError, {}.update, [(1, 2, 3)])
- # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses
- class KeyUpperDict(dict):
- def __getitem__(self, key):
- return key.upper()
- d.clear()
- d.update(KeyUpperDict.fromkeys('abc'))
- self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'})
-
def test_fromkeys(self):
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
d = {}
diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py
index 892535d..04f1359 100644
--- a/Lib/test/test_generators.py
+++ b/Lib/test/test_generators.py
@@ -382,7 +382,7 @@ From the Iterators list, about the types of these things.
>>> type(i)
<type 'generator'>
>>> [s for s in dir(i) if not s.startswith('_')]
-['close', 'gi_frame', 'gi_running', 'send', 'throw']
+['close', 'gi_code', 'gi_frame', 'gi_running', 'send', 'throw']
>>> print(i.__next__.__doc__)
x.__next__() <==> next(x)
>>> iter(i) is i
@@ -899,6 +899,24 @@ This one caused a crash (see SF bug 567538):
>>> print(next(g))
Traceback (most recent call last):
StopIteration
+
+
+Test the gi_code attribute
+
+>>> def f():
+... yield 5
+...
+>>> g = f()
+>>> g.gi_code is f.__code__
+True
+>>> next(g)
+5
+>>> next(g)
+Traceback (most recent call last):
+StopIteration
+>>> g.gi_code is f.__code__
+True
+
"""
# conjoin is a simple backtracking generator, named in honor of Icon's
diff --git a/Lib/test/test_rational.py b/Lib/test/test_rational.py
index 729527f..284a42a 100644
--- a/Lib/test/test_rational.py
+++ b/Lib/test/test_rational.py
@@ -9,10 +9,28 @@ import unittest
from copy import copy, deepcopy
from pickle import dumps, loads
R = rational.Rational
+gcd = rational.gcd
+
+
+class GcdTest(unittest.TestCase):
+
+ def testMisc(self):
+ self.assertEquals(0, gcd(0, 0))
+ self.assertEquals(1, gcd(1, 0))
+ self.assertEquals(-1, gcd(-1, 0))
+ self.assertEquals(1, gcd(0, 1))
+ self.assertEquals(-1, gcd(0, -1))
+ self.assertEquals(1, gcd(7, 1))
+ self.assertEquals(-1, gcd(7, -1))
+ self.assertEquals(1, gcd(-23, 15))
+ self.assertEquals(12, gcd(120, 84))
+ self.assertEquals(-12, gcd(84, -120))
+
def _components(r):
return (r.numerator, r.denominator)
+
class RationalTest(unittest.TestCase):
def assertTypedEquals(self, expected, actual):
@@ -57,6 +75,8 @@ class RationalTest(unittest.TestCase):
self.assertEquals((-3, 2), _components(R("-3/2 ")))
self.assertEquals((3, 2), _components(R(" 03/02 \n ")))
self.assertEquals((3, 2), _components(R(" 03/02 \n ")))
+ self.assertEquals((16, 5), _components(R(" 3.2 ")))
+ self.assertEquals((-16, 5), _components(R(" -3.2 ")))
self.assertRaisesMessage(
ZeroDivisionError, "Rational(3, 0)",
@@ -76,9 +96,21 @@ class RationalTest(unittest.TestCase):
ValueError, "Invalid literal for Rational: + 3/2",
R, "+ 3/2")
self.assertRaisesMessage(
- # Only parse fractions, not decimals.
- ValueError, "Invalid literal for Rational: 3.2",
- R, "3.2")
+ # Avoid treating '.' as a regex special character.
+ ValueError, "Invalid literal for Rational: 3a2",
+ R, "3a2")
+ self.assertRaisesMessage(
+ # Only parse ordinary decimals, not scientific form.
+ ValueError, "Invalid literal for Rational: 3.2e4",
+ R, "3.2e4")
+ self.assertRaisesMessage(
+ # Don't accept combinations of decimals and rationals.
+ ValueError, "Invalid literal for Rational: 3/7.2",
+ R, "3/7.2")
+ self.assertRaisesMessage(
+ # Don't accept combinations of decimals and rationals.
+ ValueError, "Invalid literal for Rational: 3.2/7",
+ R, "3.2/7")
def testImmutable(self):
r = R(7, 3)
@@ -370,7 +402,7 @@ class RationalTest(unittest.TestCase):
self.assertEqual(id(r), id(deepcopy(r)))
def test_main():
- run_unittest(RationalTest)
+ run_unittest(RationalTest, GcdTest)
if __name__ == '__main__':
test_main()
diff --git a/Lib/test/test_resource.py b/Lib/test/test_resource.py
index 1216560..987c8d7 100644
--- a/Lib/test/test_resource.py
+++ b/Lib/test/test_resource.py
@@ -15,7 +15,6 @@ class ResourceTest(unittest.TestCase):
self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42)
def test_fsize_ismax(self):
-
try:
(cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE)
except AttributeError:
@@ -54,6 +53,13 @@ class ResourceTest(unittest.TestCase):
try:
f.write(b"Y")
f.flush()
+ # On some systems (e.g., Ubuntu on hppa) the flush()
+ # doesn't always cause the exception, but the close()
+ # does eventually. Try closing several times in
+ # an attempt to ensure the file is really synced and
+ # the exception raised.
+ for i in range(5):
+ f.close()
except IOError:
if not limit_set:
raise
@@ -63,10 +69,10 @@ class ResourceTest(unittest.TestCase):
resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
finally:
f.close()
- os.unlink(test_support.TESTFN)
finally:
if limit_set:
resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
+ test_support.unlink(test_support.TESTFN)
def test_fsize_toobig(self):
# Be sure that setrlimit is checking for really large values
diff --git a/Lib/test/test_telnetlib.py b/Lib/test/test_telnetlib.py
index c48de04..3a53ad9 100644
--- a/Lib/test/test_telnetlib.py
+++ b/Lib/test/test_telnetlib.py
@@ -7,13 +7,13 @@ from unittest import TestCase
from test import test_support
-def server(evt, ready):
+def server(evt):
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.settimeout(3)
serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serv.bind(("", 9091))
serv.listen(5)
- ready.set()
+ evt.set()
try:
conn, addr = serv.accept()
except socket.timeout:
@@ -26,9 +26,10 @@ class GeneralTests(TestCase):
def setUp(self):
self.evt = threading.Event()
- ready = threading.Event()
- threading.Thread(target=server, args=(self.evt, ready)).start()
- ready.wait()
+ threading.Thread(target=server, args=(self.evt,)).start()
+ self.evt.wait()
+ self.evt.clear()
+ time.sleep(.1)
def tearDown(self):
self.evt.wait()
diff --git a/Lib/test/test_urllibnet.py b/Lib/test/test_urllibnet.py
index a7d3805..c9a483a 100644
--- a/Lib/test/test_urllibnet.py
+++ b/Lib/test/test_urllibnet.py
@@ -9,6 +9,20 @@ import sys
import os
import mimetools
+
+def _open_with_retry(func, host, *args, **kwargs):
+ # Connecting to remote hosts is flaky. Make it more robust
+ # by retrying the connection several times.
+ for i in range(3):
+ try:
+ return func(host, *args, **kwargs)
+ except IOError, last_exc:
+ continue
+ except:
+ raise
+ raise last_exc
+
+
class URLTimeoutTest(unittest.TestCase):
TIMEOUT = 10.0
@@ -20,7 +34,7 @@ class URLTimeoutTest(unittest.TestCase):
socket.setdefaulttimeout(None)
def testURLread(self):
- f = urllib.urlopen("http://www.python.org/")
+ f = _open_with_retry(urllib.urlopen, "http://www.python.org/")
x = f.read()
class urlopenNetworkTests(unittest.TestCase):
@@ -38,9 +52,12 @@ class urlopenNetworkTests(unittest.TestCase):
"""
+ def urlopen(self, *args):
+ return _open_with_retry(urllib.urlopen, *args)
+
def test_basic(self):
# Simple test expected to pass.
- open_url = urllib.urlopen("http://www.python.org/")
+ open_url = self.urlopen("http://www.python.org/")
for attr in ("read", "readline", "readlines", "fileno", "close",
"info", "geturl"):
self.assert_(hasattr(open_url, attr), "object returned from "
@@ -52,7 +69,7 @@ class urlopenNetworkTests(unittest.TestCase):
def test_readlines(self):
# Test both readline and readlines.
- open_url = urllib.urlopen("http://www.python.org/")
+ open_url = self.urlopen("http://www.python.org/")
try:
self.assert_(isinstance(open_url.readline(), bytes),
"readline did not return bytes")
@@ -63,7 +80,7 @@ class urlopenNetworkTests(unittest.TestCase):
def test_info(self):
# Test 'info'.
- open_url = urllib.urlopen("http://www.python.org/")
+ open_url = self.urlopen("http://www.python.org/")
try:
info_obj = open_url.info()
finally:
@@ -76,7 +93,7 @@ class urlopenNetworkTests(unittest.TestCase):
def test_geturl(self):
# Make sure same URL as opened is returned by geturl.
URL = "http://www.python.org/"
- open_url = urllib.urlopen(URL)
+ open_url = self.urlopen(URL)
try:
gotten_url = open_url.geturl()
finally:
@@ -100,7 +117,7 @@ class urlopenNetworkTests(unittest.TestCase):
# test can't pass on Windows.
return
# Make sure fd returned by fileno is valid.
- open_url = urllib.urlopen("http://www.python.org/")
+ open_url = self.urlopen("http://www.python.org/")
fd = open_url.fileno()
FILE = os.fdopen(fd)
try:
@@ -125,9 +142,12 @@ class urlopenNetworkTests(unittest.TestCase):
class urlretrieveNetworkTests(unittest.TestCase):
"""Tests urllib.urlretrieve using the network."""
+ def urlretrieve(self, *args):
+ return _open_with_retry(urllib.urlretrieve, *args)
+
def test_basic(self):
# Test basic functionality.
- file_location,info = urllib.urlretrieve("http://www.python.org/")
+ file_location,info = self.urlretrieve("http://www.python.org/")
self.assert_(os.path.exists(file_location), "file location returned by"
" urlretrieve is not a valid path")
FILE = open(file_location)
@@ -140,8 +160,8 @@ class urlretrieveNetworkTests(unittest.TestCase):
def test_specified_path(self):
# Make sure that specifying the location of the file to write to works.
- file_location,info = urllib.urlretrieve("http://www.python.org/",
- test_support.TESTFN)
+ file_location,info = self.urlretrieve("http://www.python.org/",
+ test_support.TESTFN)
self.assertEqual(file_location, test_support.TESTFN)
self.assert_(os.path.exists(file_location))
FILE = open(file_location)
@@ -153,7 +173,7 @@ class urlretrieveNetworkTests(unittest.TestCase):
def test_header(self):
# Make sure header returned as 2nd value from urlretrieve is good.
- file_location, header = urllib.urlretrieve("http://www.python.org/")
+ file_location, header = self.urlretrieve("http://www.python.org/")
os.unlink(file_location)
self.assert_(isinstance(header, mimetools.Message),
"header is not an instance of mimetools.Message")
diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
index 16ef798..7b5af9e 100644
--- a/Lib/test/test_xmlrpc.py
+++ b/Lib/test/test_xmlrpc.py
@@ -261,6 +261,9 @@ class BinaryTestCase(unittest.TestCase):
PORT = None
+# The evt is set twice. First when the server is ready to serve.
+# Second when the server has been shutdown. The user must clear
+# the event after it has been set the first time to catch the second set.
def http_server(evt, numrequests):
class TestInstanceClass:
def div(self, x, y):
@@ -287,6 +290,7 @@ def http_server(evt, numrequests):
serv.register_function(lambda x,y: x+y, 'add')
serv.register_function(my_function)
serv.register_instance(TestInstanceClass())
+ evt.set()
# handle up to 'numrequests' requests
while numrequests > 0:
@@ -300,14 +304,16 @@ def http_server(evt, numrequests):
PORT = None
evt.set()
-def stop_serving():
- global PORT
- if PORT is None:
- return
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect(('localhost', int(PORT)))
- sock.send(b"")
- sock.close()
+# This function prevents errors like:
+# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
+def is_unavailable_exception(e):
+ '''Returns True if the given ProtocolError is the product of a server-side
+ exception caused by the 'temporarily unavailable' response sometimes
+ given by operations on non-blocking sockets.'''
+
+ # sometimes we get a -1 error code and/or empty headers
+ if e.errcode == -1 or e.headers is None:
+ return True
class SimpleServerTestCase(unittest.TestCase):
@@ -320,13 +326,9 @@ class SimpleServerTestCase(unittest.TestCase):
serv_args = (self.evt, 1)
threading.Thread(target=http_server, args=serv_args).start()
- # wait for port to be assigned to server
- n = 1000
- while n > 0 and PORT is None:
- time.sleep(0.001)
- n -= 1
-
- time.sleep(0.5)
+ # wait for the server to be ready
+ self.evt.wait()
+ self.evt.clear()
def tearDown(self):
# wait on the server thread to terminate
@@ -457,13 +459,9 @@ class FailingServerTestCase(unittest.TestCase):
serv_args = (self.evt, 1)
threading.Thread(target=http_server, args=serv_args).start()
- # wait for port to be assigned to server
- n = 1000
- while n > 0 and PORT is None:
- time.sleep(0.001)
- n -= 1
-
- time.sleep(0.5)
+ # wait for the server to be ready
+ self.evt.wait()
+ self.evt.clear()
def tearDown(self):
# wait on the server thread to terminate
diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py
index 1b14d2a..c4f8f79 100644
--- a/Lib/test/test_zipfile.py
+++ b/Lib/test/test_zipfile.py
@@ -309,6 +309,7 @@ class TestsWithSourceFile(unittest.TestCase):
correctfile = os.path.join(os.getcwd(), fpath[1:])
else:
correctfile = os.path.join(os.getcwd(), fpath)
+ correctfile = os.path.normpath(correctfile)
self.assertEqual(writtenfile, correctfile)