[Stackless-checkins] CVS: slpdev/src/2.2/src/Lib/test 185test.db, NONE, 1.1 badsyntax_future8.py, NONE, 1.1 badsyntax_future9.py, NONE, 1.1 cjkencodings_test.py, NONE, 1.1 list_tests.py, NONE, 1.1 seq_tests.py, NONE, 1.1 test__locale.py, NONE, 1.1 test_aepack.py, NONE, 1.1 test_anydbm.py, NONE, 1.1 test_applesingle.py, NONE, 1.1 test_bool.py, NONE, 1.1 test_bsddb185.py, NONE, 1.1 test_bsddb3.py, NONE, 1.1 test_bz2.py, NONE, 1.1 test_codeccallbacks.py, NONE, 1.1 test_codecencodings_cn.py, NONE, 1.1 test_codecencodings_jp.py, NONE, 1.1 test_codecencodings_kr.py, NONE, 1.1 test_codecencodings_tw.py, NONE, 1.1 test_codecmaps_cn.py, NONE, 1.1 test_codecmaps_jp.py, NONE, 1.1 test_codecmaps_kr.py, NONE, 1.1 test_codecmaps_tw.py, NONE, 1.1 test_colorsys.py, NONE, 1.1 test_copy.py, NONE, 1.1 test_csv.py, NONE, 1.1 test_datetime.py, NONE, 1.1 test_deque.py, NONE, 1.1 test_dis.py, NONE, 1.1 test_dummy_thread.py, NONE, 1.1 test_dummy_threading.py, NONE, 1.1 test_enumerate.py, NONE, 1.1 test_eof.py, NONE, 1.1 test_filecmp.py, NONE, 1.1 test_getargs2.py, NONE, 1.1 test_heapq.py, NONE, 1.1 test_hexoct.py, NONE, 1.1 test_imaplib.py, NONE, 1.1 test_imp.py, NONE, 1.1 test_importhooks.py, NONE, 1.1 test_ioctl.py, NONE, 1.1 test_isinstance.py, NONE, 1.1 test_iterlen.py, NONE, 1.1 test_itertools.py, NONE, 1.1 test_list.py, NONE, 1.1 test_logging.py, NONE, 1.1 test_macfs.py, NONE, 1.1 test_macostools.py, NONE, 1.1 test_macpath.py, NONE, 1.1 test_module.py, NONE, 1.1 test_mpz.py, NONE, 1.1 test_multibytecodec.py, NONE, 1.1 test_multibytecodec_support.py, NONE, 1.1 test_normalization.py, NONE, 1.1 test_optparse.py, NONE, 1.1 test_ossaudiodev.py, NONE, 1.1 test_pep263.py, NONE, 1.1 test_pep277.py, NONE, 1.1 test_pickletools.py, NONE, 1.1 test_plistlib.py, NONE, 1.1 test_popen.py, NONE, 1.1 test_posix.py, NONE, 1.1 test_resource.py, NONE, 1.1 test_robotparser.py, NONE, 1.1 test_scriptpackages.py, NONE, 1.1 test_set.py, NONE, 1.1 test_sets.py, NONE, 1.1 test_shelve.py, NONE, 1.1 test_shlex.py, NONE, 1.1 test_shutil.py, NONE, 1.1 test_slice.py, NONE, 1.1 test_softspace.py, NONE, 1.1 test_sort.py, NONE, 1.1 test_str.py, NONE, 1.1 test_stringprep.py, NONE, 1.1 test_strptime.py, NONE, 1.1 test_syntax.py, NONE, 1.1 test_sys.py, NONE, 1.1 test_tarfile.py, NONE, 1.1 test_tcl.py, NONE, 1.1 test_textwrap.py, NONE, 1.1 test_timeout.py, NONE, 1.1 test_tuple.py, NONE, 1.1 test_univnewlines.py, NONE, 1.1 test_urllibnet.py, NONE, 1.1 test_warnings.py, NONE, 1.1 test_whichdb.py, NONE, 1.1 test_xpickle.py, NONE, 1.1 test_zipimport.py, NONE, 1.1 testtar.tar, NONE, 1.1 tf_inherit_check.py, NONE, 1.1 tokenize_tests.txt, NONE, 1.1 xmltests.py, NONE, 1.1
Christian Tismer
tismer at centera.de
Sat May 1 02:54:21 CEST 2004
- Previous message: [Stackless-checkins] CVS: slpdev/src/2.2/src/Lib/test/output test_logging, NONE, 1.1 test_ossaudiodev, NONE, 1.1 test_pep277, NONE, 1.1 test_popen, NONE, 1.1 test_resource, NONE, 1.1 xmltests, NONE, 1.1
- Next message: [Stackless-checkins] CVS: slpdev/src/2.2/src/Lib/xml/dom NodeFilter.py, NONE, 1.1 expatbuilder.py, NONE, 1.1 minicompat.py, NONE, 1.1 xmlbuilder.py, NONE, 1.1
- Messages sorted by:
[ date ]
[ thread ]
[ subject ]
[ author ]
Update of /home/cvs/slpdev/src/2.2/src/Lib/test
In directory centera.de:/home/tismer/slpdev/src/2.2/src/Lib/test
Added Files:
185test.db badsyntax_future8.py badsyntax_future9.py
cjkencodings_test.py list_tests.py seq_tests.py
test__locale.py test_aepack.py test_anydbm.py
test_applesingle.py test_bool.py test_bsddb185.py
test_bsddb3.py test_bz2.py test_codeccallbacks.py
test_codecencodings_cn.py test_codecencodings_jp.py
test_codecencodings_kr.py test_codecencodings_tw.py
test_codecmaps_cn.py test_codecmaps_jp.py test_codecmaps_kr.py
test_codecmaps_tw.py test_colorsys.py test_copy.py test_csv.py
test_datetime.py test_deque.py test_dis.py
test_dummy_thread.py test_dummy_threading.py test_enumerate.py
test_eof.py test_filecmp.py test_getargs2.py test_heapq.py
test_hexoct.py test_imaplib.py test_imp.py test_importhooks.py
test_ioctl.py test_isinstance.py test_iterlen.py
test_itertools.py test_list.py test_logging.py test_macfs.py
test_macostools.py test_macpath.py test_module.py test_mpz.py
test_multibytecodec.py test_multibytecodec_support.py
test_normalization.py test_optparse.py test_ossaudiodev.py
test_pep263.py test_pep277.py test_pickletools.py
test_plistlib.py test_popen.py test_posix.py test_resource.py
test_robotparser.py test_scriptpackages.py test_set.py
test_sets.py test_shelve.py test_shlex.py test_shutil.py
test_slice.py test_softspace.py test_sort.py test_str.py
test_stringprep.py test_strptime.py test_syntax.py test_sys.py
test_tarfile.py test_tcl.py test_textwrap.py test_timeout.py
test_tuple.py test_univnewlines.py test_urllibnet.py
test_warnings.py test_whichdb.py test_xpickle.py
test_zipimport.py testtar.tar tf_inherit_check.py
tokenize_tests.txt xmltests.py
Log Message:
added files
--- NEW FILE: 185test.db ---
ÿÿ
--- NEW FILE: badsyntax_future8.py ---
"""This is a test"""
from __future__ import *
def f(x):
def g(y):
return x + y
return g
print f(2)(4)
--- NEW FILE: badsyntax_future9.py ---
"""This is a test"""
from __future__ import nested_scopes, braces
def f(x):
def g(y):
return x + y
return g
print f(2)(4)
--- NEW FILE: cjkencodings_test.py ---
teststring = {
'big5': (
"\xa6\x70\xa6\xf3\xa6\x62\x20\x50\x79\x74\x68\x6f\x6e\x20\xa4\xa4"
"\xa8\xcf\xa5\xce\xac\x4a\xa6\xb3\xaa\xba\x20\x43\x20\x6c\x69\x62"
"\x72\x61\x72\x79\x3f\x0a\xa1\x40\xa6\x62\xb8\xea\xb0\x54\xac\xec"
"\xa7\xde\xa7\xd6\xb3\x74\xb5\x6f\xae\x69\xaa\xba\xa4\xb5\xa4\xd1"
"\x2c\x20\xb6\x7d\xb5\x6f\xa4\xce\xb4\xfa\xb8\xd5\xb3\x6e\xc5\xe9"
"\xaa\xba\xb3\x74\xab\xd7\xac\x4f\xa4\xa3\xae\x65\xa9\xbf\xb5\xf8"
"\xaa\xba\x0a\xbd\xd2\xc3\x44\x2e\x20\xac\xb0\xa5\x5b\xa7\xd6\xb6"
"\x7d\xb5\x6f\xa4\xce\xb4\xfa\xb8\xd5\xaa\xba\xb3\x74\xab\xd7\x2c"
"\x20\xa7\xda\xad\xcc\xab\x4b\xb1\x60\xa7\xc6\xb1\xe6\xaf\xe0\xa7"
"\x51\xa5\xce\xa4\x40\xa8\xc7\xa4\x77\xb6\x7d\xb5\x6f\xa6\x6e\xaa"
"\xba\x0a\x6c\x69\x62\x72\x61\x72\x79\x2c\x20\xa8\xc3\xa6\xb3\xa4"
"\x40\xad\xd3\x20\x66\x61\x73\x74\x20\x70\x72\x6f\x74\x6f\x74\x79"
"\x70\x69\x6e\x67\x20\xaa\xba\x20\x70\x72\x6f\x67\x72\x61\x6d\x6d"
"\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75\x61\x67\x65\x20\xa5\x69\x0a"
"\xa8\xd1\xa8\xcf\xa5\xce\x2e\x20\xa5\xd8\xab\x65\xa6\xb3\xb3\x5c"
"\xb3\x5c\xa6\x68\xa6\x68\xaa\xba\x20\x6c\x69\x62\x72\x61\x72\x79"
"\x20\xac\x4f\xa5\x48\x20\x43\x20\xbc\x67\xa6\xa8\x2c\x20\xa6\xd3"
[...962 lines suppressed...]
"\x20\xe3\x81\xa7\xe3\x81\xaf\xe3\x81\x9d\xe3\x81\x86\xe3\x81\x84"
"\xe3\x81\xa3\xe3\x81\x9f\xe5\xb0\x8f\xe7\xb4\xb0\xe5\xb7\xa5\xe3"
"\x81\x8c\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x95\xe3\x82\x8c\xe3\x82"
"\x8b\xe3\x81\x93\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\x82\xe3\x81\xbe"
"\xe3\x82\x8a\xe3\x81\x82\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x9b\xe3"
"\x82\x93\xe3\x80\x82\x0a\xe8\xa8\x80\xe8\xaa\x9e\xe8\x87\xaa\xe4"
"\xbd\x93\xe3\x81\xae\xe6\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x9c"
"\x80\xe5\xb0\x8f\xe9\x99\x90\xe3\x81\xab\xe6\x8a\xbc\xe3\x81\x95"
"\xe3\x81\x88\xe3\x80\x81\xe5\xbf\x85\xe8\xa6\x81\xe3\x81\xaa\xe6"
"\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x8b\xa1\xe5\xbc\xb5\xe3\x83"
"\xa2\xe3\x82\xb8\xe3\x83\xa5\xe3\x83\xbc\xe3\x83\xab\xe3\x81\xa8"
"\xe3\x81\x97\xe3\x81\xa6\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x99\xe3"
"\x82\x8b\xe3\x80\x81\xe3\x81\xa8\xe3\x81\x84\xe3\x81\x86\xe3\x81"
"\xae\xe3\x81\x8c\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe3"
"\x83\x9d\xe3\x83\xaa\xe3\x82\xb7\xe3\x83\xbc\xe3\x81\xa7\xe3\x81"
"\x99\xe3\x80\x82\x0a\x0a\xe3\x83\x8e\xe3\x81\x8b\xe3\x82\x9a\x20"
"\xe3\x83\x88\xe3\x82\x9a\x20\xe3\x83\x88\xe3\x82\xad\xef\xa8\xb6"
"\xef\xa8\xb9\x20\xf0\xa1\x9a\xb4\xf0\xaa\x8e\x8c\x20\xe9\xba\x80"
"\xe9\xbd\x81\xf0\xa9\x9b\xb0\x0a"),
}
--- NEW FILE: list_tests.py ---
"""
Tests common to list and UserList.UserList
"""
import sys
import unittest
from test import test_support, seq_tests
class CommonTest(seq_tests.CommonTest):
def test_repr(self):
l0 = []
l2 = [0, 1, 2]
a0 = self.type2test(l0)
a2 = self.type2test(l2)
self.assertEqual(str(a0), str(l0))
self.assertEqual(repr(a0), repr(l0))
self.assertEqual(`a2`, `l2`)
self.assertEqual(str(a2), "[0, 1, 2]")
self.assertEqual(repr(a2), "[0, 1, 2]")
def test_setitem(self):
a = self.type2test([0, 1])
a[0] = 0
a[1] = 100
self.assertEqual(a, self.type2test([0, 100]))
a[-1] = 200
self.assertEqual(a, self.type2test([0, 200]))
a[-2] = 100
self.assertEqual(a, self.type2test([100, 200]))
self.assertRaises(IndexError, a.__setitem__, -3, 200)
self.assertRaises(IndexError, a.__setitem__, 2, 200)
a = self.type2test([])
self.assertRaises(IndexError, a.__setitem__, 0, 200)
self.assertRaises(IndexError, a.__setitem__, -1, 200)
self.assertRaises(TypeError, a.__setitem__)
a = self.type2test([0,1,2,3,4])
a[0L] = 1
a[1L] = 2
a[2L] = 3
self.assertEqual(a, self.type2test([1,2,3,3,4]))
a[0] = 5
a[1] = 6
a[2] = 7
self.assertEqual(a, self.type2test([5,6,7,3,4]))
a[-2L] = 88
a[-1L] = 99
self.assertEqual(a, self.type2test([5,6,7,88,99]))
a[-2] = 8
a[-1] = 9
self.assertEqual(a, self.type2test([5,6,7,8,9]))
def test_delitem(self):
a = self.type2test([0, 1])
del a[1]
self.assertEqual(a, [0])
del a[0]
self.assertEqual(a, [])
a = self.type2test([0, 1])
del a[-2]
self.assertEqual(a, [1])
del a[-1]
self.assertEqual(a, [])
a = self.type2test([0, 1])
self.assertRaises(IndexError, a.__delitem__, -3)
self.assertRaises(IndexError, a.__delitem__, 2)
a = self.type2test([])
self.assertRaises(IndexError, a.__delitem__, 0)
self.assertRaises(TypeError, a.__delitem__)
def test_setslice(self):
l = [0, 1]
a = self.type2test(l)
for i in range(-3, 4):
a[:i] = l[:i]
self.assertEqual(a, l)
a2 = a[:]
a2[:i] = a[:i]
self.assertEqual(a2, a)
a[i:] = l[i:]
self.assertEqual(a, l)
a2 = a[:]
a2[i:] = a[i:]
self.assertEqual(a2, a)
for j in range(-3, 4):
a[i:j] = l[i:j]
self.assertEqual(a, l)
a2 = a[:]
a2[i:j] = a[i:j]
self.assertEqual(a2, a)
aa2 = a2[:]
aa2[:0] = [-2, -1]
self.assertEqual(aa2, [-2, -1, 0, 1])
aa2[0:] = []
self.assertEqual(aa2, [])
a = self.type2test([1, 2, 3, 4, 5])
a[:-1] = a
self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 5]))
a = self.type2test([1, 2, 3, 4, 5])
a[1:] = a
self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5]))
a = self.type2test([1, 2, 3, 4, 5])
a[1:-1] = a
self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5, 5]))
a = self.type2test([])
a[:] = tuple(range(10))
self.assertEqual(a, self.type2test(range(10)))
self.assertRaises(TypeError, a.__setslice__, 0, 1, 5)
self.assertRaises(TypeError, a.__setslice__)
def test_delslice(self):
a = self.type2test([0, 1])
del a[1:2]
del a[0:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[1L:2L]
del a[0L:1L]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[-2:-1]
self.assertEqual(a, self.type2test([1]))
a = self.type2test([0, 1])
del a[-2L:-1L]
self.assertEqual(a, self.type2test([1]))
a = self.type2test([0, 1])
del a[1:]
del a[:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[1L:]
del a[:1L]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
del a[-1:]
self.assertEqual(a, self.type2test([0]))
a = self.type2test([0, 1])
del a[-1L:]
self.assertEqual(a, self.type2test([0]))
a = self.type2test([0, 1])
del a[:]
self.assertEqual(a, self.type2test([]))
def test_append(self):
a = self.type2test([])
a.append(0)
a.append(1)
a.append(2)
self.assertEqual(a, self.type2test([0, 1, 2]))
self.assertRaises(TypeError, a.append)
def test_extend(self):
a1 = self.type2test([0])
a2 = self.type2test((0, 1))
a = a1[:]
a.extend(a2)
self.assertEqual(a, a1 + a2)
a.extend(self.type2test([]))
self.assertEqual(a, a1 + a2)
a.extend(a)
self.assertEqual(a, self.type2test([0, 0, 1, 0, 0, 1]))
a = self.type2test("spam")
a.extend("eggs")
self.assertEqual(a, list("spameggs"))
self.assertRaises(TypeError, a.extend, None)
self.assertRaises(TypeError, a.extend)
def test_insert(self):
a = self.type2test([0, 1, 2])
a.insert(0, -2)
a.insert(1, -1)
a.insert(2, 0)
self.assertEqual(a, [-2, -1, 0, 0, 1, 2])
b = a[:]
b.insert(-2, "foo")
b.insert(-200, "left")
b.insert(200, "right")
self.assertEqual(b, self.type2test(["left",-2,-1,0,0,"foo",1,2,"right"]))
self.assertRaises(TypeError, a.insert)
def test_pop(self):
a = self.type2test([-1, 0, 1])
a.pop()
self.assertEqual(a, [-1, 0])
a.pop(0)
self.assertEqual(a, [0])
self.assertRaises(IndexError, a.pop, 5)
a.pop(0)
self.assertEqual(a, [])
self.assertRaises(IndexError, a.pop)
self.assertRaises(TypeError, a.pop, 42, 42)
def test_remove(self):
a = self.type2test([0, 0, 1])
a.remove(1)
self.assertEqual(a, [0, 0])
a.remove(0)
self.assertEqual(a, [0])
a.remove(0)
self.assertEqual(a, [])
self.assertRaises(ValueError, a.remove, 0)
self.assertRaises(TypeError, a.remove)
class BadExc(Exception):
pass
class BadCmp:
def __eq__(self, other):
if other == 2:
raise BadExc()
return False
a = self.type2test([0, 1, 2, 3])
self.assertRaises(BadExc, a.remove, BadCmp())
def test_count(self):
a = self.type2test([0, 1, 2])*3
self.assertEqual(a.count(0), 3)
self.assertEqual(a.count(1), 3)
self.assertEqual(a.count(3), 0)
self.assertRaises(TypeError, a.count)
class BadExc(Exception):
pass
class BadCmp:
def __eq__(self, other):
if other == 2:
raise BadExc()
return False
self.assertRaises(BadExc, a.count, BadCmp())
def test_index(self):
u = self.type2test([0, 1])
self.assertEqual(u.index(0), 0)
self.assertEqual(u.index(1), 1)
self.assertRaises(ValueError, u.index, 2)
u = self.type2test([-2, -1, 0, 0, 1, 2])
self.assertEqual(u.count(0), 2)
self.assertEqual(u.index(0), 2)
self.assertEqual(u.index(0, 2), 2)
self.assertEqual(u.index(-2, -10), 0)
self.assertEqual(u.index(0, 3), 3)
self.assertEqual(u.index(0, 3, 4), 3)
self.assertRaises(ValueError, u.index, 2, 0, -10)
self.assertRaises(TypeError, u.index)
class BadExc(Exception):
pass
class BadCmp:
def __eq__(self, other):
if other == 2:
raise BadExc()
return False
a = self.type2test([0, 1, 2, 3])
self.assertRaises(BadExc, a.index, BadCmp())
a = self.type2test([-2, -1, 0, 0, 1, 2])
self.assertEqual(a.index(0), 2)
self.assertEqual(a.index(0, 2), 2)
self.assertEqual(a.index(0, -4), 2)
self.assertEqual(a.index(-2, -10), 0)
self.assertEqual(a.index(0, 3), 3)
self.assertEqual(a.index(0, -3), 3)
self.assertEqual(a.index(0, 3, 4), 3)
self.assertEqual(a.index(0, -3, -2), 3)
self.assertEqual(a.index(0, -4*sys.maxint, 4*sys.maxint), 2)
self.assertRaises(ValueError, a.index, 0, 4*sys.maxint,-4*sys.maxint)
self.assertRaises(ValueError, a.index, 2, 0, -10)
a.remove(0)
self.assertRaises(ValueError, a.index, 2, 0, 4)
self.assertEqual(a, self.type2test([-2, -1, 0, 1, 2]))
def test_reverse(self):
u = self.type2test([-2, -1, 0, 1, 2])
u2 = u[:]
u.reverse()
self.assertEqual(u, [2, 1, 0, -1, -2])
u.reverse()
self.assertEqual(u, u2)
self.assertRaises(TypeError, u.reverse, 42)
def test_sort(self):
u = self.type2test([1, 0])
u.sort()
self.assertEqual(u, [0, 1])
u = self.type2test([2,1,0,-1,-2])
u.sort()
self.assertEqual(u, self.type2test([-2,-1,0,1,2]))
self.assertRaises(TypeError, u.sort, 42, 42)
def revcmp(a, b):
return cmp(b, a)
u.sort(revcmp)
self.assertEqual(u, self.type2test([2,1,0,-1,-2]))
# The following dumps core in unpatched Python 1.5:
def myComparison(x,y):
return cmp(x%3, y%7)
z = self.type2test(range(12))
z.sort(myComparison)
self.assertRaises(TypeError, z.sort, 2)
def selfmodifyingComparison(x,y):
z.append(1)
return cmp(x, y)
self.assertRaises(ValueError, z.sort, selfmodifyingComparison)
self.assertRaises(TypeError, z.sort, lambda x, y: 's')
self.assertRaises(TypeError, z.sort, 42, 42, 42, 42)
def test_slice(self):
u = self.type2test("spam")
u[:2] = "h"
self.assertEqual(u, list("ham"))
def test_iadd(self):
super(CommonTest, self).test_iadd()
u = self.type2test([0, 1])
u2 = u
u += [2, 3]
self.assert_(u is u2)
u = self.type2test("spam")
u += "eggs"
self.assertEqual(u, self.type2test("spameggs"))
self.assertRaises(TypeError, u.__iadd__, None)
def test_imul(self):
u = self.type2test([0, 1])
u *= 3
self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1]))
u *= 0
self.assertEqual(u, self.type2test([]))
def test_extendedslicing(self):
# subscript
a = self.type2test([0,1,2,3,4])
# deletion
del a[::2]
self.assertEqual(a, self.type2test([1,3]))
a = self.type2test(range(5))
del a[1::2]
self.assertEqual(a, self.type2test([0,2,4]))
a = self.type2test(range(5))
del a[1::-2]
self.assertEqual(a, self.type2test([0,2,3,4]))
a = self.type2test(range(10))
del a[::1000]
self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 6, 7, 8, 9]))
# assignment
a = self.type2test(range(10))
a[::2] = [-1]*5
self.assertEqual(a, self.type2test([-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]))
a = self.type2test(range(10))
a[::-4] = [10]*3
self.assertEqual(a, self.type2test([0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
a = self.type2test(range(4))
a[::-1] = a
self.assertEqual(a, self.type2test([3, 2, 1, 0]))
a = self.type2test(range(10))
b = a[:]
c = a[:]
a[2:3] = self.type2test(["two", "elements"])
b[slice(2,3)] = self.type2test(["two", "elements"])
c[2:3:] = self.type2test(["two", "elements"])
self.assertEqual(a, b)
self.assertEqual(a, c)
a = self.type2test(range(10))
a[::2] = tuple(range(5))
self.assertEqual(a, self.type2test([0, 1, 1, 3, 2, 5, 3, 7, 4, 9]))
--- NEW FILE: seq_tests.py ---
"""
Tests common to tuple, list and UserList.UserList
"""
import unittest
from test import test_support
class CommonTest(unittest.TestCase):
# The type to be tested
type2test = None
def test_constructors(self):
l0 = []
l1 = [0]
l2 = [0, 1]
u = self.type2test()
u0 = self.type2test(l0)
u1 = self.type2test(l1)
u2 = self.type2test(l2)
uu = self.type2test(u)
uu0 = self.type2test(u0)
uu1 = self.type2test(u1)
uu2 = self.type2test(u2)
v = self.type2test(tuple(u))
class OtherSeq:
def __init__(self, initseq):
self.__data = initseq
def __len__(self):
return len(self.__data)
def __getitem__(self, i):
return self.__data[i]
s = OtherSeq(u0)
v0 = self.type2test(s)
self.assertEqual(len(v0), len(s))
s = "this is also a sequence"
vv = self.type2test(s)
self.assertEqual(len(vv), len(s))
def test_truth(self):
self.assert_(not self.type2test())
self.assert_(self.type2test([42]))
def test_getitem(self):
u = self.type2test([0, 1, 2, 3, 4])
for i in xrange(len(u)):
self.assertEqual(u[i], i)
for i in xrange(-len(u), -1):
self.assertEqual(u[i], len(u)+i)
self.assertRaises(IndexError, u.__getitem__, -len(u)-1)
self.assertRaises(IndexError, u.__getitem__, len(u))
u = self.type2test()
self.assertRaises(IndexError, u.__getitem__, 0)
self.assertRaises(IndexError, u.__getitem__, -1)
self.assertRaises(TypeError, u.__getitem__)
def test_getslice(self):
l = [0, 1, 2, 3, 4]
u = self.type2test(l)
self.assertEqual(u[0:0], self.type2test())
self.assertEqual(u[1:2], self.type2test([1]))
self.assertEqual(u[-2:-1], self.type2test([3]))
self.assertEqual(u[-1000:1000], u)
self.assertEqual(u[1000:-1000], self.type2test([]))
self.assertEqual(u[:], u)
self.assertEqual(u[1:None], self.type2test([1, 2, 3, 4]))
self.assertEqual(u[None:3], self.type2test([0, 1, 2]))
# Extended slices
self.assertEqual(u[::], u)
self.assertEqual(u[::2], self.type2test([0, 2, 4]))
self.assertEqual(u[1::2], self.type2test([1, 3]))
self.assertEqual(u[::-1], self.type2test([4, 3, 2, 1, 0]))
self.assertEqual(u[::-2], self.type2test([4, 2, 0]))
self.assertEqual(u[3::-2], self.type2test([3, 1]))
self.assertEqual(u[3:3:-2], self.type2test([]))
self.assertEqual(u[3:2:-2], self.type2test([3]))
self.assertEqual(u[3:1:-2], self.type2test([3]))
self.assertEqual(u[3:0:-2], self.type2test([3, 1]))
self.assertEqual(u[::-100], self.type2test([4]))
self.assertEqual(u[100:-100:], self.type2test([]))
self.assertEqual(u[-100:100:], u)
self.assertEqual(u[100:-100:-1], u[::-1])
self.assertEqual(u[-100:100:-1], self.type2test([]))
self.assertEqual(u[-100L:100L:2L], self.type2test([0, 2, 4]))
# Test extreme cases with long ints
a = self.type2test([0,1,2,3,4])
self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2]))
self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4]))
self.assertRaises(TypeError, u.__getslice__)
def test_contains(self):
u = self.type2test([0, 1, 2])
for i in u:
self.assert_(i in u)
for i in min(u)-1, max(u)+1:
self.assert_(i not in u)
self.assertRaises(TypeError, u.__contains__)
def test_len(self):
self.assertEqual(len(self.type2test()), 0)
self.assertEqual(len(self.type2test([])), 0)
self.assertEqual(len(self.type2test([0])), 1)
self.assertEqual(len(self.type2test([0, 1, 2])), 3)
def test_minmax(self):
u = self.type2test([0, 1, 2])
self.assertEqual(min(u), 0)
self.assertEqual(max(u), 2)
def test_addmul(self):
u1 = self.type2test([0])
u2 = self.type2test([0, 1])
self.assertEqual(u1, u1 + self.type2test())
self.assertEqual(u1, self.type2test() + u1)
self.assertEqual(u1 + self.type2test([1]), u2)
self.assertEqual(self.type2test([-1]) + u1, self.type2test([-1, 0]))
self.assertEqual(self.type2test(), u2*0)
self.assertEqual(self.type2test(), 0*u2)
self.assertEqual(self.type2test(), u2*0L)
self.assertEqual(self.type2test(), 0L*u2)
self.assertEqual(u2, u2*1)
self.assertEqual(u2, 1*u2)
self.assertEqual(u2, u2*1L)
self.assertEqual(u2, 1L*u2)
self.assertEqual(u2+u2, u2*2)
self.assertEqual(u2+u2, 2*u2)
self.assertEqual(u2+u2, u2*2L)
self.assertEqual(u2+u2, 2L*u2)
self.assertEqual(u2+u2+u2, u2*3)
self.assertEqual(u2+u2+u2, 3*u2)
class subclass(self.type2test):
pass
u3 = subclass([0, 1])
self.assertEqual(u3, u3*1)
self.assert_(u3 is not u3*1)
def test_iadd(self):
u = self.type2test([0, 1])
u += self.type2test()
self.assertEqual(u, self.type2test([0, 1]))
u += self.type2test([2, 3])
self.assertEqual(u, self.type2test([0, 1, 2, 3]))
u += self.type2test([4, 5])
self.assertEqual(u, self.type2test([0, 1, 2, 3, 4, 5]))
u = self.type2test("spam")
u += self.type2test("eggs")
self.assertEqual(u, self.type2test("spameggs"))
def test_imul(self):
u = self.type2test([0, 1])
u *= 3
self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1]))
def test_getitemoverwriteiter(self):
# Verify that __getitem__ overrides are not recognized by __iter__
class T(self.type2test):
def __getitem__(self, key):
return str(key) + '!!!'
self.assertEqual(iter(T((1,2))).next(), 1)
--- NEW FILE: test__locale.py ---
from test.test_support import verbose, TestSkipped
from _locale import setlocale, LC_NUMERIC, RADIXCHAR, THOUSEP, nl_langinfo
from _locale import localeconv, Error
candidate_locales = ['es_UY', 'fr_FR', 'fi_FI', 'es_CO', 'pt_PT', 'it_IT',
'et_EE', 'es_PY', 'no_NO', 'nl_NL', 'lv_LV', 'el_GR', 'be_BY', 'fr_BE',
'ro_RO', 'ru_UA', 'ru_RU', 'es_VE', 'ca_ES', 'se_NO', 'es_EC', 'id_ID',
'ka_GE', 'es_CL', 'hu_HU', 'wa_BE', 'lt_LT', 'sl_SI', 'hr_HR', 'es_AR',
'es_ES', 'oc_FR', 'gl_ES', 'bg_BG', 'is_IS', 'mk_MK', 'de_AT', 'pt_BR',
'da_DK', 'nn_NO', 'cs_CZ', 'de_LU', 'es_BO', 'sq_AL', 'sk_SK', 'fr_CH',
'de_DE', 'sr_YU', 'br_FR', 'nl_BE', 'sv_FI', 'pl_PL', 'fr_CA', 'fo_FO',
'bs_BA', 'fr_LU', 'kl_GL', 'fa_IR', 'de_BE', 'sv_SE', 'it_CH', 'uk_UA',
'eu_ES', 'vi_VN', 'af_ZA', 'nb_NO', 'en_DK', 'tg_TJ',
'es_ES.ISO8859-1', 'fr_FR.ISO8859-15', 'ru_RU.KOI8-R', 'ko_KR.eucKR']
saw_locale = 0
for loc in candidate_locales:
try:
setlocale(LC_NUMERIC, loc)
except Error:
continue
if verbose:
print "locale %r" % loc
saw_locale = 1
nl_radixchar = nl_langinfo(RADIXCHAR)
li_radixchar = localeconv()['decimal_point']
if nl_radixchar != li_radixchar:
print "%r != %r" % (nl_radixchar, li_radixchar)
nl_radixchar = nl_langinfo(THOUSEP)
li_radixchar = localeconv()['thousands_sep']
if nl_radixchar != li_radixchar:
print "%r != %r" % (nl_radixchar, li_radixchar)
if not saw_locale:
raise ImportError, "None of the listed locales found"
--- NEW FILE: test_aepack.py ---
# Copyright (C) 2003 Python Software Foundation
import unittest
import aepack
import aetypes
import os
from test import test_support
class TestAepack(unittest.TestCase):
OBJECTS = [
aetypes.Enum('enum'),
aetypes.Type('type'),
aetypes.Keyword('kwrd'),
aetypes.Range(1, 10),
aetypes.Comparison(1, '< ', 10),
aetypes.Logical('not ', 1),
aetypes.IntlText(0, 0, 'international text'),
aetypes.IntlWritingCode(0,0),
aetypes.QDPoint(50,100),
aetypes.QDRectangle(50,100,150,200),
aetypes.RGBColor(0x7000, 0x6000, 0x5000),
aetypes.Unknown('xxxx', 'unknown type data'),
aetypes.Character(1),
aetypes.Character(2, aetypes.Line(2)),
]
def test_roundtrip_string(self):
o = 'a string'
packed = aepack.pack(o)
unpacked = aepack.unpack(packed)
self.assertEqual(o, unpacked)
def test_roundtrip_int(self):
o = 12
packed = aepack.pack(o)
unpacked = aepack.unpack(packed)
self.assertEqual(o, unpacked)
def test_roundtrip_float(self):
o = 12.1
packed = aepack.pack(o)
unpacked = aepack.unpack(packed)
self.assertEqual(o, unpacked)
def test_roundtrip_None(self):
o = None
packed = aepack.pack(o)
unpacked = aepack.unpack(packed)
self.assertEqual(o, unpacked)
def test_roundtrip_aeobjects(self):
for o in self.OBJECTS:
packed = aepack.pack(o)
unpacked = aepack.unpack(packed)
self.assertEqual(repr(o), repr(unpacked))
def test_roundtrip_FSSpec(self):
try:
import Carbon.File
except:
return
o = Carbon.File.FSSpec(os.curdir)
packed = aepack.pack(o)
unpacked = aepack.unpack(packed)
self.assertEqual(o.as_pathname(), unpacked.as_pathname())
def test_roundtrip_Alias(self):
try:
import Carbon.File
except:
return
o = Carbon.File.FSSpec(os.curdir).NewAliasMinimal()
packed = aepack.pack(o)
unpacked = aepack.unpack(packed)
self.assertEqual(o.FSResolveAlias(None)[0].as_pathname(),
unpacked.FSResolveAlias(None)[0].as_pathname())
def test_main():
test_support.run_unittest(TestAepack)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_anydbm.py ---
#! /usr/bin/env python
"""Test script for the anydbm module
based on testdumbdbm.py
"""
import os
import unittest
import anydbm
import glob
from test import test_support
_fname = test_support.TESTFN
def _delete_files():
# we don't know the precise name the underlying database uses
# so we use glob to locate all names
for f in glob.glob(_fname + "*"):
try:
os.unlink(f)
except OSError:
pass
class AnyDBMTestCase(unittest.TestCase):
_dict = {'0': '',
'a': 'Python:',
'b': 'Programming',
'c': 'the',
'd': 'way',
'f': 'Guido',
'g': 'intended'
}
def __init__(self, *args):
unittest.TestCase.__init__(self, *args)
def test_anydbm_creation(self):
f = anydbm.open(_fname, 'c')
self.assertEqual(f.keys(), [])
for key in self._dict:
f[key] = self._dict[key]
self.read_helper(f)
f.close()
def test_anydbm_modification(self):
self.init_db()
f = anydbm.open(_fname, 'c')
self._dict['g'] = f['g'] = "indented"
self.read_helper(f)
f.close()
def test_anydbm_read(self):
self.init_db()
f = anydbm.open(_fname, 'r')
self.read_helper(f)
f.close()
def test_anydbm_keys(self):
self.init_db()
f = anydbm.open(_fname, 'r')
keys = self.keys_helper(f)
f.close()
def read_helper(self, f):
keys = self.keys_helper(f)
for key in self._dict:
self.assertEqual(self._dict[key], f[key])
def init_db(self):
f = anydbm.open(_fname, 'n')
for k in self._dict:
f[k] = self._dict[k]
f.close()
def keys_helper(self, f):
keys = f.keys()
keys.sort()
dkeys = self._dict.keys()
dkeys.sort()
self.assertEqual(keys, dkeys)
return keys
def tearDown(self):
_delete_files()
def setUp(self):
_delete_files()
def test_main():
try:
test_support.run_unittest(AnyDBMTestCase)
finally:
_delete_files()
if __name__ == "__main__":
test_main()
--- NEW FILE: test_applesingle.py ---
# Copyright (C) 2003 Python Software Foundation
import unittest
import macostools
import Carbon.File
import MacOS
import os
import sys
from test import test_support
import struct
import applesingle
AS_MAGIC=0x00051600
AS_VERSION=0x00020000
dataforkdata = 'hello\r\0world\n'
resourceforkdata = 'goodbye\ncruel\0world\r'
applesingledata = struct.pack("ll16sh", AS_MAGIC, AS_VERSION, "foo", 2) + \
struct.pack("llllll", 1, 50, len(dataforkdata),
2, 50+len(dataforkdata), len(resourceforkdata)) + \
dataforkdata + \
resourceforkdata
TESTFN2 = test_support.TESTFN + '2'
class TestApplesingle(unittest.TestCase):
def setUp(self):
fp = open(test_support.TESTFN, 'w')
fp.write(applesingledata)
fp.close()
def tearDown(self):
try:
os.unlink(test_support.TESTFN)
except:
pass
try:
os.unlink(TESTFN2)
except:
pass
def compareData(self, isrf, data):
if isrf:
fp = MacOS.openrf(TESTFN2, '*rb')
else:
fp = open(TESTFN2, 'rb')
filedata = fp.read(1000)
self.assertEqual(data, filedata)
def test_applesingle(self):
try:
os.unlink(TESTFN2)
except:
pass
applesingle.decode(test_support.TESTFN, TESTFN2)
self.compareData(False, dataforkdata)
self.compareData(True, resourceforkdata)
def test_applesingle_resonly(self):
try:
os.unlink(TESTFN2)
except:
pass
applesingle.decode(test_support.TESTFN, TESTFN2, resonly=True)
self.compareData(False, resourceforkdata)
def test_main():
test_support.run_unittest(TestApplesingle)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_bool.py ---
# Test properties of bool promised by PEP 285
import unittest
from test import test_support
import os
class BoolTest(unittest.TestCase):
def assertIs(self, a, b):
self.assert_(a is b)
def assertIsNot(self, a, b):
self.assert_(a is not b)
def test_subclass(self):
try:
class C(bool):
pass
except TypeError:
pass
else:
self.fail("bool should not be subclassable")
self.assertRaises(TypeError, int.__new__, bool, 0)
def test_print(self):
try:
fo = open(test_support.TESTFN, "wb")
print >> fo, False, True
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), 'False True\n')
finally:
fo.close()
os.remove(test_support.TESTFN)
def test_repr(self):
self.assertEqual(repr(False), 'False')
self.assertEqual(repr(True), 'True')
self.assertEqual(eval(repr(False)), False)
self.assertEqual(eval(repr(True)), True)
def test_str(self):
self.assertEqual(str(False), 'False')
self.assertEqual(str(True), 'True')
def test_int(self):
self.assertEqual(int(False), 0)
self.assertIsNot(int(False), False)
self.assertEqual(int(True), 1)
self.assertIsNot(int(True), True)
def test_math(self):
self.assertEqual(+False, 0)
self.assertIsNot(+False, False)
self.assertEqual(-False, 0)
self.assertIsNot(-False, False)
self.assertEqual(abs(False), 0)
self.assertIsNot(abs(False), False)
self.assertEqual(+True, 1)
self.assertIsNot(+True, True)
self.assertEqual(-True, -1)
self.assertEqual(abs(True), 1)
self.assertIsNot(abs(True), True)
self.assertEqual(~False, -1)
self.assertEqual(~True, -2)
self.assertEqual(False+2, 2)
self.assertEqual(True+2, 3)
self.assertEqual(2+False, 2)
self.assertEqual(2+True, 3)
self.assertEqual(False+False, 0)
self.assertIsNot(False+False, False)
self.assertEqual(False+True, 1)
self.assertIsNot(False+True, True)
self.assertEqual(True+False, 1)
self.assertIsNot(True+False, True)
self.assertEqual(True+True, 2)
self.assertEqual(True-True, 0)
self.assertIsNot(True-True, False)
self.assertEqual(False-False, 0)
self.assertIsNot(False-False, False)
self.assertEqual(True-False, 1)
self.assertIsNot(True-False, True)
self.assertEqual(False-True, -1)
self.assertEqual(True*1, 1)
self.assertEqual(False*1, 0)
self.assertIsNot(False*1, False)
self.assertEqual(True/1, 1)
self.assertIsNot(True/1, True)
self.assertEqual(False/1, 0)
self.assertIsNot(False/1, False)
for b in False, True:
for i in 0, 1, 2:
self.assertEqual(b**i, int(b)**i)
self.assertIsNot(b**i, bool(int(b)**i))
for a in False, True:
for b in False, True:
self.assertIs(a&b, bool(int(a)&int(b)))
self.assertIs(a|b, bool(int(a)|int(b)))
self.assertIs(a^b, bool(int(a)^int(b)))
self.assertEqual(a&int(b), int(a)&int(b))
self.assertIsNot(a&int(b), bool(int(a)&int(b)))
self.assertEqual(a|int(b), int(a)|int(b))
self.assertIsNot(a|int(b), bool(int(a)|int(b)))
self.assertEqual(a^int(b), int(a)^int(b))
self.assertIsNot(a^int(b), bool(int(a)^int(b)))
self.assertEqual(int(a)&b, int(a)&int(b))
self.assertIsNot(int(a)&b, bool(int(a)&int(b)))
self.assertEqual(int(a)|b, int(a)|int(b))
self.assertIsNot(int(a)|b, bool(int(a)|int(b)))
self.assertEqual(int(a)^b, int(a)^int(b))
self.assertIsNot(int(a)^b, bool(int(a)^int(b)))
self.assertIs(1==1, True)
self.assertIs(1==0, False)
self.assertIs(0<1, True)
self.assertIs(1<0, False)
self.assertIs(0<=0, True)
self.assertIs(1<=0, False)
self.assertIs(1>0, True)
self.assertIs(1>1, False)
self.assertIs(1>=1, True)
self.assertIs(0>=1, False)
self.assertIs(0!=1, True)
self.assertIs(0!=0, False)
x = [1]
self.assertIs(x is x, True)
self.assertIs(x is not x, False)
self.assertIs(1 in x, True)
self.assertIs(0 in x, False)
self.assertIs(1 not in x, False)
self.assertIs(0 not in x, True)
x = {1: 2}
self.assertIs(x is x, True)
self.assertIs(x is not x, False)
self.assertIs(1 in x, True)
self.assertIs(0 in x, False)
self.assertIs(1 not in x, False)
self.assertIs(0 not in x, True)
self.assertIs(not True, False)
self.assertIs(not False, True)
def test_convert(self):
self.assertRaises(TypeError, bool, 42, 42)
self.assertIs(bool(10), True)
self.assertIs(bool(1), True)
self.assertIs(bool(-1), True)
self.assertIs(bool(0), False)
self.assertIs(bool("hello"), True)
self.assertIs(bool(""), False)
self.assertIs(bool(), False)
def test_hasattr(self):
self.assertIs(hasattr([], "append"), True)
self.assertIs(hasattr([], "wobble"), False)
def test_callable(self):
self.assertIs(callable(len), True)
self.assertIs(callable(1), False)
def test_isinstance(self):
self.assertIs(isinstance(True, bool), True)
self.assertIs(isinstance(False, bool), True)
self.assertIs(isinstance(True, int), True)
self.assertIs(isinstance(False, int), True)
self.assertIs(isinstance(1, bool), False)
self.assertIs(isinstance(0, bool), False)
def test_issubclass(self):
self.assertIs(issubclass(bool, int), True)
self.assertIs(issubclass(int, bool), False)
def test_haskey(self):
self.assertIs({}.has_key(1), False)
self.assertIs({1:1}.has_key(1), True)
def test_string(self):
self.assertIs("xyz".endswith("z"), True)
self.assertIs("xyz".endswith("x"), False)
self.assertIs("xyz0123".isalnum(), True)
self.assertIs("@#$%".isalnum(), False)
self.assertIs("xyz".isalpha(), True)
self.assertIs("@#$%".isalpha(), False)
self.assertIs("0123".isdigit(), True)
self.assertIs("xyz".isdigit(), False)
self.assertIs("xyz".islower(), True)
self.assertIs("XYZ".islower(), False)
self.assertIs(" ".isspace(), True)
self.assertIs("XYZ".isspace(), False)
self.assertIs("X".istitle(), True)
self.assertIs("x".istitle(), False)
self.assertIs("XYZ".isupper(), True)
self.assertIs("xyz".isupper(), False)
self.assertIs("xyz".startswith("x"), True)
self.assertIs("xyz".startswith("z"), False)
if test_support.have_unicode:
self.assertIs(unicode("xyz", 'ascii').endswith(unicode("z", 'ascii')), True)
self.assertIs(unicode("xyz", 'ascii').endswith(unicode("x", 'ascii')), False)
self.assertIs(unicode("xyz0123", 'ascii').isalnum(), True)
self.assertIs(unicode("@#$%", 'ascii').isalnum(), False)
self.assertIs(unicode("xyz", 'ascii').isalpha(), True)
self.assertIs(unicode("@#$%", 'ascii').isalpha(), False)
self.assertIs(unicode("0123", 'ascii').isdecimal(), True)
self.assertIs(unicode("xyz", 'ascii').isdecimal(), False)
self.assertIs(unicode("0123", 'ascii').isdigit(), True)
self.assertIs(unicode("xyz", 'ascii').isdigit(), False)
self.assertIs(unicode("xyz", 'ascii').islower(), True)
self.assertIs(unicode("XYZ", 'ascii').islower(), False)
self.assertIs(unicode("0123", 'ascii').isnumeric(), True)
self.assertIs(unicode("xyz", 'ascii').isnumeric(), False)
self.assertIs(unicode(" ", 'ascii').isspace(), True)
self.assertIs(unicode("XYZ", 'ascii').isspace(), False)
self.assertIs(unicode("X", 'ascii').istitle(), True)
self.assertIs(unicode("x", 'ascii').istitle(), False)
self.assertIs(unicode("XYZ", 'ascii').isupper(), True)
self.assertIs(unicode("xyz", 'ascii').isupper(), False)
self.assertIs(unicode("xyz", 'ascii').startswith(unicode("x", 'ascii')), True)
self.assertIs(unicode("xyz", 'ascii').startswith(unicode("z", 'ascii')), False)
def test_boolean(self):
self.assertEqual(True & 1, 1)
self.assert_(not isinstance(True & 1, bool))
self.assertIs(True & True, True)
self.assertEqual(True | 1, 1)
self.assert_(not isinstance(True | 1, bool))
self.assertIs(True | True, True)
self.assertEqual(True ^ 1, 0)
self.assert_(not isinstance(True ^ 1, bool))
self.assertIs(True ^ True, False)
def test_fileclosed(self):
try:
f = file(test_support.TESTFN, "w")
self.assertIs(f.closed, False)
f.close()
self.assertIs(f.closed, True)
finally:
os.remove(test_support.TESTFN)
def test_operator(self):
import operator
self.assertIs(operator.truth(0), False)
self.assertIs(operator.truth(1), True)
self.assertIs(operator.isCallable(0), False)
self.assertIs(operator.isCallable(len), True)
self.assertIs(operator.isNumberType(None), False)
self.assertIs(operator.isNumberType(0), True)
self.assertIs(operator.not_(1), False)
self.assertIs(operator.not_(0), True)
self.assertIs(operator.isSequenceType(0), False)
self.assertIs(operator.isSequenceType([]), True)
self.assertIs(operator.contains([], 1), False)
self.assertIs(operator.contains([1], 1), True)
self.assertIs(operator.isMappingType(1), False)
self.assertIs(operator.isMappingType({}), True)
self.assertIs(operator.lt(0, 0), False)
self.assertIs(operator.lt(0, 1), True)
self.assertIs(operator.is_(True, True), True)
self.assertIs(operator.is_(True, False), False)
self.assertIs(operator.is_not(True, True), False)
self.assertIs(operator.is_not(True, False), True)
def test_marshal(self):
import marshal
self.assertIs(marshal.loads(marshal.dumps(True)), True)
self.assertIs(marshal.loads(marshal.dumps(False)), False)
def test_pickle(self):
import pickle
self.assertIs(pickle.loads(pickle.dumps(True)), True)
self.assertIs(pickle.loads(pickle.dumps(False)), False)
self.assertIs(pickle.loads(pickle.dumps(True, True)), True)
self.assertIs(pickle.loads(pickle.dumps(False, True)), False)
def test_cpickle(self):
import cPickle
self.assertIs(cPickle.loads(cPickle.dumps(True)), True)
self.assertIs(cPickle.loads(cPickle.dumps(False)), False)
self.assertIs(cPickle.loads(cPickle.dumps(True, True)), True)
self.assertIs(cPickle.loads(cPickle.dumps(False, True)), False)
def test_mixedpickle(self):
import pickle, cPickle
self.assertIs(pickle.loads(cPickle.dumps(True)), True)
self.assertIs(pickle.loads(cPickle.dumps(False)), False)
self.assertIs(pickle.loads(cPickle.dumps(True, True)), True)
self.assertIs(pickle.loads(cPickle.dumps(False, True)), False)
self.assertIs(cPickle.loads(pickle.dumps(True)), True)
self.assertIs(cPickle.loads(pickle.dumps(False)), False)
self.assertIs(cPickle.loads(pickle.dumps(True, True)), True)
self.assertIs(cPickle.loads(pickle.dumps(False, True)), False)
def test_picklevalues(self):
import pickle, cPickle
# Test for specific backwards-compatible pickle values
self.assertEqual(pickle.dumps(True), "I01\n.")
self.assertEqual(pickle.dumps(False), "I00\n.")
self.assertEqual(cPickle.dumps(True), "I01\n.")
self.assertEqual(cPickle.dumps(False), "I00\n.")
self.assertEqual(pickle.dumps(True, True), "I01\n.")
self.assertEqual(pickle.dumps(False, True), "I00\n.")
self.assertEqual(cPickle.dumps(True, True), "I01\n.")
self.assertEqual(cPickle.dumps(False, True), "I00\n.")
def test_convert_to_bool(self):
# Verify that TypeError occurs when bad things are returned
# from __nonzero__(). This isn't really a bool test, but
# it's related.
check = lambda o: self.assertRaises(TypeError, bool, o)
class Foo(object):
def __nonzero__(self):
return self
check(Foo())
class Bar(object):
def __nonzero__(self):
return "Yes"
check(Bar())
class Baz(int):
def __nonzero__(self):
return self
check(Baz())
def test_main():
test_support.run_unittest(BoolTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_bsddb185.py ---
"""Tests for the bsddb185 module.
The file 185test.db found in Lib/test/ is for testing purposes with this
testing suite.
"""
from test.test_support import verbose, run_unittest, findfile
import unittest
import bsddb185
import anydbm
import whichdb
import os
import tempfile
import shutil
class Bsddb185Tests(unittest.TestCase):
def test_open_existing_hash(self):
# Verify we can open a file known to be a hash v2 file
db = bsddb185.hashopen(findfile("185test.db"))
self.assertEqual(db["1"], "1")
db.close()
def test_whichdb(self):
# Verify that whichdb correctly sniffs the known hash v2 file
self.assertEqual(whichdb.whichdb(findfile("185test.db")), "bsddb185")
def test_anydbm_create(self):
# Verify that anydbm.open does *not* create a bsddb185 file
tmpdir = tempfile.mkdtemp()
try:
dbfile = os.path.join(tmpdir, "foo.db")
anydbm.open(dbfile, "c").close()
ftype = whichdb.whichdb(dbfile)
self.assertNotEqual(ftype, "bsddb185")
finally:
shutil.rmtree(tmpdir)
def test_main():
run_unittest(Bsddb185Tests)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_bsddb3.py ---
# Test driver for bsddb package.
"""
Run all test cases.
"""
import sys
import unittest
from test.test_support import requires, verbose, run_suite
# When running as a script instead of within the regrtest framework, skip the
# requires test, since it's obvious we want to run them.
if __name__ <> '__main__':
requires('bsddb')
verbose = False
if 'verbose' in sys.argv:
verbose = True
sys.argv.remove('verbose')
if 'silent' in sys.argv: # take care of old flag, just in case
verbose = False
sys.argv.remove('silent')
def suite():
test_modules = [
'test_associate',
'test_basics',
'test_compat',
'test_dbobj',
'test_dbshelve',
'test_dbtables',
'test_env_close',
'test_get_none',
'test_join',
'test_lock',
'test_misc',
'test_queue',
'test_recno',
'test_thread',
]
alltests = unittest.TestSuite()
for name in test_modules:
module = __import__("bsddb.test."+name, globals(), locals(), name)
#print module,name
alltests.addTest(module.test_suite())
return alltests
# For invocation through regrtest
def test_main():
tests = suite()
run_suite(tests)
# For invocation as a script
if __name__ == '__main__':
from bsddb import db
print '-=' * 38
print db.DB_VERSION_STRING
print 'bsddb.db.version(): %s' % (db.version(),)
print 'bsddb.db.__version__: %s' % db.__version__
print 'bsddb.db.cvsid: %s' % db.cvsid
print 'python version: %s' % sys.version
print '-=' * 38
unittest.main(defaultTest='suite')
--- NEW FILE: test_bz2.py ---
#!/usr/bin/python
from test import test_support
from test.test_support import TESTFN
import unittest
from cStringIO import StringIO
import os
import popen2
import sys
import bz2
from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor
has_cmdline_bunzip2 = sys.platform not in ("win32", "os2emx", "riscos")
class BaseTest(unittest.TestCase):
"Base for other testcases."
TEXT = 'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:\ndaemon:x:2:2:daemon:/sbin:\nadm:x:3:4:adm:/var/adm:\nlp:x:4:7:lp:/var/spool/lpd:\nsync:x:5:0:sync:/sbin:/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/var/spool/mail:\nnews:x:9:13:news:/var/spool/news:\nuucp:x:10:14:uucp:/var/spool/uucp:\noperator:x:11:0:operator:/root:\ngames:x:12:100:games:/usr/games:\ngopher:x:13:30:gopher:/usr/lib/gopher-data:\nftp:x:14:50:FTP User:/var/ftp:/bin/bash\nnobody:x:65534:65534:Nobody:/home:\npostfix:x:100:101:postfix:/var/spool/postfix:\nniemeyer:x:500:500::/home/niemeyer:/bin/bash\npostgres:x:101:102:PostgreSQL Server:/var/lib/pgsql:/bin/bash\nmysql:x:102:103:MySQL server:/var/lib/mysql:/bin/bash\nwww:x:103:104::/var/www:/bin/false\n'
DATA = 'BZh91AY&SY.\xc8N\x18\x00\x01>_\x80\x00\x10@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe00\x01\x99\xaa\x00\xc0\x03F\x86\x8c#&\x83F\x9a\x03\x06\xa6\xd0\xa6\x93M\x0fQ\xa7\xa8\x06\x804hh\x12$\x11\xa4i4\xf14S\xd2<Q\xb5\x0fH\xd3\xd4\xdd\xd5\x87\xbb\xf8\x94\r\x8f\xafI\x12\xe1\xc9\xf8/E\x00pu\x89\x12]\xc9\xbbDL\nQ\x0e\t1\x12\xdf\xa0\xc0\x97\xac2O9\x89\x13\x94\x0e\x1c7\x0ed\x95I\x0c\xaaJ\xa4\x18L\x10\x05#\x9c\xaf\xba\xbc/\x97\x8a#C\xc8\xe1\x8cW\xf9\xe2\xd0\xd6M\xa7\x8bXa<e\x84t\xcbL\xb3\xa7\xd9\xcd\xd1\xcb\x84.\xaf\xb3\xab\xab\xad`n}\xa0lh\tE,\x8eZ\x15\x17VH>\x88\xe5\xcd9gd6\x0b\n\xe9\x9b\xd5\x8a\x99\xf7\x08.K\x8ev\xfb\xf7xw\xbb\xdf\xa1\x92\xf1\xdd|/";\xa2\xba\x9f\xd5\xb1#A\xb6\xf6\xb3o\xc9\xc5y\\\xebO\xe7\x85\x9a\xbc\xb6f8\x952\xd5\xd7"%\x89>V,\xf7\xa6z\xe2\x9f\xa3\xdf\x11\x11"\xd6E)I\xa9\x13^\xca\xf3r\xd0\x03U\x922\xf26\xec\xb6\xed\x8b\xc3U\x13\x9d\xc5\x170\xa4\xfa^\x92\xacDF\x8a\x97\xd6\x19\xfe\xdd\xb8\xbd\x1a\x9a\x19\xa3\x80ankR\x8b\xe5\xd83]\xa9\xc6\x08\x82f\xf6\xb9"6l$\xb8j@\xc0\x8a\xb0l1..\xbak\x83ls\x15\xbc\xf4\xc1\x13\xbe\xf8E\xb8\x9d\r\xa8\x9dk\x84\xd3n\xfa\xacQ\x07\xb1%y\xaav\xb4\x08\xe0z\x1b\x16\xf5\x04\xe9\xcc\xb9\x08z\x1en7.G\xfc]\xc9\x14\xe1B@\xbb!8`'
DATA_CRLF = 'BZh91AY&SY\xaez\xbbN\x00\x01H\xdf\x80\x00\x12@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe0@\x01\xbc\xc6`\x86*\x8d=M\xa9\x9a\x86\xd0L@\x0fI\xa6!\xa1\x13\xc8\x88jdi\x8d@\x03@\x1a\x1a\x0c\x0c\x83 \x00\xc4h2\x19\x01\x82D\x84e\t\xe8\x99\x89\x19\x1ah\x00\r\x1a\x11\xaf\x9b\x0fG\xf5(\x1b\x1f?\t\x12\xcf\xb5\xfc\x95E\x00ps\x89\x12^\xa4\xdd\xa2&\x05(\x87\x04\x98\x89u\xe40%\xb6\x19\'\x8c\xc4\x89\xca\x07\x0e\x1b!\x91UIFU%C\x994!DI\xd2\xfa\xf0\xf1N8W\xde\x13A\xf5\x9cr%?\x9f3;I45A\xd1\x8bT\xb1<l\xba\xcb_\xc00xY\x17r\x17\x88\x08\x08@\xa0\ry@\x10\x04$)`\xf2\xce\x89z\xb0s\xec\x9b.iW\x9d\x81\xb5-+t\x9f\x1a\'\x97dB\xf5x\xb5\xbe.[.\xd7\x0e\x81\xe7\x08\x1cN`\x88\x10\xca\x87\xc3!"\x80\x92R\xa1/\xd1\xc0\xe6mf\xac\xbd\x99\xcca\xb3\x8780>\xa4\xc7\x8d\x1a\\"\xad\xa1\xabyBg\x15\xb9l\x88\x88\x91k"\x94\xa4\xd4\x89\xae*\xa6\x0b\x10\x0c\xd6\xd4m\xe86\xec\xb5j\x8a\x86j\';\xca.\x01I\xf2\xaaJ\xe8\x88\x8cU+t3\xfb\x0c\n\xa33\x13r2\r\x16\xe0\xb3(\xbf\x1d\x83r\xe7M\xf0D\x1365\xd8\x88\xd3\xa4\x92\xcb2\x06\x04\\\xc1\xb0\xea//\xbek&\xd8\xe6+t\xe5\xa1\x13\xada\x16\xder5"w]\xa2i\xb7[\x97R \xe2IT\xcd;Z\x04dk4\xad\x8a\t\xd3\x81z\x10\xf1:^`\xab\x1f\xc5\xdc\x91N\x14$+\x9e\xae\xd3\x80'
if has_cmdline_bunzip2:
def decompress(self, data):
pop = popen2.Popen3("bunzip2", capturestderr=1)
pop.tochild.write(data)
pop.tochild.close()
ret = pop.fromchild.read()
pop.fromchild.close()
if pop.wait() != 0:
ret = bz2.decompress(data)
return ret
else:
# popen2.Popen3 doesn't exist on Windows, and even if it did, bunzip2
# isn't available to run.
def decompress(self, data):
return bz2.decompress(data)
class BZ2FileTest(BaseTest):
"Test MCRYPT type miscelaneous methods."
def setUp(self):
self.filename = TESTFN
def tearDown(self):
if os.path.isfile(self.filename):
os.unlink(self.filename)
def createTempFile(self, crlf=0):
f = open(self.filename, "wb")
if crlf:
data = self.DATA_CRLF
else:
data = self.DATA
f.write(data)
f.close()
def testRead(self):
# "Test BZ2File.read()"
self.createTempFile()
bz2f = BZ2File(self.filename)
self.assertEqual(bz2f.read(), self.TEXT)
bz2f.close()
def testReadChunk10(self):
# "Test BZ2File.read() in chunks of 10 bytes"
self.createTempFile()
bz2f = BZ2File(self.filename)
text = ''
while 1:
str = bz2f.read(10)
if not str:
break
text += str
self.assertEqual(text, text)
bz2f.close()
def testRead100(self):
# "Test BZ2File.read(100)"
self.createTempFile()
bz2f = BZ2File(self.filename)
self.assertEqual(bz2f.read(100), self.TEXT[:100])
bz2f.close()
def testReadLine(self):
# "Test BZ2File.readline()"
self.createTempFile()
bz2f = BZ2File(self.filename)
sio = StringIO(self.TEXT)
for line in sio.readlines():
self.assertEqual(bz2f.readline(), line)
bz2f.close()
def testReadLines(self):
# "Test BZ2File.readlines()"
self.createTempFile()
bz2f = BZ2File(self.filename)
sio = StringIO(self.TEXT)
self.assertEqual(bz2f.readlines(), sio.readlines())
bz2f.close()
def testIterator(self):
# "Test iter(BZ2File)"
self.createTempFile()
bz2f = BZ2File(self.filename)
sio = StringIO(self.TEXT)
self.assertEqual(list(iter(bz2f)), sio.readlines())
bz2f.close()
def testXReadLines(self):
# "Test BZ2File.xreadlines()"
self.createTempFile()
bz2f = BZ2File(self.filename)
sio = StringIO(self.TEXT)
self.assertEqual(list(bz2f.xreadlines()), sio.readlines())
bz2f.close()
def testUniversalNewlinesLF(self):
# "Test BZ2File.read() with universal newlines (\\n)"
self.createTempFile()
bz2f = BZ2File(self.filename, "rU")
self.assertEqual(bz2f.read(), self.TEXT)
self.assertEqual(bz2f.newlines, "\n")
bz2f.close()
def testUniversalNewlinesCRLF(self):
# "Test BZ2File.read() with universal newlines (\\r\\n)"
self.createTempFile(crlf=1)
bz2f = BZ2File(self.filename, "rU")
self.assertEqual(bz2f.read(), self.TEXT)
self.assertEqual(bz2f.newlines, "\r\n")
bz2f.close()
def testWrite(self):
# "Test BZ2File.write()"
bz2f = BZ2File(self.filename, "w")
bz2f.write(self.TEXT)
bz2f.close()
f = open(self.filename, 'rb')
self.assertEqual(self.decompress(f.read()), self.TEXT)
f.close()
def testWriteChunks10(self):
# "Test BZ2File.write() with chunks of 10 bytes"
bz2f = BZ2File(self.filename, "w")
n = 0
while 1:
str = self.TEXT[n*10:(n+1)*10]
if not str:
break
bz2f.write(str)
n += 1
bz2f.close()
f = open(self.filename, 'rb')
self.assertEqual(self.decompress(f.read()), self.TEXT)
f.close()
def testWriteLines(self):
# "Test BZ2File.writelines()"
bz2f = BZ2File(self.filename, "w")
sio = StringIO(self.TEXT)
bz2f.writelines(sio.readlines())
bz2f.close()
f = open(self.filename, 'rb')
self.assertEqual(self.decompress(f.read()), self.TEXT)
f.close()
def testSeekForward(self):
# "Test BZ2File.seek(150, 0)"
self.createTempFile()
bz2f = BZ2File(self.filename)
bz2f.seek(150)
self.assertEqual(bz2f.read(), self.TEXT[150:])
bz2f.close()
def testSeekBackwards(self):
# "Test BZ2File.seek(-150, 1)"
self.createTempFile()
bz2f = BZ2File(self.filename)
bz2f.read(500)
bz2f.seek(-150, 1)
self.assertEqual(bz2f.read(), self.TEXT[500-150:])
bz2f.close()
def testSeekBackwardsFromEnd(self):
# "Test BZ2File.seek(-150, 2)"
self.createTempFile()
bz2f = BZ2File(self.filename)
bz2f.seek(-150, 2)
self.assertEqual(bz2f.read(), self.TEXT[len(self.TEXT)-150:])
bz2f.close()
def testSeekPostEnd(self):
# "Test BZ2File.seek(150000)"
self.createTempFile()
bz2f = BZ2File(self.filename)
bz2f.seek(150000)
self.assertEqual(bz2f.tell(), len(self.TEXT))
self.assertEqual(bz2f.read(), "")
bz2f.close()
def testSeekPostEndTwice(self):
# "Test BZ2File.seek(150000) twice"
self.createTempFile()
bz2f = BZ2File(self.filename)
bz2f.seek(150000)
bz2f.seek(150000)
self.assertEqual(bz2f.tell(), len(self.TEXT))
self.assertEqual(bz2f.read(), "")
bz2f.close()
def testSeekPreStart(self):
# "Test BZ2File.seek(-150, 0)"
self.createTempFile()
bz2f = BZ2File(self.filename)
bz2f.seek(-150)
self.assertEqual(bz2f.tell(), 0)
self.assertEqual(bz2f.read(), self.TEXT)
bz2f.close()
def testOpenDel(self):
# "Test opening and deleting a file many times"
self.createTempFile()
for i in xrange(10000):
o = BZ2File(self.filename)
del o
def testOpenNonexistent(self):
# "Test opening a nonexistent file"
self.assertRaises(IOError, BZ2File, "/non/existent")
class BZ2CompressorTest(BaseTest):
def testCompress(self):
# "Test BZ2Compressor.compress()/flush()"
bz2c = BZ2Compressor()
data = bz2c.compress(self.TEXT)
data += bz2c.flush()
self.assertEqual(self.decompress(data), self.TEXT)
def testCompressChunks10(self):
# "Test BZ2Compressor.compress()/flush() with chunks of 10 bytes"
bz2c = BZ2Compressor()
n = 0
data = ''
while 1:
str = self.TEXT[n*10:(n+1)*10]
if not str:
break
data += bz2c.compress(str)
n += 1
data += bz2c.flush()
self.assertEqual(self.decompress(data), self.TEXT)
class BZ2DecompressorTest(BaseTest):
def testDecompress(self):
# "Test BZ2Decompressor.decompress()"
bz2d = BZ2Decompressor()
text = bz2d.decompress(self.DATA)
self.assertEqual(text, self.TEXT)
def testDecompressChunks10(self):
# "Test BZ2Decompressor.decompress() with chunks of 10 bytes"
bz2d = BZ2Decompressor()
text = ''
n = 0
while 1:
str = self.DATA[n*10:(n+1)*10]
if not str:
break
text += bz2d.decompress(str)
n += 1
self.assertEqual(text, self.TEXT)
def testDecompressUnusedData(self):
# "Test BZ2Decompressor.decompress() with unused data"
bz2d = BZ2Decompressor()
unused_data = "this is unused data"
text = bz2d.decompress(self.DATA+unused_data)
self.assertEqual(text, self.TEXT)
self.assertEqual(bz2d.unused_data, unused_data)
def testEOFError(self):
# "Calling BZ2Decompressor.decompress() after EOS must raise EOFError"
bz2d = BZ2Decompressor()
text = bz2d.decompress(self.DATA)
self.assertRaises(EOFError, bz2d.decompress, "anything")
class FuncTest(BaseTest):
"Test module functions"
def testCompress(self):
# "Test compress() function"
data = bz2.compress(self.TEXT)
self.assertEqual(self.decompress(data), self.TEXT)
def testDecompress(self):
# "Test decompress() function"
text = bz2.decompress(self.DATA)
self.assertEqual(text, self.TEXT)
def testDecompressEmpty(self):
# "Test decompress() function with empty string"
text = bz2.decompress("")
self.assertEqual(text, "")
def testDecompressIncomplete(self):
# "Test decompress() function with incomplete data"
self.assertRaises(ValueError, bz2.decompress, self.DATA[:-10])
def test_main():
test_support.run_unittest(
BZ2FileTest,
BZ2CompressorTest,
BZ2DecompressorTest,
FuncTest
)
if __name__ == '__main__':
test_main()
# vim:ts=4:sw=4
--- NEW FILE: test_codeccallbacks.py ---
import test.test_support, unittest
import sys, codecs, htmlentitydefs, unicodedata
class PosReturn:
# this can be used for configurable callbacks
def __init__(self):
self.pos = 0
def handle(self, exc):
oldpos = self.pos
realpos = oldpos
if realpos<0:
realpos = len(exc.object) + realpos
# if we don't advance this time, terminate on the next call
# otherwise we'd get an endless loop
if realpos <= exc.start:
self.pos = len(exc.object)
return (u"<?>", oldpos)
class CodecCallbackTest(unittest.TestCase):
def test_xmlcharrefreplace(self):
# replace unencodable characters which numeric character entities.
# For ascii, latin-1 and charmaps this is completely implemented
# in C and should be reasonably fast.
s = u"\u30b9\u30d1\u30e2 \xe4nd eggs"
self.assertEqual(
s.encode("ascii", "xmlcharrefreplace"),
"スパモ änd eggs"
)
self.assertEqual(
s.encode("latin-1", "xmlcharrefreplace"),
"スパモ \xe4nd eggs"
)
def test_xmlcharnamereplace(self):
# This time use a named character entity for unencodable
# characters, if one is available.
def xmlcharnamereplace(exc):
if not isinstance(exc, UnicodeEncodeError):
raise TypeError("don't know how to handle %r" % exc)
l = []
for c in exc.object[exc.start:exc.end]:
try:
l.append(u"&%s;" % htmlentitydefs.codepoint2name[ord(c)])
except KeyError:
l.append(u"&#%d;" % ord(c))
return (u"".join(l), exc.end)
codecs.register_error(
"test.xmlcharnamereplace", xmlcharnamereplace)
sin = u"\xab\u211c\xbb = \u2329\u1234\u20ac\u232a"
sout = "«ℜ» = ⟨ሴ€⟩"
self.assertEqual(sin.encode("ascii", "test.xmlcharnamereplace"), sout)
sout = "\xabℜ\xbb = ⟨ሴ€⟩"
self.assertEqual(sin.encode("latin-1", "test.xmlcharnamereplace"), sout)
sout = "\xabℜ\xbb = ⟨ሴ\xa4⟩"
self.assertEqual(sin.encode("iso-8859-15", "test.xmlcharnamereplace"), sout)
def test_uninamereplace(self):
# We're using the names from the unicode database this time,
# and we're doing "syntax highlighting" here, i.e. we include
# the replaced text in ANSI escape sequences. For this it is
# useful that the error handler is not called for every single
# unencodable character, but for a complete sequence of
# unencodable characters, otherwise we would output many
# unneccessary escape sequences.
def uninamereplace(exc):
if not isinstance(exc, UnicodeEncodeError):
raise TypeError("don't know how to handle %r" % exc)
l = []
for c in exc.object[exc.start:exc.end]:
l.append(unicodedata.name(c, u"0x%x" % ord(c)))
return (u"\033[1m%s\033[0m" % u", ".join(l), exc.end)
codecs.register_error(
"test.uninamereplace", uninamereplace)
sin = u"\xac\u1234\u20ac\u8000"
sout = "\033[1mNOT SIGN, ETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
self.assertEqual(sin.encode("ascii", "test.uninamereplace"), sout)
sout = "\xac\033[1mETHIOPIC SYLLABLE SEE, EURO SIGN, CJK UNIFIED IDEOGRAPH-8000\033[0m"
self.assertEqual(sin.encode("latin-1", "test.uninamereplace"), sout)
sout = "\xac\033[1mETHIOPIC SYLLABLE SEE\033[0m\xa4\033[1mCJK UNIFIED IDEOGRAPH-8000\033[0m"
self.assertEqual(sin.encode("iso-8859-15", "test.uninamereplace"), sout)
def test_backslashescape(self):
# Does the same as the "unicode-escape" encoding, but with different
# base encodings.
sin = u"a\xac\u1234\u20ac\u8000"
if sys.maxunicode > 0xffff:
sin += unichr(sys.maxunicode)
sout = "a\\xac\\u1234\\u20ac\\u8000"
if sys.maxunicode > 0xffff:
sout += "\\U%08x" % sys.maxunicode
self.assertEqual(sin.encode("ascii", "backslashreplace"), sout)
sout = "a\xac\\u1234\\u20ac\\u8000"
if sys.maxunicode > 0xffff:
sout += "\\U%08x" % sys.maxunicode
self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout)
sout = "a\xac\\u1234\xa4\\u8000"
if sys.maxunicode > 0xffff:
sout += "\\U%08x" % sys.maxunicode
self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout)
def test_relaxedutf8(self):
# This is the test for a decoding callback handler,
# that relaxes the UTF-8 minimal encoding restriction.
# A null byte that is encoded as "\xc0\x80" will be
# decoded as a null byte. All other illegal sequences
# will be handled strictly.
def relaxedutf8(exc):
if not isinstance(exc, UnicodeDecodeError):
raise TypeError("don't know how to handle %r" % exc)
if exc.object[exc.start:exc.end].startswith("\xc0\x80"):
return (u"\x00", exc.start+2) # retry after two bytes
else:
raise exc
codecs.register_error(
"test.relaxedutf8", relaxedutf8)
sin = "a\x00b\xc0\x80c\xc3\xbc\xc0\x80\xc0\x80"
sout = u"a\x00b\x00c\xfc\x00\x00"
self.assertEqual(sin.decode("utf-8", "test.relaxedutf8"), sout)
sin = "\xc0\x80\xc0\x81"
self.assertRaises(UnicodeError, sin.decode, "utf-8", "test.relaxedutf8")
def test_charmapencode(self):
# For charmap encodings the replacement string will be
# mapped through the encoding again. This means, that
# to be able to use e.g. the "replace" handler, the
# charmap has to have a mapping for "?".
charmap = dict([ (ord(c), 2*c.upper()) for c in "abcdefgh"])
sin = u"abc"
sout = "AABBCC"
self.assertEquals(codecs.charmap_encode(sin, "strict", charmap)[0], sout)
sin = u"abcA"
self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap)
charmap[ord("?")] = "XYZ"
sin = u"abcDEF"
sout = "AABBCCXYZXYZXYZ"
self.assertEquals(codecs.charmap_encode(sin, "replace", charmap)[0], sout)
charmap[ord("?")] = u"XYZ"
self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
charmap[ord("?")] = u"XYZ"
self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
def test_callbacks(self):
def handler1(exc):
if not isinstance(exc, UnicodeEncodeError) \
and not isinstance(exc, UnicodeDecodeError):
raise TypeError("don't know how to handle %r" % exc)
l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
return (u"[%s]" % u"".join(l), exc.end)
codecs.register_error("test.handler1", handler1)
def handler2(exc):
if not isinstance(exc, UnicodeDecodeError):
raise TypeError("don't know how to handle %r" % exc)
l = [u"<%d>" % ord(exc.object[pos]) for pos in xrange(exc.start, exc.end)]
return (u"[%s]" % u"".join(l), exc.end+1) # skip one character
codecs.register_error("test.handler2", handler2)
s = "\x00\x81\x7f\x80\xff"
self.assertEqual(
s.decode("ascii", "test.handler1"),
u"\x00[<129>]\x7f[<128>][<255>]"
)
self.assertEqual(
s.decode("ascii", "test.handler2"),
u"\x00[<129>][<128>]"
)
self.assertEqual(
"\\u3042\u3xxx".decode("unicode-escape", "test.handler1"),
u"\u3042[<92><117><51><120>]xx"
)
self.assertEqual(
"\\u3042\u3xx".decode("unicode-escape", "test.handler1"),
u"\u3042[<92><117><51><120><120>]"
)
self.assertEqual(
codecs.charmap_decode("abc", "test.handler1", {ord("a"): u"z"})[0],
u"z[<98>][<99>]"
)
self.assertEqual(
u"g\xfc\xdfrk".encode("ascii", "test.handler1"),
u"g[<252><223>]rk"
)
self.assertEqual(
u"g\xfc\xdf".encode("ascii", "test.handler1"),
u"g[<252><223>]"
)
def test_longstrings(self):
# test long strings to check for memory overflow problems
errors = [ "strict", "ignore", "replace", "xmlcharrefreplace", "backslashreplace"]
# register the handlers under different names,
# to prevent the codec from recognizing the name
for err in errors:
codecs.register_error("test." + err, codecs.lookup_error(err))
l = 1000
errors += [ "test." + err for err in errors ]
for uni in [ s*l for s in (u"x", u"\u3042", u"a\xe4") ]:
for enc in ("ascii", "latin-1", "iso-8859-1", "iso-8859-15", "utf-8", "utf-7", "utf-16"):
for err in errors:
try:
uni.encode(enc, err)
except UnicodeError:
pass
def check_exceptionobjectargs(self, exctype, args, msg):
# Test UnicodeError subclasses: construction, attribute assignment and __str__ conversion
# check with one missing argument
self.assertRaises(TypeError, exctype, *args[:-1])
# check with one argument too much
self.assertRaises(TypeError, exctype, *(args + ["too much"]))
# check with one argument of the wrong type
wrongargs = [ "spam", u"eggs", 42, 1.0, None ]
for i in xrange(len(args)):
for wrongarg in wrongargs:
if type(wrongarg) is type(args[i]):
continue
# build argument array
callargs = []
for j in xrange(len(args)):
if i==j:
callargs.append(wrongarg)
else:
callargs.append(args[i])
self.assertRaises(TypeError, exctype, *callargs)
# check with the correct number and type of arguments
exc = exctype(*args)
self.assertEquals(str(exc), msg)
def test_unicodeencodeerror(self):
self.check_exceptionobjectargs(
UnicodeEncodeError,
["ascii", u"g\xfcrk", 1, 2, "ouch"],
"'ascii' codec can't encode character u'\\xfc' in position 1: ouch"
)
self.check_exceptionobjectargs(
UnicodeEncodeError,
["ascii", u"g\xfcrk", 1, 4, "ouch"],
"'ascii' codec can't encode characters in position 1-3: ouch"
)
self.check_exceptionobjectargs(
UnicodeEncodeError,
["ascii", u"\xfcx", 0, 1, "ouch"],
"'ascii' codec can't encode character u'\\xfc' in position 0: ouch"
)
self.check_exceptionobjectargs(
UnicodeEncodeError,
["ascii", u"\u0100x", 0, 1, "ouch"],
"'ascii' codec can't encode character u'\\u0100' in position 0: ouch"
)
self.check_exceptionobjectargs(
UnicodeEncodeError,
["ascii", u"\uffffx", 0, 1, "ouch"],
"'ascii' codec can't encode character u'\\uffff' in position 0: ouch"
)
if sys.maxunicode > 0xffff:
self.check_exceptionobjectargs(
UnicodeEncodeError,
["ascii", u"\U00010000x", 0, 1, "ouch"],
"'ascii' codec can't encode character u'\\U00010000' in position 0: ouch"
)
def test_unicodedecodeerror(self):
self.check_exceptionobjectargs(
UnicodeDecodeError,
["ascii", "g\xfcrk", 1, 2, "ouch"],
"'ascii' codec can't decode byte 0xfc in position 1: ouch"
)
self.check_exceptionobjectargs(
UnicodeDecodeError,
["ascii", "g\xfcrk", 1, 3, "ouch"],
"'ascii' codec can't decode bytes in position 1-2: ouch"
)
def test_unicodetranslateerror(self):
self.check_exceptionobjectargs(
UnicodeTranslateError,
[u"g\xfcrk", 1, 2, "ouch"],
"can't translate character u'\\xfc' in position 1: ouch"
)
self.check_exceptionobjectargs(
UnicodeTranslateError,
[u"g\u0100rk", 1, 2, "ouch"],
"can't translate character u'\\u0100' in position 1: ouch"
)
self.check_exceptionobjectargs(
UnicodeTranslateError,
[u"g\uffffrk", 1, 2, "ouch"],
"can't translate character u'\\uffff' in position 1: ouch"
)
if sys.maxunicode > 0xffff:
self.check_exceptionobjectargs(
UnicodeTranslateError,
[u"g\U00010000rk", 1, 2, "ouch"],
"can't translate character u'\\U00010000' in position 1: ouch"
)
self.check_exceptionobjectargs(
UnicodeTranslateError,
[u"g\xfcrk", 1, 3, "ouch"],
"can't translate characters in position 1-2: ouch"
)
def test_badandgoodstrictexceptions(self):
# "strict" complains about a non-exception passed in
self.assertRaises(
TypeError,
codecs.strict_errors,
42
)
# "strict" complains about the wrong exception type
self.assertRaises(
Exception,
codecs.strict_errors,
Exception("ouch")
)
# If the correct exception is passed in, "strict" raises it
self.assertRaises(
UnicodeEncodeError,
codecs.strict_errors,
UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")
)
def test_badandgoodignoreexceptions(self):
# "ignore" complains about a non-exception passed in
self.assertRaises(
TypeError,
codecs.ignore_errors,
42
)
# "ignore" complains about the wrong exception type
self.assertRaises(
TypeError,
codecs.ignore_errors,
UnicodeError("ouch")
)
# If the correct exception is passed in, "ignore" returns an empty replacement
self.assertEquals(
codecs.ignore_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
(u"", 1)
)
self.assertEquals(
codecs.ignore_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
(u"", 1)
)
self.assertEquals(
codecs.ignore_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
(u"", 1)
)
def test_badandgoodreplaceexceptions(self):
# "replace" complains about a non-exception passed in
self.assertRaises(
TypeError,
codecs.replace_errors,
42
)
# "replace" complains about the wrong exception type
self.assertRaises(
TypeError,
codecs.replace_errors,
UnicodeError("ouch")
)
# With the correct exception, "ignore" returns an empty replacement
self.assertEquals(
codecs.replace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
(u"?", 1)
)
self.assertEquals(
codecs.replace_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
(u"\ufffd", 1)
)
self.assertEquals(
codecs.replace_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
(u"\ufffd", 1)
)
def test_badandgoodxmlcharrefreplaceexceptions(self):
# "xmlcharrefreplace" complains about a non-exception passed in
self.assertRaises(
TypeError,
codecs.xmlcharrefreplace_errors,
42
)
# "xmlcharrefreplace" complains about the wrong exception types
self.assertRaises(
TypeError,
codecs.xmlcharrefreplace_errors,
UnicodeError("ouch")
)
# "xmlcharrefreplace" can only be used for encoding
self.assertRaises(
TypeError,
codecs.xmlcharrefreplace_errors,
UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
)
self.assertRaises(
TypeError,
codecs.xmlcharrefreplace_errors,
UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
)
# Use the correct exception
self.assertEquals(
codecs.xmlcharrefreplace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
(u"&#%d;" % 0x3042, 1)
)
def test_badandgoodbackslashreplaceexceptions(self):
# "backslashreplace" complains about a non-exception passed in
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
42
)
# "backslashreplace" complains about the wrong exception types
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
UnicodeError("ouch")
)
# "backslashreplace" can only be used for encoding
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
)
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
)
# Use the correct exception
self.assertEquals(
codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
(u"\\u3042", 1)
)
self.assertEquals(
codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\x00", 0, 1, "ouch")),
(u"\\x00", 1)
)
self.assertEquals(
codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\xff", 0, 1, "ouch")),
(u"\\xff", 1)
)
self.assertEquals(
codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u0100", 0, 1, "ouch")),
(u"\\u0100", 1)
)
self.assertEquals(
codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\uffff", 0, 1, "ouch")),
(u"\\uffff", 1)
)
if sys.maxunicode>0xffff:
self.assertEquals(
codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U00010000", 0, 1, "ouch")),
(u"\\U00010000", 1)
)
self.assertEquals(
codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U0010ffff", 0, 1, "ouch")),
(u"\\U0010ffff", 1)
)
def test_badhandlerresults(self):
results = ( 42, u"foo", (1,2,3), (u"foo", 1, 3), (u"foo", None), (u"foo",), ("foo", 1, 3), ("foo", None), ("foo",) )
encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15")
for res in results:
codecs.register_error("test.badhandler", lambda: res)
for enc in encs:
self.assertRaises(
TypeError,
u"\u3042".encode,
enc,
"test.badhandler"
)
for (enc, bytes) in (
("ascii", "\xff"),
("utf-8", "\xff"),
("utf-7", "+x-")
):
self.assertRaises(
TypeError,
bytes.decode,
enc,
"test.badhandler"
)
def test_lookup(self):
self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
self.assertEquals(codecs.ignore_errors, codecs.lookup_error("ignore"))
self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
self.assertEquals(
codecs.xmlcharrefreplace_errors,
codecs.lookup_error("xmlcharrefreplace")
)
self.assertEquals(
codecs.backslashreplace_errors,
codecs.lookup_error("backslashreplace")
)
def test_unencodablereplacement(self):
def unencrepl(exc):
if isinstance(exc, UnicodeEncodeError):
return (u"\u4242", exc.end)
else:
raise TypeError("don't know how to handle %r" % exc)
codecs.register_error("test.unencreplhandler", unencrepl)
for enc in ("ascii", "iso-8859-1", "iso-8859-15"):
self.assertRaises(
UnicodeEncodeError,
u"\u4242".encode,
enc,
"test.unencreplhandler"
)
def test_badregistercall(self):
# enhance coverage of:
# Modules/_codecsmodule.c::register_error()
# Python/codecs.c::PyCodec_RegisterError()
self.assertRaises(TypeError, codecs.register_error, 42)
self.assertRaises(TypeError, codecs.register_error, "test.dummy", 42)
def test_unknownhandler(self):
# enhance coverage of:
# Modules/_codecsmodule.c::lookup_error()
self.assertRaises(LookupError, codecs.lookup_error, "test.unknown")
def test_xmlcharrefvalues(self):
# enhance coverage of:
# Python/codecs.c::PyCodec_XMLCharRefReplaceErrors()
# and inline implementations
v = (1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000)
if sys.maxunicode>=100000:
v += (100000, 500000, 1000000)
s = u"".join([unichr(x) for x in v])
codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors)
for enc in ("ascii", "iso-8859-15"):
for err in ("xmlcharrefreplace", "test.xmlcharrefreplace"):
s.encode(enc, err)
def test_decodehelper(self):
# enhance coverage of:
# Objects/unicodeobject.c::unicode_decode_call_errorhandler()
# and callers
self.assertRaises(LookupError, "\xff".decode, "ascii", "test.unknown")
def baddecodereturn1(exc):
return 42
codecs.register_error("test.baddecodereturn1", baddecodereturn1)
self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn1")
self.assertRaises(TypeError, "\\".decode, "unicode-escape", "test.baddecodereturn1")
self.assertRaises(TypeError, "\\x0".decode, "unicode-escape", "test.baddecodereturn1")
self.assertRaises(TypeError, "\\x0y".decode, "unicode-escape", "test.baddecodereturn1")
self.assertRaises(TypeError, "\\Uffffeeee".decode, "unicode-escape", "test.baddecodereturn1")
self.assertRaises(TypeError, "\\uyyyy".decode, "raw-unicode-escape", "test.baddecodereturn1")
def baddecodereturn2(exc):
return (u"?", None)
codecs.register_error("test.baddecodereturn2", baddecodereturn2)
self.assertRaises(TypeError, "\xff".decode, "ascii", "test.baddecodereturn2")
handler = PosReturn()
codecs.register_error("test.posreturn", handler.handle)
# Valid negative position
handler.pos = -1
self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0")
# Valid negative position
handler.pos = -2
self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?><?>")
# Negative position out of bounds
handler.pos = -3
self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn")
# Valid positive position
handler.pos = 1
self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>0")
# Largest valid positive position (one beyond end of input
handler.pos = 2
self.assertEquals("\xff0".decode("ascii", "test.posreturn"), u"<?>")
# Invalid positive position
handler.pos = 3
self.assertRaises(IndexError, "\xff0".decode, "ascii", "test.posreturn")
# Restart at the "0"
handler.pos = 6
self.assertEquals("\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), u"<?>0")
class D(dict):
def __getitem__(self, key):
raise ValueError
self.assertRaises(UnicodeError, codecs.charmap_decode, "\xff", "strict", {0xff: None})
self.assertRaises(ValueError, codecs.charmap_decode, "\xff", "strict", D())
self.assertRaises(TypeError, codecs.charmap_decode, "\xff", "strict", {0xff: sys.maxunicode+1})
def test_encodehelper(self):
# enhance coverage of:
# Objects/unicodeobject.c::unicode_encode_call_errorhandler()
# and callers
self.assertRaises(LookupError, u"\xff".encode, "ascii", "test.unknown")
def badencodereturn1(exc):
return 42
codecs.register_error("test.badencodereturn1", badencodereturn1)
self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn1")
def badencodereturn2(exc):
return (u"?", None)
codecs.register_error("test.badencodereturn2", badencodereturn2)
self.assertRaises(TypeError, u"\xff".encode, "ascii", "test.badencodereturn2")
handler = PosReturn()
codecs.register_error("test.posreturn", handler.handle)
# Valid negative position
handler.pos = -1
self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0")
# Valid negative position
handler.pos = -2
self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?><?>")
# Negative position out of bounds
handler.pos = -3
self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn")
# Valid positive position
handler.pos = 1
self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>0")
# Largest valid positive position (one beyond end of input
handler.pos = 2
self.assertEquals(u"\xff0".encode("ascii", "test.posreturn"), "<?>")
# Invalid positive position
handler.pos = 3
self.assertRaises(IndexError, u"\xff0".encode, "ascii", "test.posreturn")
handler.pos = 0
class D(dict):
def __getitem__(self, key):
raise ValueError
for err in ("strict", "replace", "xmlcharrefreplace", "backslashreplace", "test.posreturn"):
self.assertRaises(UnicodeError, codecs.charmap_encode, u"\xff", err, {0xff: None})
self.assertRaises(ValueError, codecs.charmap_encode, u"\xff", err, D())
self.assertRaises(TypeError, codecs.charmap_encode, u"\xff", err, {0xff: 300})
def test_translatehelper(self):
# enhance coverage of:
# Objects/unicodeobject.c::unicode_encode_call_errorhandler()
# and callers
# (Unfortunately the errors argument is not directly accessible
# from Python, so we can't test that much)
class D(dict):
def __getitem__(self, key):
raise ValueError
self.assertRaises(ValueError, u"\xff".translate, D())
self.assertRaises(TypeError, u"\xff".translate, {0xff: sys.maxunicode+1})
self.assertRaises(TypeError, u"\xff".translate, {0xff: ()})
def test_bug828737(self):
charmap = {
ord("&"): u"&",
ord("<"): u"<",
ord(">"): u">",
ord('"'): u""",
}
for n in (1, 10, 100, 1000):
text = u'abc<def>ghi'*n
text.translate(charmap)
def test_main():
test.test_support.run_unittest(CodecCallbackTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecencodings_cn.py ---
#!/usr/bin/env python
#
# test_codecencodings_cn.py
# Codec encoding tests for PRC encodings.
#
# $CJKCodecs: test_codecencodings_cn.py,v 1.1 2003/12/19 03:00:05 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class Test_GB2312(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'gb2312'
tstring = test_multibytecodec_support.load_teststring('gb2312')
codectests = (
# invalid bytes
("abc\x81\x81\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x81\x81\xc1\xc4", "replace", u"abc\ufffd\u804a"),
("abc\x81\x81\xc1\xc4\xc8", "replace", u"abc\ufffd\u804a\ufffd"),
("abc\x81\x81\xc1\xc4", "ignore", u"abc\u804a"),
("\xc1\x64", "strict", None),
)
class Test_GBK(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'gbk'
tstring = test_multibytecodec_support.load_teststring('gbk')
codectests = (
# invalid bytes
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\u804a"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\u804a\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\u804a"),
("\x83\x34\x83\x31", "strict", None),
)
class Test_GB18030(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'gb18030'
tstring = test_multibytecodec_support.load_teststring('gb18030')
codectests = (
# invalid bytes
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\u804a"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\u804a\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\u804a"),
("abc\x84\x39\x84\x39\xc1\xc4", "replace", u"abc\ufffd\u804a"),
)
has_iso10646 = True
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Test_GB2312))
suite.addTest(unittest.makeSuite(Test_GBK))
suite.addTest(unittest.makeSuite(Test_GB18030))
test_support.run_suite(suite)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecencodings_jp.py ---
#!/usr/bin/env python
#
# test_codecencodings_jp.py
# Codec encoding tests for Japanese encodings.
#
# $CJKCodecs: test_codecencodings_jp.py,v 1.2 2004/01/06 09:25:37 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class Test_CP932(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'cp932'
tstring = test_multibytecodec_support.load_teststring('shift_jis')
codectests = (
# invalid bytes
("abc\x81\x00\x81\x00\x82\x84", "strict", None),
("abc\xf8", "strict", None),
("abc\x81\x00\x82\x84", "replace", u"abc\ufffd\uff44"),
("abc\x81\x00\x82\x84\x88", "replace", u"abc\ufffd\uff44\ufffd"),
("abc\x81\x00\x82\x84", "ignore", u"abc\uff44"),
# sjis vs cp932
("\\\x7e", "replace", u"\\\x7e"),
("\x81\x5f\x81\x61\x81\x7c", "replace", u"\uff3c\u2225\uff0d"),
)
class Test_EUC_JISX0213(test_multibytecodec_support.TestBase,
unittest.TestCase):
encoding = 'euc_jisx0213'
tstring = test_multibytecodec_support.load_teststring('euc_jisx0213')
codectests = (
# invalid bytes
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\u7956"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\u7956\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\u7956"),
("abc\x8f\x83\x83", "replace", u"abc\ufffd"),
("\xc1\x64", "strict", None),
("\xa1\xc0", "strict", u"\uff3c"),
)
xmlcharnametest = (
u"\xab\u211c\xbb = \u2329\u1234\u232a",
"\xa9\xa8ℜ\xa9\xb2 = ⟨ሴ⟩"
)
eucjp_commontests = (
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\u7956"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\u7956\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\u7956"),
("abc\x8f\x83\x83", "replace", u"abc\ufffd"),
("\xc1\x64", "strict", None),
)
class Test_EUC_JP_COMPAT(test_multibytecodec_support.TestBase,
unittest.TestCase):
encoding = 'euc_jp'
tstring = test_multibytecodec_support.load_teststring('euc_jp')
codectests = eucjp_commontests + (
("\xa1\xc0\\", "strict", u"\uff3c\\"),
(u"\xa5", "strict", "\x5c"),
(u"\u203e", "strict", "\x7e"),
)
class Test_EUC_JP_STRICT(test_multibytecodec_support.TestBase,
unittest.TestCase):
encoding = 'euc_jp_strict'
tstring = test_multibytecodec_support.load_teststring('euc_jp')
codectests = eucjp_commontests + (
("\xa1\xc0\\", "strict", u"\\\\"),
(u"\xa5", "strict", None),
(u"\u203e", "strict", None),
)
shiftjis_commonenctests = (
("abc\x80\x80\x82\x84", "strict", None),
("abc\xf8", "strict", None),
("abc\x80\x80\x82\x84", "replace", u"abc\ufffd\uff44"),
("abc\x80\x80\x82\x84\x88", "replace", u"abc\ufffd\uff44\ufffd"),
("abc\x80\x80\x82\x84def", "ignore", u"abc\uff44def"),
)
class Test_SJIS_COMPAT(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'shift_jis'
tstring = test_multibytecodec_support.load_teststring('shift_jis')
codectests = shiftjis_commonenctests + (
("\\\x7e", "strict", u"\\\x7e"),
("\x81\x5f\x81\x61\x81\x7c", "strict", u"\uff3c\u2016\u2212"),
)
class Test_SJIS_STRICT(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'shift_jis_strict'
tstring = test_multibytecodec_support.load_teststring('shift_jis')
codectests = shiftjis_commonenctests + (
("\\\x7e", "replace", u"\xa5\u203e"),
("\x81\x5f\x81\x61\x81\x7c", "replace", u"\x5c\u2016\u2212"),
)
class Test_SJISX0213(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'shift_jisx0213'
tstring = test_multibytecodec_support.load_teststring('shift_jisx0213')
codectests = (
# invalid bytes
("abc\x80\x80\x82\x84", "strict", None),
("abc\xf8", "strict", None),
("abc\x80\x80\x82\x84", "replace", u"abc\ufffd\uff44"),
("abc\x80\x80\x82\x84\x88", "replace", u"abc\ufffd\uff44\ufffd"),
("abc\x80\x80\x82\x84def", "ignore", u"abc\uff44def"),
# sjis vs cp932
("\\\x7e", "replace", u"\xa5\u203e"),
("\x81\x5f\x81\x61\x81\x7c", "replace", u"\x5c\u2016\u2212"),
)
xmlcharnametest = (
u"\xab\u211c\xbb = \u2329\u1234\u232a",
"\x85Gℜ\x85Q = ⟨ሴ⟩"
)
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Test_CP932))
suite.addTest(unittest.makeSuite(Test_EUC_JISX0213))
suite.addTest(unittest.makeSuite(Test_EUC_JP_COMPAT))
suite.addTest(unittest.makeSuite(Test_SJIS_COMPAT))
if test_multibytecodec_support.__cjkcodecs__:
suite.addTest(unittest.makeSuite(Test_EUC_JP_STRICT))
suite.addTest(unittest.makeSuite(Test_SJIS_STRICT))
suite.addTest(unittest.makeSuite(Test_SJISX0213))
test_support.run_suite(suite)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecencodings_kr.py ---
#!/usr/bin/env python
#
# test_codecencodings_kr.py
# Codec encoding tests for ROK encodings.
#
# $CJKCodecs: test_codecencodings_kr.py,v 1.1 2003/12/19 03:00:06 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class Test_CP949(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'cp949'
tstring = test_multibytecodec_support.load_teststring('cp949')
codectests = (
# invalid bytes
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\uc894"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\uc894\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\uc894"),
)
class Test_EUCKR(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'euc_kr'
tstring = test_multibytecodec_support.load_teststring('euc_kr')
codectests = (
# invalid bytes
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\uc894"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\uc894\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\uc894"),
)
class Test_JOHAB(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'johab'
tstring = test_multibytecodec_support.load_teststring('johab')
codectests = (
# invalid bytes
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\ucd27"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\ucd27\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\ucd27"),
)
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Test_CP949))
suite.addTest(unittest.makeSuite(Test_EUCKR))
suite.addTest(unittest.makeSuite(Test_JOHAB))
test_support.run_suite(suite)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecencodings_tw.py ---
#!/usr/bin/env python
#
# test_codecencodings_tw.py
# Codec encoding tests for ROC encodings.
#
# $CJKCodecs: test_codecencodings_tw.py,v 1.1 2003/12/19 03:00:06 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class Test_Big5(test_multibytecodec_support.TestBase, unittest.TestCase):
encoding = 'big5'
tstring = test_multibytecodec_support.load_teststring('big5')
codectests = (
# invalid bytes
("abc\x80\x80\xc1\xc4", "strict", None),
("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\u8b10"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\u8b10\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\u8b10"),
)
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Test_Big5))
test_support.run_suite(suite)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecmaps_cn.py ---
#!/usr/bin/env python
#
# test_codecmaps_cn.py
# Codec mapping tests for PRC encodings
#
# $CJKCodecs: test_codecmaps_cn.py,v 1.2 2004/01/17 12:47:19 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class TestGB2312Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'gb2312'
mapfilename = 'EUC-CN.TXT'
mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-CN.TXT'
class TestGBKMap(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'gbk'
mapfilename = 'CP936.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/' \
'MICSFT/WINDOWS/CP936.TXT'
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestGB2312Map))
suite.addTest(unittest.makeSuite(TestGBKMap))
test_support.run_suite(suite)
test_multibytecodec_support.register_skip_expected(TestGB2312Map, TestGBKMap)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecmaps_jp.py ---
#!/usr/bin/env python
#
# test_codecmaps_jp.py
# Codec mapping tests for Japanese encodings
#
# $CJKCodecs: test_codecmaps_jp.py,v 1.2 2004/01/17 12:47:19 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class TestCP932Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'cp932'
mapfilename = 'CP932.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/' \
'WINDOWS/CP932.TXT'
supmaps = [
('\x80', u'\u0080'),
('\xa0', u'\uf8f0'),
('\xfd', u'\uf8f1'),
('\xfe', u'\uf8f2'),
('\xff', u'\uf8f3'),
]
for i in range(0xa1, 0xe0):
supmaps.append((chr(i), unichr(i+0xfec0)))
class TestEUCJPCOMPATMap(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'euc_jp'
mapfilename = 'EUC-JP.TXT'
mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-JP.TXT'
class TestSJISCOMPATMap(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'shift_jis'
mapfilename = 'SHIFTJIS.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/OBSOLETE' \
'/EASTASIA/JIS/SHIFTJIS.TXT'
pass_enctest = [
('\x81_', u'\\'),
]
pass_dectest = [
('\\', u'\xa5'),
('~', u'\u203e'),
('\x81_', u'\\'),
]
class TestSJISSTRICTMap(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'shift_jis_strict'
mapfilename = 'SHIFTJIS.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/OBSOLETE' \
'/EASTASIA/JIS/SHIFTJIS.TXT'
class TestEUCJISX0213Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'euc_jisx0213'
mapfilename = 'EUC-JISX0213.TXT'
mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-JISX0213.TXT'
class TestSJISX0213Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'shift_jisx0213'
mapfilename = 'SHIFT_JISX0213.TXT'
mapfileurl = 'http://people.freebsd.org/~perky/i18n/SHIFT_JISX0213.TXT'
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestCP932Map))
suite.addTest(unittest.makeSuite(TestEUCJPCOMPATMap))
suite.addTest(unittest.makeSuite(TestSJISCOMPATMap))
if test_multibytecodec_support.__cjkcodecs__:
suite.addTest(unittest.makeSuite(TestSJISSTRICTMap))
suite.addTest(unittest.makeSuite(TestEUCJISX0213Map))
suite.addTest(unittest.makeSuite(TestSJISX0213Map))
test_support.run_suite(suite)
test_multibytecodec_support.register_skip_expected(TestCP932Map,
TestEUCJPCOMPATMap, TestSJISCOMPATMap, TestEUCJISX0213Map,
TestSJISX0213Map)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecmaps_kr.py ---
#!/usr/bin/env python
#
# test_codecmaps_kr.py
# Codec mapping tests for ROK encodings
#
# $CJKCodecs: test_codecmaps_kr.py,v 1.2 2004/01/17 12:47:19 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class TestCP949Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'cp949'
mapfilename = 'CP949.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT' \
'/WINDOWS/CP949.TXT'
class TestEUCKRMap(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'euc_kr'
mapfilename = 'EUC-KR.TXT'
mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-KR.TXT'
class TestJOHABMap(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'johab'
mapfilename = 'JOHAB.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/' \
'KSC/JOHAB.TXT'
# KS X 1001 standard assigned 0x5c as WON SIGN.
# but, in early 90s that is the only era used johab widely,
# the most softwares implements it as REVERSE SOLIDUS.
# So, we ignore the standard here.
pass_enctest = [('\\', u'\u20a9')]
pass_dectest = [('\\', u'\u20a9')]
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestCP949Map))
suite.addTest(unittest.makeSuite(TestEUCKRMap))
suite.addTest(unittest.makeSuite(TestJOHABMap))
test_support.run_suite(suite)
test_multibytecodec_support.register_skip_expected(TestCP949Map,
TestEUCKRMap, TestJOHABMap)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_codecmaps_tw.py ---
#!/usr/bin/env python
#
# test_codecmaps_tw.py
# Codec mapping tests for ROC encodings
#
# $CJKCodecs: test_codecmaps_tw.py,v 1.2 2004/01/17 12:47:19 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest
class TestBIG5Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'big5'
mapfilename = 'BIG5.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/OBSOLETE/' \
'EASTASIA/OTHER/BIG5.TXT'
class TestCP950Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'cp950'
mapfilename = 'CP950.TXT'
mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/' \
'WINDOWS/CP950.TXT'
pass_enctest = [
('\xa2\xcc', u'\u5341'),
('\xa2\xce', u'\u5345'),
]
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestBIG5Map))
suite.addTest(unittest.makeSuite(TestCP950Map))
test_support.run_suite(suite)
test_multibytecodec_support.register_skip_expected(TestBIG5Map, TestCP950Map)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_colorsys.py ---
import unittest, test.test_support
import colorsys
def frange(start, stop, step):
while start <= stop:
yield start
start += stop
class ColorsysTest(unittest.TestCase):
def assertTripleEqual(self, tr1, tr2):
self.assertEqual(len(tr1), 3)
self.assertEqual(len(tr2), 3)
self.assertAlmostEqual(tr1[0], tr2[0])
self.assertAlmostEqual(tr1[1], tr2[1])
self.assertAlmostEqual(tr1[2], tr2[2])
def test_hsv_roundtrip(self):
for r in frange(0.0, 1.0, 0.2):
for g in frange(0.0, 1.0, 0.2):
for b in frange(0.0, 1.0, 0.2):
rgb = (r, g, b)
self.assertTripleEqual(
rgb,
colorsys.hsv_to_rgb(*colorsys.rgb_to_hsv(*rgb))
)
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def test_hls_roundtrip(self):
for r in frange(0.0, 1.0, 0.2):
for g in frange(0.0, 1.0, 0.2):
for b in frange(0.0, 1.0, 0.2):
rgb = (r, g, b)
self.assertTripleEqual(
rgb,
colorsys.hls_to_rgb(*colorsys.rgb_to_hls(*rgb))
)
def test_hls_values(self):
values = [
# rgb, hls
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 0.5, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 0.5, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 0.5, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 0.5, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 0.5, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 0.5, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 1.0, 0.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.5, 0.0)), # grey
]
for (rgb, hls) in values:
self.assertTripleEqual(hls, colorsys.rgb_to_hls(*rgb))
self.assertTripleEqual(rgb, colorsys.hls_to_rgb(*hls))
def test_main():
test.test_support.run_unittest(ColorsysTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_copy.py ---
"""Unit tests for the copy module."""
import sys
import copy
import copy_reg
import unittest
from test import test_support
class TestCopy(unittest.TestCase):
# Attempt full line coverage of copy.py from top to bottom
def test_exceptions(self):
self.assert_(copy.Error is copy.error)
self.assert_(issubclass(copy.Error, Exception))
# The copy() method
def test_copy_basic(self):
x = 42
y = copy.copy(x)
self.assertEqual(x, y)
def test_copy_copy(self):
class C(object):
def __init__(self, foo):
self.foo = foo
def __copy__(self):
return C(self.foo)
x = C(42)
y = copy.copy(x)
self.assertEqual(y.__class__, x.__class__)
self.assertEqual(y.foo, x.foo)
def test_copy_registry(self):
class C(object):
def __new__(cls, foo):
obj = object.__new__(cls)
obj.foo = foo
return obj
def pickle_C(obj):
return (C, (obj.foo,))
x = C(42)
self.assertRaises(TypeError, copy.copy, x)
copy_reg.pickle(C, pickle_C, C)
y = copy.copy(x)
def test_copy_reduce_ex(self):
class C(object):
def __reduce_ex__(self, proto):
return ""
def __reduce__(self):
raise test_support.TestFailed, "shouldn't call this"
x = C()
y = copy.copy(x)
self.assert_(y is x)
def test_copy_reduce(self):
class C(object):
def __reduce__(self):
return ""
x = C()
y = copy.copy(x)
self.assert_(y is x)
def test_copy_cant(self):
class C(object):
def __getattribute__(self, name):
if name.startswith("__reduce"):
raise AttributeError, name
return object.__getattribute__(self, name)
x = C()
self.assertRaises(copy.Error, copy.copy, x)
# Type-specific _copy_xxx() methods
def test_copy_atomic(self):
class Classic:
pass
class NewStyle(object):
pass
def f():
pass
tests = [None, 42, 2L**100, 3.14, True, False, 1j,
"hello", u"hello\u1234", f.func_code,
NewStyle, xrange(10), Classic, max]
for x in tests:
self.assert_(copy.copy(x) is x, repr(x))
def test_copy_list(self):
x = [1, 2, 3]
self.assertEqual(copy.copy(x), x)
def test_copy_tuple(self):
x = (1, 2, 3)
self.assertEqual(copy.copy(x), x)
def test_copy_dict(self):
x = {"foo": 1, "bar": 2}
self.assertEqual(copy.copy(x), x)
def test_copy_inst_vanilla(self):
class C:
def __init__(self, foo):
self.foo = foo
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C(42)
self.assertEqual(copy.copy(x), x)
def test_copy_inst_copy(self):
class C:
def __init__(self, foo):
self.foo = foo
def __copy__(self):
return C(self.foo)
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C(42)
self.assertEqual(copy.copy(x), x)
def test_copy_inst_getinitargs(self):
class C:
def __init__(self, foo):
self.foo = foo
def __getinitargs__(self):
return (self.foo,)
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C(42)
self.assertEqual(copy.copy(x), x)
def test_copy_inst_getstate(self):
class C:
def __init__(self, foo):
self.foo = foo
def __getstate__(self):
return {"foo": self.foo}
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C(42)
self.assertEqual(copy.copy(x), x)
def test_copy_inst_setstate(self):
class C:
def __init__(self, foo):
self.foo = foo
def __setstate__(self, state):
self.foo = state["foo"]
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C(42)
self.assertEqual(copy.copy(x), x)
def test_copy_inst_getstate_setstate(self):
class C:
def __init__(self, foo):
self.foo = foo
def __getstate__(self):
return self.foo
def __setstate__(self, state):
self.foo = state
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C(42)
self.assertEqual(copy.copy(x), x)
# The deepcopy() method
def test_deepcopy_basic(self):
x = 42
y = copy.deepcopy(x)
self.assertEqual(y, x)
def test_deepcopy_memo(self):
# Tests of reflexive objects are under type-specific sections below.
# This tests only repetitions of objects.
x = []
x = [x, x]
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y is not x)
self.assert_(y[0] is not x[0])
self.assert_(y[0] is y[1])
def test_deepcopy_issubclass(self):
# XXX Note: there's no way to test the TypeError coming out of
# issubclass() -- this can only happen when an extension
# module defines a "type" that doesn't formally inherit from
# type.
class Meta(type):
pass
class C:
__metaclass__ = Meta
self.assertEqual(copy.deepcopy(C), C)
def test_deepcopy_deepcopy(self):
class C(object):
def __init__(self, foo):
self.foo = foo
def __deepcopy__(self, memo=None):
return C(self.foo)
x = C(42)
y = copy.deepcopy(x)
self.assertEqual(y.__class__, x.__class__)
self.assertEqual(y.foo, x.foo)
def test_deepcopy_registry(self):
class C(object):
def __new__(cls, foo):
obj = object.__new__(cls)
obj.foo = foo
return obj
def pickle_C(obj):
return (C, (obj.foo,))
x = C(42)
self.assertRaises(TypeError, copy.deepcopy, x)
copy_reg.pickle(C, pickle_C, C)
y = copy.deepcopy(x)
def test_deepcopy_reduce_ex(self):
class C(object):
def __reduce_ex__(self, proto):
return ""
def __reduce__(self):
raise test_support.TestFailed, "shouldn't call this"
x = C()
y = copy.deepcopy(x)
self.assert_(y is x)
def test_deepcopy_reduce(self):
class C(object):
def __reduce__(self):
return ""
x = C()
y = copy.deepcopy(x)
self.assert_(y is x)
def test_deepcopy_cant(self):
class C(object):
def __getattribute__(self, name):
if name.startswith("__reduce"):
raise AttributeError, name
return object.__getattribute__(self, name)
x = C()
self.assertRaises(copy.Error, copy.deepcopy, x)
# Type-specific _deepcopy_xxx() methods
def test_deepcopy_atomic(self):
class Classic:
pass
class NewStyle(object):
pass
def f():
pass
tests = [None, 42, 2L**100, 3.14, True, False, 1j,
"hello", u"hello\u1234", f.func_code,
NewStyle, xrange(10), Classic, max]
for x in tests:
self.assert_(copy.deepcopy(x) is x, repr(x))
def test_deepcopy_list(self):
x = [[1, 2], 3]
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(x is not y)
self.assert_(x[0] is not y[0])
def test_deepcopy_reflexive_list(self):
x = []
x.append(x)
y = copy.deepcopy(x)
self.assertRaises(RuntimeError, cmp, y, x)
self.assert_(y is not x)
self.assert_(y[0] is y)
self.assertEqual(len(y), 1)
def test_deepcopy_tuple(self):
x = ([1, 2], 3)
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(x is not y)
self.assert_(x[0] is not y[0])
def test_deepcopy_reflexive_tuple(self):
x = ([],)
x[0].append(x)
y = copy.deepcopy(x)
self.assertRaises(RuntimeError, cmp, y, x)
self.assert_(y is not x)
self.assert_(y[0] is not x[0])
self.assert_(y[0][0] is y)
def test_deepcopy_dict(self):
x = {"foo": [1, 2], "bar": 3}
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(x is not y)
self.assert_(x["foo"] is not y["foo"])
def test_deepcopy_reflexive_dict(self):
x = {}
x['foo'] = x
y = copy.deepcopy(x)
self.assertRaises(RuntimeError, cmp, y, x)
self.assert_(y is not x)
self.assert_(y['foo'] is y)
self.assertEqual(len(y), 1)
def test_deepcopy_keepalive(self):
memo = {}
x = 42
y = copy.deepcopy(x, memo)
self.assert_(memo[id(x)] is x)
def test_deepcopy_inst_vanilla(self):
class C:
def __init__(self, foo):
self.foo = foo
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y.foo is not x.foo)
def test_deepcopy_inst_deepcopy(self):
class C:
def __init__(self, foo):
self.foo = foo
def __deepcopy__(self, memo):
return C(copy.deepcopy(self.foo, memo))
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y is not x)
self.assert_(y.foo is not x.foo)
def test_deepcopy_inst_getinitargs(self):
class C:
def __init__(self, foo):
self.foo = foo
def __getinitargs__(self):
return (self.foo,)
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y is not x)
self.assert_(y.foo is not x.foo)
def test_deepcopy_inst_getstate(self):
class C:
def __init__(self, foo):
self.foo = foo
def __getstate__(self):
return {"foo": self.foo}
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y is not x)
self.assert_(y.foo is not x.foo)
def test_deepcopy_inst_setstate(self):
class C:
def __init__(self, foo):
self.foo = foo
def __setstate__(self, state):
self.foo = state["foo"]
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y is not x)
self.assert_(y.foo is not x.foo)
def test_deepcopy_inst_getstate_setstate(self):
class C:
def __init__(self, foo):
self.foo = foo
def __getstate__(self):
return self.foo
def __setstate__(self, state):
self.foo = state
def __cmp__(self, other):
return cmp(self.foo, other.foo)
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y is not x)
self.assert_(y.foo is not x.foo)
def test_deepcopy_reflexive_inst(self):
class C:
pass
x = C()
x.foo = x
y = copy.deepcopy(x)
self.assert_(y is not x)
self.assert_(y.foo is y)
# _reconstruct()
def test_reconstruct_string(self):
class C(object):
def __reduce__(self):
return ""
x = C()
y = copy.copy(x)
self.assert_(y is x)
y = copy.deepcopy(x)
self.assert_(y is x)
def test_reconstruct_nostate(self):
class C(object):
def __reduce__(self):
return (C, ())
x = C()
x.foo = 42
y = copy.copy(x)
self.assert_(y.__class__ is x.__class__)
y = copy.deepcopy(x)
self.assert_(y.__class__ is x.__class__)
def test_reconstruct_state(self):
class C(object):
def __reduce__(self):
return (C, (), self.__dict__)
def __cmp__(self, other):
return cmp(self.__dict__, other.__dict__)
x = C()
x.foo = [42]
y = copy.copy(x)
self.assertEqual(y, x)
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y.foo is not x.foo)
def test_reconstruct_state_setstate(self):
class C(object):
def __reduce__(self):
return (C, (), self.__dict__)
def __setstate__(self, state):
self.__dict__.update(state)
def __cmp__(self, other):
return cmp(self.__dict__, other.__dict__)
x = C()
x.foo = [42]
y = copy.copy(x)
self.assertEqual(y, x)
y = copy.deepcopy(x)
self.assertEqual(y, x)
self.assert_(y.foo is not x.foo)
def test_reconstruct_reflexive(self):
class C(object):
pass
x = C()
x.foo = x
y = copy.deepcopy(x)
self.assert_(y is not x)
self.assert_(y.foo is y)
# Additions for Python 2.3 and pickle protocol 2
def test_reduce_4tuple(self):
class C(list):
def __reduce__(self):
return (C, (), self.__dict__, iter(self))
def __cmp__(self, other):
return (cmp(list(self), list(other)) or
cmp(self.__dict__, other.__dict__))
x = C([[1, 2], 3])
y = copy.copy(x)
self.assertEqual(x, y)
self.assert_(x is not y)
self.assert_(x[0] is y[0])
y = copy.deepcopy(x)
self.assertEqual(x, y)
self.assert_(x is not y)
self.assert_(x[0] is not y[0])
def test_reduce_5tuple(self):
class C(dict):
def __reduce__(self):
return (C, (), self.__dict__, None, self.iteritems())
def __cmp__(self, other):
return (cmp(dict(self), list(dict)) or
cmp(self.__dict__, other.__dict__))
x = C([("foo", [1, 2]), ("bar", 3)])
y = copy.copy(x)
self.assertEqual(x, y)
self.assert_(x is not y)
self.assert_(x["foo"] is y["foo"])
y = copy.deepcopy(x)
self.assertEqual(x, y)
self.assert_(x is not y)
self.assert_(x["foo"] is not y["foo"])
def test_copy_slots(self):
class C(object):
__slots__ = ["foo"]
x = C()
x.foo = [42]
y = copy.copy(x)
self.assert_(x.foo is y.foo)
def test_deepcopy_slots(self):
class C(object):
__slots__ = ["foo"]
x = C()
x.foo = [42]
y = copy.deepcopy(x)
self.assertEqual(x.foo, y.foo)
self.assert_(x.foo is not y.foo)
def test_copy_list_subclass(self):
class C(list):
pass
x = C([[1, 2], 3])
x.foo = [4, 5]
y = copy.copy(x)
self.assertEqual(list(x), list(y))
self.assertEqual(x.foo, y.foo)
self.assert_(x[0] is y[0])
self.assert_(x.foo is y.foo)
def test_deepcopy_list_subclass(self):
class C(list):
pass
x = C([[1, 2], 3])
x.foo = [4, 5]
y = copy.deepcopy(x)
self.assertEqual(list(x), list(y))
self.assertEqual(x.foo, y.foo)
self.assert_(x[0] is not y[0])
self.assert_(x.foo is not y.foo)
def test_copy_tuple_subclass(self):
class C(tuple):
pass
x = C([1, 2, 3])
self.assertEqual(tuple(x), (1, 2, 3))
y = copy.copy(x)
self.assertEqual(tuple(y), (1, 2, 3))
def test_deepcopy_tuple_subclass(self):
class C(tuple):
pass
x = C([[1, 2], 3])
self.assertEqual(tuple(x), ([1, 2], 3))
y = copy.deepcopy(x)
self.assertEqual(tuple(y), ([1, 2], 3))
self.assert_(x is not y)
self.assert_(x[0] is not y[0])
def test_getstate_exc(self):
class EvilState(object):
def __getstate__(self):
raise ValueError, "ain't got no stickin' state"
self.assertRaises(ValueError, copy.copy, EvilState())
def test_main():
test_support.run_unittest(TestCopy)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_csv.py ---
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2001,2002 Python Software Foundation
# csv package unit tests
import sys
import unittest
from StringIO import StringIO
import csv
import gc
from test import test_support
class Test_Csv(unittest.TestCase):
"""
Test the underlying C csv parser in ways that are not appropriate
from the high level interface. Further tests of this nature are done
in TestDialectRegistry.
"""
def test_reader_arg_valid(self):
self.assertRaises(TypeError, csv.reader)
self.assertRaises(TypeError, csv.reader, None)
self.assertRaises(AttributeError, csv.reader, [], bad_attr = 0)
self.assertRaises(csv.Error, csv.reader, [], 'foo')
class BadClass:
def __init__(self):
raise IOError
self.assertRaises(IOError, csv.reader, [], BadClass)
self.assertRaises(TypeError, csv.reader, [], None)
class BadDialect:
bad_attr = 0
self.assertRaises(AttributeError, csv.reader, [], BadDialect)
def test_writer_arg_valid(self):
self.assertRaises(TypeError, csv.writer)
self.assertRaises(TypeError, csv.writer, None)
self.assertRaises(AttributeError, csv.writer, StringIO(), bad_attr = 0)
def _test_attrs(self, obj):
self.assertEqual(obj.dialect.delimiter, ',')
obj.dialect.delimiter = '\t'
self.assertEqual(obj.dialect.delimiter, '\t')
self.assertRaises(TypeError, delattr, obj.dialect, 'delimiter')
self.assertRaises(TypeError, setattr, obj.dialect,
'lineterminator', None)
obj.dialect.escapechar = None
self.assertEqual(obj.dialect.escapechar, None)
self.assertRaises(TypeError, delattr, obj.dialect, 'quoting')
self.assertRaises(TypeError, setattr, obj.dialect, 'quoting', None)
obj.dialect.quoting = csv.QUOTE_MINIMAL
self.assertEqual(obj.dialect.quoting, csv.QUOTE_MINIMAL)
def test_reader_attrs(self):
self._test_attrs(csv.reader([]))
def test_writer_attrs(self):
self._test_attrs(csv.writer(StringIO()))
def _write_test(self, fields, expect, **kwargs):
fileobj = StringIO()
writer = csv.writer(fileobj, **kwargs)
writer.writerow(fields)
self.assertEqual(fileobj.getvalue(),
expect + writer.dialect.lineterminator)
def test_write_arg_valid(self):
self.assertRaises(csv.Error, self._write_test, None, '')
self._write_test((), '')
self._write_test([None], '""')
self.assertRaises(csv.Error, self._write_test,
[None], None, quoting = csv.QUOTE_NONE)
# Check that exceptions are passed up the chain
class BadList:
def __len__(self):
return 10;
def __getitem__(self, i):
if i > 2:
raise IOError
self.assertRaises(IOError, self._write_test, BadList(), '')
class BadItem:
def __str__(self):
raise IOError
self.assertRaises(IOError, self._write_test, [BadItem()], '')
def test_write_bigfield(self):
# This exercises the buffer realloc functionality
bigstring = 'X' * 50000
self._write_test([bigstring,bigstring], '%s,%s' % \
(bigstring, bigstring))
def test_write_quoting(self):
self._write_test(['a','1','p,q'], 'a,1,"p,q"')
self.assertRaises(csv.Error,
self._write_test,
['a','1','p,q'], 'a,1,"p,q"',
quoting = csv.QUOTE_NONE)
self._write_test(['a','1','p,q'], 'a,1,"p,q"',
quoting = csv.QUOTE_MINIMAL)
self._write_test(['a','1','p,q'], '"a",1,"p,q"',
quoting = csv.QUOTE_NONNUMERIC)
self._write_test(['a','1','p,q'], '"a","1","p,q"',
quoting = csv.QUOTE_ALL)
def test_write_escape(self):
self._write_test(['a','1','p,q'], 'a,1,"p,q"',
escapechar='\\')
# FAILED - needs to be fixed [am]:
# self._write_test(['a','1','p,"q"'], 'a,1,"p,\\"q\\"',
# escapechar='\\', doublequote = 0)
self._write_test(['a','1','p,q'], 'a,1,p\\,q',
escapechar='\\', quoting = csv.QUOTE_NONE)
def test_writerows(self):
class BrokenFile:
def write(self, buf):
raise IOError
writer = csv.writer(BrokenFile())
self.assertRaises(IOError, writer.writerows, [['a']])
fileobj = StringIO()
writer = csv.writer(fileobj)
self.assertRaises(TypeError, writer.writerows, None)
writer.writerows([['a','b'],['c','d']])
self.assertEqual(fileobj.getvalue(), "a,b\r\nc,d\r\n")
def _read_test(self, input, expect, **kwargs):
reader = csv.reader(input, **kwargs)
result = list(reader)
self.assertEqual(result, expect)
def test_read_oddinputs(self):
self._read_test([], [])
self._read_test([''], [[]])
self.assertRaises(csv.Error, self._read_test,
['"ab"c'], None, strict = 1)
# cannot handle null bytes for the moment
self.assertRaises(csv.Error, self._read_test,
['ab\0c'], None, strict = 1)
self._read_test(['"ab"c'], [['abc']], doublequote = 0)
def test_read_eol(self):
self._read_test(['a,b'], [['a','b']])
self._read_test(['a,b\n'], [['a','b']])
self._read_test(['a,b\r\n'], [['a','b']])
self._read_test(['a,b\r'], [['a','b']])
self.assertRaises(csv.Error, self._read_test, ['a,b\rc,d'], [])
self.assertRaises(csv.Error, self._read_test, ['a,b\nc,d'], [])
self.assertRaises(csv.Error, self._read_test, ['a,b\r\nc,d'], [])
def test_read_escape(self):
self._read_test(['a,\\b,c'], [['a', '\\b', 'c']], escapechar='\\')
self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\')
self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\')
self._read_test(['a,"b,\\c"'], [['a', 'b,\\c']], escapechar='\\')
self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\')
self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\')
def test_read_bigfield(self):
# This exercises the buffer realloc functionality
bigstring = 'X' * 50000
bigline = '%s,%s' % (bigstring, bigstring)
self._read_test([bigline], [[bigstring, bigstring]])
class TestDialectRegistry(unittest.TestCase):
def test_registry_badargs(self):
self.assertRaises(TypeError, csv.list_dialects, None)
self.assertRaises(TypeError, csv.get_dialect)
self.assertRaises(csv.Error, csv.get_dialect, None)
self.assertRaises(csv.Error, csv.get_dialect, "nonesuch")
self.assertRaises(TypeError, csv.unregister_dialect)
self.assertRaises(csv.Error, csv.unregister_dialect, None)
self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch")
self.assertRaises(TypeError, csv.register_dialect, None)
self.assertRaises(TypeError, csv.register_dialect, None, None)
self.assertRaises(TypeError, csv.register_dialect, "nonesuch", None)
class bogus:
def __init__(self):
raise KeyError
self.assertRaises(KeyError, csv.register_dialect, "nonesuch", bogus)
def test_registry(self):
class myexceltsv(csv.excel):
delimiter = "\t"
name = "myexceltsv"
expected_dialects = csv.list_dialects() + [name]
expected_dialects.sort()
csv.register_dialect(name, myexceltsv)
try:
self.failUnless(isinstance(csv.get_dialect(name), myexceltsv))
got_dialects = csv.list_dialects()
got_dialects.sort()
self.assertEqual(expected_dialects, got_dialects)
finally:
csv.unregister_dialect(name)
def test_incomplete_dialect(self):
class myexceltsv(csv.Dialect):
delimiter = "\t"
self.assertRaises(csv.Error, myexceltsv)
def test_space_dialect(self):
class space(csv.excel):
delimiter = " "
quoting = csv.QUOTE_NONE
escapechar = "\\"
s = StringIO("abc def\nc1ccccc1 benzene\n")
rdr = csv.reader(s, dialect=space())
self.assertEqual(rdr.next(), ["abc", "def"])
self.assertEqual(rdr.next(), ["c1ccccc1", "benzene"])
def test_dialect_apply(self):
class testA(csv.excel):
delimiter = "\t"
class testB(csv.excel):
delimiter = ":"
class testC(csv.excel):
delimiter = "|"
csv.register_dialect('testC', testC)
try:
fileobj = StringIO()
writer = csv.writer(fileobj)
writer.writerow([1,2,3])
self.assertEqual(fileobj.getvalue(), "1,2,3\r\n")
fileobj = StringIO()
writer = csv.writer(fileobj, testA)
writer.writerow([1,2,3])
self.assertEqual(fileobj.getvalue(), "1\t2\t3\r\n")
fileobj = StringIO()
writer = csv.writer(fileobj, dialect=testB())
writer.writerow([1,2,3])
self.assertEqual(fileobj.getvalue(), "1:2:3\r\n")
fileobj = StringIO()
writer = csv.writer(fileobj, dialect='testC')
writer.writerow([1,2,3])
self.assertEqual(fileobj.getvalue(), "1|2|3\r\n")
fileobj = StringIO()
writer = csv.writer(fileobj, dialect=testA, delimiter=';')
writer.writerow([1,2,3])
self.assertEqual(fileobj.getvalue(), "1;2;3\r\n")
finally:
csv.unregister_dialect('testC')
def test_bad_dialect(self):
# Unknown parameter
self.assertRaises(AttributeError, csv.reader, [], bad_attr = 0)
# Bad values
self.assertRaises(TypeError, csv.reader, [], delimiter = None)
self.assertRaises(TypeError, csv.reader, [], quoting = -1)
self.assertRaises(TypeError, csv.reader, [], quoting = 100)
class TestCsvBase(unittest.TestCase):
def readerAssertEqual(self, input, expected_result):
reader = csv.reader(StringIO(input), dialect = self.dialect)
fields = list(reader)
self.assertEqual(fields, expected_result)
def writerAssertEqual(self, input, expected_result):
fileobj = StringIO()
writer = csv.writer(fileobj, dialect = self.dialect)
writer.writerows(input)
self.assertEqual(fileobj.getvalue(), expected_result)
class TestDialectExcel(TestCsvBase):
dialect = 'excel'
def test_single(self):
self.readerAssertEqual('abc', [['abc']])
def test_simple(self):
self.readerAssertEqual('1,2,3,4,5', [['1','2','3','4','5']])
def test_blankline(self):
self.readerAssertEqual('', [])
def test_empty_fields(self):
self.readerAssertEqual(',', [['', '']])
def test_singlequoted(self):
self.readerAssertEqual('""', [['']])
def test_singlequoted_left_empty(self):
self.readerAssertEqual('"",', [['','']])
def test_singlequoted_right_empty(self):
self.readerAssertEqual(',""', [['','']])
def test_single_quoted_quote(self):
self.readerAssertEqual('""""', [['"']])
def test_quoted_quotes(self):
self.readerAssertEqual('""""""', [['""']])
def test_inline_quote(self):
self.readerAssertEqual('a""b', [['a""b']])
def test_inline_quotes(self):
self.readerAssertEqual('a"b"c', [['a"b"c']])
def test_quotes_and_more(self):
self.readerAssertEqual('"a"b', [['ab']])
def test_lone_quote(self):
self.readerAssertEqual('a"b', [['a"b']])
def test_quote_and_quote(self):
self.readerAssertEqual('"a" "b"', [['a "b"']])
def test_space_and_quote(self):
self.readerAssertEqual(' "a"', [[' "a"']])
def test_quoted(self):
self.readerAssertEqual('1,2,3,"I think, therefore I am",5,6',
[['1', '2', '3',
'I think, therefore I am',
'5', '6']])
def test_quoted_quote(self):
self.readerAssertEqual('1,2,3,"""I see,"" said the blind man","as he picked up his hammer and saw"',
[['1', '2', '3',
'"I see," said the blind man',
'as he picked up his hammer and saw']])
def test_quoted_nl(self):
input = '''\
1,2,3,"""I see,""
said the blind man","as he picked up his
hammer and saw"
9,8,7,6'''
self.readerAssertEqual(input,
[['1', '2', '3',
'"I see,"\nsaid the blind man',
'as he picked up his\nhammer and saw'],
['9','8','7','6']])
def test_dubious_quote(self):
self.readerAssertEqual('12,12,1",', [['12', '12', '1"', '']])
def test_null(self):
self.writerAssertEqual([], '')
def test_single(self):
self.writerAssertEqual([['abc']], 'abc\r\n')
def test_simple(self):
self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1,2,abc,3,4\r\n')
def test_quotes(self):
self.writerAssertEqual([[1, 2, 'a"bc"', 3, 4]], '1,2,"a""bc""",3,4\r\n')
def test_quote_fieldsep(self):
self.writerAssertEqual([['abc,def']], '"abc,def"\r\n')
def test_newlines(self):
self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n')
class EscapedExcel(csv.excel):
quoting = csv.QUOTE_NONE
escapechar = '\\'
class TestEscapedExcel(TestCsvBase):
dialect = EscapedExcel()
def test_escape_fieldsep(self):
self.writerAssertEqual([['abc,def']], 'abc\\,def\r\n')
def test_read_escape_fieldsep(self):
self.readerAssertEqual('abc\\,def\r\n', [['abc,def']])
class QuotedEscapedExcel(csv.excel):
quoting = csv.QUOTE_NONNUMERIC
escapechar = '\\'
class TestQuotedEscapedExcel(TestCsvBase):
dialect = QuotedEscapedExcel()
def test_write_escape_fieldsep(self):
self.writerAssertEqual([['abc,def']], '"abc,def"\r\n')
def test_read_escape_fieldsep(self):
self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']])
class TestDictFields(unittest.TestCase):
### "long" means the row is longer than the number of fieldnames
### "short" means there are fewer elements in the row than fieldnames
def test_write_simple_dict(self):
fileobj = StringIO()
writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
writer.writerow({"f1": 10, "f3": "abc"})
self.assertEqual(fileobj.getvalue(), "10,,abc\r\n")
def test_write_no_fields(self):
fileobj = StringIO()
self.assertRaises(TypeError, csv.DictWriter, fileobj)
def test_read_dict_fields(self):
reader = csv.DictReader(StringIO("1,2,abc\r\n"),
fieldnames=["f1", "f2", "f3"])
self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'})
def test_read_dict_no_fieldnames(self):
reader = csv.DictReader(StringIO("f1,f2,f3\r\n1,2,abc\r\n"))
self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'})
def test_read_long(self):
reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"),
fieldnames=["f1", "f2"])
self.assertEqual(reader.next(), {"f1": '1', "f2": '2',
None: ["abc", "4", "5", "6"]})
def test_read_long_with_rest(self):
reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"),
fieldnames=["f1", "f2"], restkey="_rest")
self.assertEqual(reader.next(), {"f1": '1', "f2": '2',
"_rest": ["abc", "4", "5", "6"]})
def test_read_long_with_rest_no_fieldnames(self):
reader = csv.DictReader(StringIO("f1,f2\r\n1,2,abc,4,5,6\r\n"),
restkey="_rest")
self.assertEqual(reader.next(), {"f1": '1', "f2": '2',
"_rest": ["abc", "4", "5", "6"]})
def test_read_short(self):
reader = csv.DictReader(["1,2,abc,4,5,6\r\n","1,2,abc\r\n"],
fieldnames="1 2 3 4 5 6".split(),
restval="DEFAULT")
self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
"4": 'DEFAULT', "5": 'DEFAULT',
"6": 'DEFAULT'})
def test_read_multi(self):
sample = [
'2147483648,43.0e12,17,abc,def\r\n',
'147483648,43.0e2,17,abc,def\r\n',
'47483648,43.0,170,abc,def\r\n'
]
reader = csv.DictReader(sample,
fieldnames="i1 float i2 s1 s2".split())
self.assertEqual(reader.next(), {"i1": '2147483648',
"float": '43.0e12',
"i2": '17',
"s1": 'abc',
"s2": 'def'})
def test_read_with_blanks(self):
reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n",
"1,2,abc,4,5,6\r\n"],
fieldnames="1 2 3 4 5 6".split())
self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
def test_read_semi_sep(self):
reader = csv.DictReader(["1;2;abc;4;5;6\r\n"],
fieldnames="1 2 3 4 5 6".split(),
delimiter=';')
self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc',
"4": '4', "5": '5', "6": '6'})
class TestArrayWrites(unittest.TestCase):
def test_int_write(self):
import array
contents = [(20-i) for i in range(20)]
a = array.array('i', contents)
fileobj = StringIO()
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join([str(i) for i in a])+"\r\n"
self.assertEqual(fileobj.getvalue(), expected)
def test_double_write(self):
import array
contents = [(20-i)*0.1 for i in range(20)]
a = array.array('d', contents)
fileobj = StringIO()
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join([str(i) for i in a])+"\r\n"
self.assertEqual(fileobj.getvalue(), expected)
def test_float_write(self):
import array
contents = [(20-i)*0.1 for i in range(20)]
a = array.array('f', contents)
fileobj = StringIO()
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join([str(i) for i in a])+"\r\n"
self.assertEqual(fileobj.getvalue(), expected)
def test_char_write(self):
import array, string
a = array.array('c', string.letters)
fileobj = StringIO()
writer = csv.writer(fileobj, dialect="excel")
writer.writerow(a)
expected = ",".join(a)+"\r\n"
self.assertEqual(fileobj.getvalue(), expected)
class TestDialectValidity(unittest.TestCase):
def test_quoting(self):
class mydialect(csv.Dialect):
delimiter = ";"
escapechar = '\\'
doublequote = False
skipinitialspace = True
lineterminator = '\r\n'
quoting = csv.QUOTE_NONE
d = mydialect()
mydialect.quoting = None
self.assertRaises(csv.Error, mydialect)
mydialect.quoting = csv.QUOTE_NONE
mydialect.escapechar = None
self.assertRaises(csv.Error, mydialect)
mydialect.doublequote = True
mydialect.quoting = csv.QUOTE_ALL
mydialect.quotechar = '"'
d = mydialect()
mydialect.quotechar = "''"
self.assertRaises(csv.Error, mydialect)
mydialect.quotechar = 4
self.assertRaises(csv.Error, mydialect)
def test_delimiter(self):
class mydialect(csv.Dialect):
delimiter = ";"
escapechar = '\\'
doublequote = False
skipinitialspace = True
lineterminator = '\r\n'
quoting = csv.QUOTE_NONE
d = mydialect()
mydialect.delimiter = ":::"
self.assertRaises(csv.Error, mydialect)
mydialect.delimiter = 4
self.assertRaises(csv.Error, mydialect)
def test_lineterminator(self):
class mydialect(csv.Dialect):
delimiter = ";"
escapechar = '\\'
doublequote = False
skipinitialspace = True
lineterminator = '\r\n'
quoting = csv.QUOTE_NONE
d = mydialect()
mydialect.lineterminator = ":::"
d = mydialect()
mydialect.lineterminator = 4
self.assertRaises(csv.Error, mydialect)
class TestSniffer(unittest.TestCase):
sample1 = """\
Harry's, Arlington Heights, IL, 2/1/03, Kimi Hayes
Shark City, Glendale Heights, IL, 12/28/02, Prezence
Tommy's Place, Blue Island, IL, 12/28/02, Blue Sunday/White Crow
Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back
"""
sample2 = """\
'Harry''s':'Arlington Heights':'IL':'2/1/03':'Kimi Hayes'
'Shark City':'Glendale Heights':'IL':'12/28/02':'Prezence'
'Tommy''s Place':'Blue Island':'IL':'12/28/02':'Blue Sunday/White Crow'
'Stonecutters Seafood and Chop House':'Lemont':'IL':'12/19/02':'Week Back'
"""
header = '''\
"venue","city","state","date","performers"
'''
sample3 = '''\
05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
'''
sample4 = '''\
2147483648;43.0e12;17;abc;def
147483648;43.0e2;17;abc;def
47483648;43.0;170;abc;def
'''
def test_has_header(self):
sniffer = csv.Sniffer()
self.assertEqual(sniffer.has_header(self.sample1), False)
self.assertEqual(sniffer.has_header(self.header+self.sample1), True)
def test_sniff(self):
sniffer = csv.Sniffer()
dialect = sniffer.sniff(self.sample1)
self.assertEqual(dialect.delimiter, ",")
self.assertEqual(dialect.quotechar, '"')
self.assertEqual(dialect.skipinitialspace, True)
dialect = sniffer.sniff(self.sample2)
self.assertEqual(dialect.delimiter, ":")
self.assertEqual(dialect.quotechar, "'")
self.assertEqual(dialect.skipinitialspace, False)
def test_delimiters(self):
sniffer = csv.Sniffer()
dialect = sniffer.sniff(self.sample3)
self.assertEqual(dialect.delimiter, "0")
dialect = sniffer.sniff(self.sample3, delimiters="?,")
self.assertEqual(dialect.delimiter, "?")
dialect = sniffer.sniff(self.sample3, delimiters="/,")
self.assertEqual(dialect.delimiter, "/")
dialect = sniffer.sniff(self.sample4)
self.assertEqual(dialect.delimiter, ";")
if not hasattr(sys, "gettotalrefcount"):
if test_support.verbose: print "*** skipping leakage tests ***"
else:
class NUL:
def write(s, *args):
pass
writelines = write
class TestLeaks(unittest.TestCase):
def test_create_read(self):
delta = 0
lastrc = sys.gettotalrefcount()
for i in xrange(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
csv.reader(["a,b,c\r\n"])
csv.reader(["a,b,c\r\n"])
csv.reader(["a,b,c\r\n"])
delta = rc-lastrc
lastrc = rc
# if csv.reader() leaks, last delta should be 3 or more
self.assertEqual(delta < 3, True)
def test_create_write(self):
delta = 0
lastrc = sys.gettotalrefcount()
s = NUL()
for i in xrange(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
csv.writer(s)
csv.writer(s)
csv.writer(s)
delta = rc-lastrc
lastrc = rc
# if csv.writer() leaks, last delta should be 3 or more
self.assertEqual(delta < 3, True)
def test_read(self):
delta = 0
rows = ["a,b,c\r\n"]*5
lastrc = sys.gettotalrefcount()
for i in xrange(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
rdr = csv.reader(rows)
for row in rdr:
pass
delta = rc-lastrc
lastrc = rc
# if reader leaks during read, delta should be 5 or more
self.assertEqual(delta < 5, True)
def test_write(self):
delta = 0
rows = [[1,2,3]]*5
s = NUL()
lastrc = sys.gettotalrefcount()
for i in xrange(20):
gc.collect()
self.assertEqual(gc.garbage, [])
rc = sys.gettotalrefcount()
writer = csv.writer(s)
for row in rows:
writer.writerow(row)
delta = rc-lastrc
lastrc = rc
# if writer leaks during write, last delta should be 5 or more
self.assertEqual(delta < 5, True)
# commented out for now - csv module doesn't yet support Unicode
if 0:
from StringIO import StringIO
import csv
class TestUnicode(unittest.TestCase):
def test_unicode_read(self):
import codecs
f = codecs.EncodedFile(StringIO("Martin von Löwis,"
"Marc André Lemburg,"
"Guido van Rossum,"
"François Pinard\r\n"),
data_encoding='iso-8859-1')
reader = csv.reader(f)
self.assertEqual(list(reader), [[u"Martin von Löwis",
u"Marc André Lemburg",
u"Guido van Rossum",
u"François Pinardn"]])
def test_main():
mod = sys.modules[__name__]
test_support.run_unittest(
*[getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_datetime.py ---
"""Test date/time type.
See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases
"""
import sys
import pickle
import cPickle
import unittest
from test import test_support
from datetime import MINYEAR, MAXYEAR
from datetime import timedelta
from datetime import tzinfo
from datetime import time
from datetime import date, datetime
pickle_choices = [(pickler, unpickler, proto)
[...3094 lines suppressed...]
lastrc = None
while True:
test_support.run_suite(thesuite)
if 1: # change to 0, under a debug build, for some leak detection
break
gc.collect()
if gc.garbage:
raise SystemError("gc.garbage not empty after test run: %r" %
gc.garbage)
if hasattr(sys, 'gettotalrefcount'):
thisrc = sys.gettotalrefcount()
print >> sys.stderr, '*' * 10, 'total refs:', thisrc,
if lastrc:
print >> sys.stderr, 'delta:', thisrc - lastrc
else:
print >> sys.stderr
lastrc = thisrc
if __name__ == "__main__":
test_main()
--- NEW FILE: test_deque.py ---
from collections import deque
import unittest
from test import test_support
import copy
import cPickle as pickle
from cStringIO import StringIO
import random
BIG = 100000
class TestBasic(unittest.TestCase):
def test_basics(self):
d = deque(xrange(100))
d.__init__(xrange(100, 200))
for i in xrange(200, 400):
d.append(i)
for i in reversed(xrange(-200, 0)):
d.appendleft(i)
self.assertEqual(list(d), range(-200, 400))
self.assertEqual(len(d), 600)
left = [d.popleft() for i in xrange(250)]
self.assertEqual(left, range(-200, 50))
self.assertEqual(list(d), range(50, 400))
right = [d.pop() for i in xrange(250)]
right.reverse()
self.assertEqual(right, range(150, 400))
self.assertEqual(list(d), range(50, 150))
def test_comparisons(self):
d = deque('xabc'); d.popleft()
for e in [d, deque('abc'), deque('ab'), deque(), list(d)]:
self.assertEqual(d==e, type(d)==type(e) and list(d)==list(e))
self.assertEqual(d!=e, not(type(d)==type(e) and list(d)==list(e)))
args = map(deque, ('', 'a', 'b', 'ab', 'ba', 'abc', 'xba', 'xabc', 'cba'))
for x in args:
for y in args:
self.assertEqual(x == y, list(x) == list(y), (x,y))
self.assertEqual(x != y, list(x) != list(y), (x,y))
self.assertEqual(x < y, list(x) < list(y), (x,y))
self.assertEqual(x <= y, list(x) <= list(y), (x,y))
self.assertEqual(x > y, list(x) > list(y), (x,y))
self.assertEqual(x >= y, list(x) >= list(y), (x,y))
self.assertEqual(cmp(x,y), cmp(list(x),list(y)), (x,y))
def test_extend(self):
d = deque('a')
self.assertRaises(TypeError, d.extend, 1)
d.extend('bcd')
self.assertEqual(list(d), list('abcd'))
def test_extendleft(self):
d = deque('a')
self.assertRaises(TypeError, d.extendleft, 1)
d.extendleft('bcd')
self.assertEqual(list(d), list(reversed('abcd')))
def test_getitem(self):
n = 200
d = deque(xrange(n))
l = range(n)
for i in xrange(n):
d.popleft()
l.pop(0)
if random.random() < 0.5:
d.append(i)
l.append(i)
for j in xrange(1-len(l), len(l)):
assert d[j] == l[j]
d = deque('superman')
self.assertEqual(d[0], 's')
self.assertEqual(d[-1], 'n')
d = deque()
self.assertRaises(IndexError, d.__getitem__, 0)
self.assertRaises(IndexError, d.__getitem__, -1)
def test_setitem(self):
n = 200
d = deque(xrange(n))
for i in xrange(n):
d[i] = 10 * i
self.assertEqual(list(d), [10*i for i in xrange(n)])
l = list(d)
for i in xrange(1-n, 0, -1):
d[i] = 7*i
l[i] = 7*i
self.assertEqual(list(d), l)
def test_rotate(self):
s = tuple('abcde')
n = len(s)
d = deque(s)
d.rotate(1) # verify rot(1)
self.assertEqual(''.join(d), 'eabcd')
d = deque(s)
d.rotate(-1) # verify rot(-1)
self.assertEqual(''.join(d), 'bcdea')
d.rotate() # check default to 1
self.assertEqual(tuple(d), s)
for i in xrange(n*3):
d = deque(s)
e = deque(d)
d.rotate(i) # check vs. rot(1) n times
for j in xrange(i):
e.rotate(1)
self.assertEqual(tuple(d), tuple(e))
d.rotate(-i) # check that it works in reverse
self.assertEqual(tuple(d), s)
e.rotate(n-i) # check that it wraps forward
self.assertEqual(tuple(e), s)
for i in xrange(n*3):
d = deque(s)
e = deque(d)
d.rotate(-i)
for j in xrange(i):
e.rotate(-1) # check vs. rot(-1) n times
self.assertEqual(tuple(d), tuple(e))
d.rotate(i) # check that it works in reverse
self.assertEqual(tuple(d), s)
e.rotate(i-n) # check that it wraps backaround
self.assertEqual(tuple(e), s)
d = deque(s)
e = deque(s)
e.rotate(BIG+17) # verify on long series of rotates
dr = d.rotate
for i in xrange(BIG+17):
dr()
self.assertEqual(tuple(d), tuple(e))
def test_len(self):
d = deque('ab')
self.assertEqual(len(d), 2)
d.popleft()
self.assertEqual(len(d), 1)
d.pop()
self.assertEqual(len(d), 0)
self.assertRaises(IndexError, d.pop)
self.assertEqual(len(d), 0)
d.append('c')
self.assertEqual(len(d), 1)
d.appendleft('d')
self.assertEqual(len(d), 2)
d.clear()
self.assertEqual(len(d), 0)
def test_underflow(self):
d = deque()
self.assertRaises(IndexError, d.pop)
self.assertRaises(IndexError, d.popleft)
def test_clear(self):
d = deque(xrange(100))
self.assertEqual(len(d), 100)
d.clear()
self.assertEqual(len(d), 0)
self.assertEqual(list(d), [])
def test_repr(self):
d = deque(xrange(200))
e = eval(repr(d))
self.assertEqual(list(d), list(e))
d.append(d)
self.assert_('...' in repr(d))
def test_print(self):
d = deque(xrange(200))
d.append(d)
f = StringIO()
print >> f, d,
self.assertEqual(f.getvalue(), repr(d))
f.close()
def test_hash(self):
self.assertRaises(TypeError, hash, deque('abc'))
def test_long_steadystate_queue_popleft(self):
for size in (0, 1, 2, 100, 1000):
d = deque(xrange(size))
append, pop = d.append, d.popleft
for i in xrange(size, BIG):
append(i)
x = pop()
if x != i - size:
self.assertEqual(x, i-size)
self.assertEqual(list(d), range(BIG-size, BIG))
def test_long_steadystate_queue_popright(self):
for size in (0, 1, 2, 100, 1000):
d = deque(reversed(xrange(size)))
append, pop = d.appendleft, d.pop
for i in xrange(size, BIG):
append(i)
x = pop()
if x != i - size:
self.assertEqual(x, i-size)
self.assertEqual(list(reversed(list(d))), range(BIG-size, BIG))
def test_big_queue_popleft(self):
pass
d = deque()
append, pop = d.append, d.popleft
for i in xrange(BIG):
append(i)
for i in xrange(BIG):
x = pop()
if x != i:
self.assertEqual(x, i)
def test_big_queue_popright(self):
d = deque()
append, pop = d.appendleft, d.pop
for i in xrange(BIG):
append(i)
for i in xrange(BIG):
x = pop()
if x != i:
self.assertEqual(x, i)
def test_big_stack_right(self):
d = deque()
append, pop = d.append, d.pop
for i in xrange(BIG):
append(i)
for i in reversed(xrange(BIG)):
x = pop()
if x != i:
self.assertEqual(x, i)
self.assertEqual(len(d), 0)
def test_big_stack_left(self):
d = deque()
append, pop = d.appendleft, d.popleft
for i in xrange(BIG):
append(i)
for i in reversed(xrange(BIG)):
x = pop()
if x != i:
self.assertEqual(x, i)
self.assertEqual(len(d), 0)
def test_roundtrip_iter_init(self):
d = deque(xrange(200))
e = deque(d)
self.assertNotEqual(id(d), id(e))
self.assertEqual(list(d), list(e))
def test_pickle(self):
d = deque(xrange(200))
s = pickle.dumps(d)
e = pickle.loads(s)
self.assertNotEqual(id(d), id(e))
self.assertEqual(list(d), list(e))
def test_deepcopy(self):
mut = [10]
d = deque([mut])
e = copy.deepcopy(d)
self.assertEqual(list(d), list(e))
mut[0] = 11
self.assertNotEqual(id(d), id(e))
self.assertNotEqual(list(d), list(e))
def test_copy(self):
mut = [10]
d = deque([mut])
e = copy.copy(d)
self.assertEqual(list(d), list(e))
mut[0] = 11
self.assertNotEqual(id(d), id(e))
self.assertEqual(list(d), list(e))
def test_reversed(self):
for s in ('abcd', xrange(2000)):
self.assertEqual(list(reversed(deque(s))), list(reversed(s)))
def R(seqn):
'Regular generator'
for i in seqn:
yield i
class G:
'Sequence using __getitem__'
def __init__(self, seqn):
self.seqn = seqn
def __getitem__(self, i):
return self.seqn[i]
class I:
'Sequence using iterator protocol'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def next(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class Ig:
'Sequence using iterator protocol defined with a generator'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
for val in self.seqn:
yield val
class X:
'Missing __getitem__ and __iter__'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def next(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class N:
'Iterator missing next()'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
class E:
'Test propagation of exceptions'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def next(self):
3/0
class S:
'Test immediate stop'
def __init__(self, seqn):
pass
def __iter__(self):
return self
def next(self):
raise StopIteration
from itertools import chain, imap
def L(seqn):
'Test multiple tiers of iterators'
return chain(imap(lambda x:x, R(Ig(G(seqn)))))
class TestVariousIteratorArgs(unittest.TestCase):
def test_constructor(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(deque(g(s))), list(g(s)))
self.assertRaises(TypeError, deque, X(s))
self.assertRaises(TypeError, deque, N(s))
self.assertRaises(ZeroDivisionError, deque, E(s))
def test_iter_with_altered_data(self):
d = deque('abcdefg')
it = iter(d)
d.pop()
self.assertRaises(RuntimeError, it.next)
class Deque(deque):
pass
class TestSubclass(unittest.TestCase):
def test_basics(self):
d = Deque(xrange(100))
d.__init__(xrange(100, 200))
for i in xrange(200, 400):
d.append(i)
for i in reversed(xrange(-200, 0)):
d.appendleft(i)
self.assertEqual(list(d), range(-200, 400))
self.assertEqual(len(d), 600)
left = [d.popleft() for i in xrange(250)]
self.assertEqual(left, range(-200, 50))
self.assertEqual(list(d), range(50, 400))
right = [d.pop() for i in xrange(250)]
right.reverse()
self.assertEqual(right, range(150, 400))
self.assertEqual(list(d), range(50, 150))
d.clear()
self.assertEqual(len(d), 0)
def test_copy_pickle(self):
d = Deque('abc')
e = d.__copy__()
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
e = Deque(d)
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
s = pickle.dumps(d)
e = pickle.loads(s)
self.assertNotEqual(id(d), id(e))
self.assertEqual(type(d), type(e))
self.assertEqual(list(d), list(e))
#==============================================================================
libreftest = """
Example from the Library Reference: Doc/lib/libcollections.tex
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print elem.upper()
G
H
I
>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'
>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque
>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])
"""
#==============================================================================
__test__ = {'libreftest' : libreftest}
def test_main(verbose=None):
import sys
from test import test_sets
test_classes = (
TestBasic,
TestVariousIteratorArgs,
TestSubclass,
)
test_support.run_unittest(*test_classes)
# verify reference counting
if verbose and hasattr(sys, "gettotalrefcount"):
import gc
counts = [None] * 5
for i in xrange(len(counts)):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
print counts
# doctests
from test import test_deque
test_support.run_doctest(test_deque, verbose)
if __name__ == "__main__":
test_main(verbose=True)
--- NEW FILE: test_dis.py ---
from test.test_support import verify, verbose, TestFailed, run_unittest
import sys
import dis
import StringIO
# Minimal tests for dis module
import unittest
def _f(a):
print a
return 1
dis_f = """\
%-4d 0 LOAD_FAST 0 (a)
3 PRINT_ITEM
4 PRINT_NEWLINE
%-4d 5 LOAD_CONST 1 (1)
8 RETURN_VALUE
9 LOAD_CONST 0 (None)
12 RETURN_VALUE
"""%(_f.func_code.co_firstlineno + 1,
_f.func_code.co_firstlineno + 2)
def bug708901():
for res in range(1,
10):
pass
dis_bug708901 = """\
%-4d 0 SETUP_LOOP 23 (to 26)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (1)
%-4d 9 LOAD_CONST 2 (10)
12 CALL_FUNCTION 2
15 GET_ITER
>> 16 FOR_ITER 6 (to 25)
19 STORE_FAST 0 (res)
%-4d 22 JUMP_ABSOLUTE 16
>> 25 POP_BLOCK
>> 26 LOAD_CONST 0 (None)
29 RETURN_VALUE
"""%(bug708901.func_code.co_firstlineno + 1,
bug708901.func_code.co_firstlineno + 2,
bug708901.func_code.co_firstlineno + 3)
class DisTests(unittest.TestCase):
def do_disassembly_test(self, func, expected):
s = StringIO.StringIO()
save_stdout = sys.stdout
sys.stdout = s
dis.dis(func)
sys.stdout = save_stdout
got = s.getvalue()
# Trim trailing blanks (if any).
lines = got.split('\n')
lines = [line.rstrip() for line in lines]
expected = expected.split("\n")
import difflib
if expected != lines:
self.fail(
"events did not match expectation:\n" +
"\n".join(difflib.ndiff(expected,
lines)))
def test_opmap(self):
self.assertEqual(dis.opmap["STOP_CODE"], 0)
self.assertEqual(dis.opmap["LOAD_CONST"] in dis.hasconst, True)
self.assertEqual(dis.opmap["STORE_NAME"] in dis.hasname, True)
def test_opname(self):
self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST")
def test_boundaries(self):
self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG)
self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT)
def test_dis(self):
self.do_disassembly_test(_f, dis_f)
def test_bug_708901(self):
self.do_disassembly_test(bug708901, dis_bug708901)
def test_main():
run_unittest(DisTests)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_dummy_thread.py ---
"""Generic thread tests.
Meant to be used by dummy_thread and thread. To allow for different modules
to be used, test_main() can be called with the module to use as the thread
implementation as its sole argument.
"""
import dummy_thread as _thread
import time
import Queue
import random
import unittest
from test import test_support
DELAY = 0 # Set > 0 when testing a module other than dummy_thread, such as
# the 'thread' module.
class LockTests(unittest.TestCase):
"""Test lock objects."""
def setUp(self):
# Create a lock
self.lock = _thread.allocate_lock()
def test_initlock(self):
#Make sure locks start locked
self.failUnless(not self.lock.locked(),
"Lock object is not initialized unlocked.")
def test_release(self):
# Test self.lock.release()
self.lock.acquire()
self.lock.release()
self.failUnless(not self.lock.locked(),
"Lock object did not release properly.")
def test_improper_release(self):
#Make sure release of an unlocked thread raises _thread.error
self.failUnlessRaises(_thread.error, self.lock.release)
def test_cond_acquire_success(self):
#Make sure the conditional acquiring of the lock works.
self.failUnless(self.lock.acquire(0),
"Conditional acquiring of the lock failed.")
def test_cond_acquire_fail(self):
#Test acquiring locked lock returns False
self.lock.acquire(0)
self.failUnless(not self.lock.acquire(0),
"Conditional acquiring of a locked lock incorrectly "
"succeeded.")
def test_uncond_acquire_success(self):
#Make sure unconditional acquiring of a lock works.
self.lock.acquire()
self.failUnless(self.lock.locked(),
"Uncondional locking failed.")
def test_uncond_acquire_return_val(self):
#Make sure that an unconditional locking returns True.
self.failUnless(self.lock.acquire(1) is True,
"Unconditional locking did not return True.")
def test_uncond_acquire_blocking(self):
#Make sure that unconditional acquiring of a locked lock blocks.
def delay_unlock(to_unlock, delay):
"""Hold on to lock for a set amount of time before unlocking."""
time.sleep(delay)
to_unlock.release()
self.lock.acquire()
start_time = int(time.time())
_thread.start_new_thread(delay_unlock,(self.lock, DELAY))
if test_support.verbose:
print
print "*** Waiting for thread to release the lock "\
"(approx. %s sec.) ***" % DELAY
self.lock.acquire()
end_time = int(time.time())
if test_support.verbose:
print "done"
self.failUnless((end_time - start_time) >= DELAY,
"Blocking by unconditional acquiring failed.")
class MiscTests(unittest.TestCase):
"""Miscellaneous tests."""
def test_exit(self):
#Make sure _thread.exit() raises SystemExit
self.failUnlessRaises(SystemExit, _thread.exit)
def test_ident(self):
#Test sanity of _thread.get_ident()
self.failUnless(isinstance(_thread.get_ident(), int),
"_thread.get_ident() returned a non-integer")
self.failUnless(_thread.get_ident() != 0,
"_thread.get_ident() returned 0")
def test_LockType(self):
#Make sure _thread.LockType is the same type as _thread.allocate_locke()
self.failUnless(isinstance(_thread.allocate_lock(), _thread.LockType),
"_thread.LockType is not an instance of what is "
"returned by _thread.allocate_lock()")
def test_interrupt_main(self):
#Calling start_new_thread with a function that executes interrupt_main
# should raise KeyboardInterrupt upon completion.
def call_interrupt():
_thread.interrupt_main()
self.failUnlessRaises(KeyboardInterrupt, _thread.start_new_thread,
call_interrupt, tuple())
def test_interrupt_in_main(self):
# Make sure that if interrupt_main is called in main threat that
# KeyboardInterrupt is raised instantly.
self.failUnlessRaises(KeyboardInterrupt, _thread.interrupt_main)
class ThreadTests(unittest.TestCase):
"""Test thread creation."""
def test_arg_passing(self):
#Make sure that parameter passing works.
def arg_tester(queue, arg1=False, arg2=False):
"""Use to test _thread.start_new_thread() passes args properly."""
queue.put((arg1, arg2))
testing_queue = Queue.Queue(1)
_thread.start_new_thread(arg_tester, (testing_queue, True, True))
result = testing_queue.get()
self.failUnless(result[0] and result[1],
"Argument passing for thread creation using tuple failed")
_thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
'arg1':True, 'arg2':True})
result = testing_queue.get()
self.failUnless(result[0] and result[1],
"Argument passing for thread creation using kwargs failed")
_thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
result = testing_queue.get()
self.failUnless(result[0] and result[1],
"Argument passing for thread creation using both tuple"
" and kwargs failed")
def test_multi_creation(self):
#Make sure multiple threads can be created.
def queue_mark(queue, delay):
"""Wait for ``delay`` seconds and then put something into ``queue``"""
time.sleep(delay)
queue.put(_thread.get_ident())
thread_count = 5
testing_queue = Queue.Queue(thread_count)
if test_support.verbose:
print
print "*** Testing multiple thread creation "\
"(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)
for count in xrange(thread_count):
if DELAY:
local_delay = round(random.random(), 1)
else:
local_delay = 0
_thread.start_new_thread(queue_mark,
(testing_queue, local_delay))
time.sleep(DELAY)
if test_support.verbose:
print 'done'
self.failUnless(testing_queue.qsize() == thread_count,
"Not all %s threads executed properly after %s sec." %
(thread_count, DELAY))
def test_main(imported_module=None):
global _thread, DELAY
if imported_module:
_thread = imported_module
DELAY = 2
if test_support.verbose:
print
print "*** Using %s as _thread module ***" % _thread
test_support.run_unittest(LockTests, MiscTests, ThreadTests)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_dummy_threading.py ---
# Very rudimentary test of threading module
# Create a bunch of threads, let each do some work, wait until all are done
from test.test_support import verbose
import random
import dummy_threading as _threading
import time
class TestThread(_threading.Thread):
def run(self):
global running
# Uncomment if testing another module, such as the real 'threading'
# module.
#delay = random.random() * 2
delay = 0
if verbose:
print 'task', self.getName(), 'will run for', delay, 'sec'
sema.acquire()
mutex.acquire()
running = running + 1
if verbose:
print running, 'tasks are running'
mutex.release()
time.sleep(delay)
if verbose:
print 'task', self.getName(), 'done'
mutex.acquire()
running = running - 1
if verbose:
print self.getName(), 'is finished.', running, 'tasks are running'
mutex.release()
sema.release()
def starttasks():
for i in range(numtasks):
t = TestThread(name="<thread %d>"%i)
threads.append(t)
t.start()
def test_main():
# This takes about n/3 seconds to run (about n/3 clumps of tasks, times
# about 1 second per clump).
global numtasks
numtasks = 10
# no more than 3 of the 10 can run at once
global sema
sema = _threading.BoundedSemaphore(value=3)
global mutex
mutex = _threading.RLock()
global running
running = 0
global threads
threads = []
starttasks()
if verbose:
print 'waiting for all tasks to complete'
for t in threads:
t.join()
if verbose:
print 'all tasks done'
if __name__ == '__main__':
test_main()
--- NEW FILE: test_enumerate.py ---
import unittest
from test import test_support
class G:
'Sequence using __getitem__'
def __init__(self, seqn):
self.seqn = seqn
def __getitem__(self, i):
return self.seqn[i]
class I:
'Sequence using iterator protocol'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def next(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class Ig:
'Sequence using iterator protocol defined with a generator'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
for val in self.seqn:
yield val
class X:
'Missing __getitem__ and __iter__'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def next(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class E:
'Test propagation of exceptions'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def next(self):
3/0
class N:
'Iterator missing next()'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
class EnumerateTestCase(unittest.TestCase):
enum = enumerate
seq, res = 'abc', [(0,'a'), (1,'b'), (2,'c')]
def test_basicfunction(self):
self.assertEqual(type(self.enum(self.seq)), self.enum)
e = self.enum(self.seq)
self.assertEqual(iter(e), e)
self.assertEqual(list(self.enum(self.seq)), self.res)
self.enum.__doc__
def test_getitemseqn(self):
self.assertEqual(list(self.enum(G(self.seq))), self.res)
e = self.enum(G(''))
self.assertRaises(StopIteration, e.next)
def test_iteratorseqn(self):
self.assertEqual(list(self.enum(I(self.seq))), self.res)
e = self.enum(I(''))
self.assertRaises(StopIteration, e.next)
def test_iteratorgenerator(self):
self.assertEqual(list(self.enum(Ig(self.seq))), self.res)
e = self.enum(Ig(''))
self.assertRaises(StopIteration, e.next)
def test_noniterable(self):
self.assertRaises(TypeError, self.enum, X(self.seq))
def test_illformediterable(self):
self.assertRaises(TypeError, list, self.enum(N(self.seq)))
def test_exception_propagation(self):
self.assertRaises(ZeroDivisionError, list, self.enum(E(self.seq)))
def test_argumentcheck(self):
self.assertRaises(TypeError, self.enum) # no arguments
self.assertRaises(TypeError, self.enum, 1) # wrong type (not iterable)
self.assertRaises(TypeError, self.enum, 'abc', 2) # too many arguments
def test_tuple_reuse(self):
# Tests an implementation detail where tuple is reused
# whenever nothing else holds a reference to it
self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq))
self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1,len(self.seq)))
class MyEnum(enumerate):
pass
class SubclassTestCase(EnumerateTestCase):
enum = MyEnum
class TestEmpty(EnumerateTestCase):
seq, res = '', []
class TestBig(EnumerateTestCase):
seq = range(10,20000,2)
res = zip(range(20000), seq)
class TestReversed(unittest.TestCase):
def test_simple(self):
class A:
def __getitem__(self, i):
if i < 5:
return str(i)
raise StopIteration
def __len__(self):
return 5
for data in 'abc', range(5), tuple(enumerate('abc')), A(), xrange(1,17,5):
self.assertEqual(list(data)[::-1], list(reversed(data)))
self.assertRaises(TypeError, reversed, {})
def test_xrange_optimization(self):
x = xrange(1)
self.assertEqual(type(reversed(x)), type(iter(x)))
def test_len(self):
# This is an implementation detail, not an interface requirement
for s in ('hello', tuple('hello'), list('hello'), xrange(5)):
self.assertEqual(len(reversed(s)), len(s))
def test_main(verbose=None):
testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig,
TestReversed)
test_support.run_unittest(*testclasses)
# verify reference counting
import sys
if verbose and hasattr(sys, "gettotalrefcount"):
counts = [None] * 5
for i in xrange(len(counts)):
test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount()
print counts
if __name__ == "__main__":
test_main(verbose=True)
--- NEW FILE: test_eof.py ---
#! /usr/bin/env python
"""test script for a few new invalid token catches"""
import os
import unittest
from test import test_support
class EOFTestCase(unittest.TestCase):
def test_EOFC(self):
try:
eval("""'this is a test\
""")
except SyntaxError, msg:
self.assertEqual(str(msg),
"EOL while scanning single-quoted string (line 1)")
else:
raise test_support.TestFailed
def test_EOFS(self):
try:
eval("""'''this is a test""")
except SyntaxError, msg:
self.assertEqual(str(msg),
"EOF while scanning triple-quoted string (line 1)")
else:
raise test_support.TestFailed
def test_main():
test_support.run_unittest(EOFTestCase)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_filecmp.py ---
import os, filecmp, shutil, tempfile
import unittest
from test import test_support
class FileCompareTestCase(unittest.TestCase):
def setUp(self):
self.name = test_support.TESTFN
self.name_same = test_support.TESTFN + '-same'
self.name_diff = test_support.TESTFN + '-diff'
data = 'Contents of file go here.\n'
for name in [self.name, self.name_same, self.name_diff]:
output = open(name, 'w')
output.write(data)
output.close()
output = open(self.name_diff, 'a+')
output.write('An extra line.\n')
output.close()
self.dir = tempfile.gettempdir()
def tearDown(self):
os.unlink(self.name)
os.unlink(self.name_same)
os.unlink(self.name_diff)
def test_matching(self):
self.failUnless(filecmp.cmp(self.name, self.name_same),
"Comparing file to itself fails")
self.failUnless(filecmp.cmp(self.name, self.name_same, shallow=False),
"Comparing file to itself fails")
self.failUnless(filecmp.cmp(self.name, self.name, shallow=False),
"Comparing file to identical file fails")
self.failUnless(filecmp.cmp(self.name, self.name),
"Comparing file to identical file fails")
def test_different(self):
self.failIf(filecmp.cmp(self.name, self.name_diff),
"Mismatched files compare as equal")
self.failIf(filecmp.cmp(self.name, self.dir),
"File and directory compare as equal")
class DirCompareTestCase(unittest.TestCase):
def setUp(self):
tmpdir = tempfile.gettempdir()
self.dir = os.path.join(tmpdir, 'dir')
self.dir_same = os.path.join(tmpdir, 'dir-same')
self.dir_diff = os.path.join(tmpdir, 'dir-diff')
self.caseinsensitive = os.path.normcase('A') == os.path.normcase('a')
data = 'Contents of file go here.\n'
for dir in [self.dir, self.dir_same, self.dir_diff]:
os.mkdir(dir)
if self.caseinsensitive and dir is self.dir_same:
fn = 'FiLe' # Verify case-insensitive comparison
else:
fn = 'file'
output = open(os.path.join(dir, fn), 'w')
output.write(data)
output.close()
output = open(os.path.join(self.dir_diff, 'file2'), 'w')
output.write('An extra file.\n')
output.close()
def tearDown(self):
shutil.rmtree(self.dir)
shutil.rmtree(self.dir_same)
shutil.rmtree(self.dir_diff)
def test_cmpfiles(self):
self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file']) ==
(['file'], [], []),
"Comparing directory to itself fails")
self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file']) ==
(['file'], [], []),
"Comparing directory to same fails")
# Try it with shallow=False
self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file'],
shallow=False) ==
(['file'], [], []),
"Comparing directory to itself fails")
self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file'],
shallow=False),
"Comparing directory to same fails")
# Add different file2
output = open(os.path.join(self.dir, 'file2'), 'w')
output.write('Different contents.\n')
output.close()
self.failIf(filecmp.cmpfiles(self.dir, self.dir_same,
['file', 'file2']) ==
(['file'], ['file2'], []),
"Comparing mismatched directories fails")
def test_dircmp(self):
# Check attributes for comparison of two identical directories
d = filecmp.dircmp(self.dir, self.dir_same)
if self.caseinsensitive:
self.assertEqual([d.left_list, d.right_list],[['file'], ['FiLe']])
else:
self.assertEqual([d.left_list, d.right_list],[['file'], ['file']])
self.failUnless(d.common == ['file'])
self.failUnless(d.left_only == d.right_only == [])
self.failUnless(d.same_files == ['file'])
self.failUnless(d.diff_files == [])
# Check attributes for comparison of two different directories
d = filecmp.dircmp(self.dir, self.dir_diff)
self.failUnless(d.left_list == ['file'])
self.failUnless(d.right_list == ['file', 'file2'])
self.failUnless(d.common == ['file'])
self.failUnless(d.left_only == [])
self.failUnless(d.right_only == ['file2'])
self.failUnless(d.same_files == ['file'])
self.failUnless(d.diff_files == [])
# Add different file2
output = open(os.path.join(self.dir, 'file2'), 'w')
output.write('Different contents.\n')
output.close()
d = filecmp.dircmp(self.dir, self.dir_diff)
self.failUnless(d.same_files == ['file'])
self.failUnless(d.diff_files == ['file2'])
def test_main():
test_support.run_unittest(FileCompareTestCase, DirCompareTestCase)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_getargs2.py ---
import unittest
from test import test_support
import sys
import warnings, re
warnings.filterwarnings("ignore",
category=DeprecationWarning,
message=".*integer argument expected, got float",
module=__name__)
warnings.filterwarnings("ignore",
category=DeprecationWarning,
message=".*integer argument expected, got float",
module="unittest")
"""
> How about the following counterproposal. This also changes some of
> the other format codes to be a little more regular.
>
> Code C type Range check
>
> b unsigned char 0..UCHAR_MAX
> h signed short SHRT_MIN..SHRT_MAX
> B unsigned char none **
> H unsigned short none **
> k * unsigned long none
> I * unsigned int 0..UINT_MAX
> i int INT_MIN..INT_MAX
> l long LONG_MIN..LONG_MAX
> K * unsigned long long none
> L long long LLONG_MIN..LLONG_MAX
> Notes:
>
> * New format codes.
>
> ** Changed from previous "range-and-a-half" to "none"; the
> range-and-a-half checking wasn't particularly useful.
Plus a C API or two, e.g. PyInt_AsLongMask() ->
unsigned long and PyInt_AsLongLongMask() -> unsigned
long long (if that exists).
"""
LARGE = 0x7FFFFFFF
VERY_LARGE = 0xFF0000121212121212121242L
from _testcapi import UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, INT_MAX, \
INT_MIN, LONG_MIN, LONG_MAX
# fake, they are not defined in Python's header files
LLONG_MAX = 2**63-1
LLONG_MIN = -2**63
ULLONG_MAX = 2**64-1
class Long:
def __int__(self):
return 99L
class Int:
def __int__(self):
return 99
class Unsigned_TestCase(unittest.TestCase):
def test_b(self):
from _testcapi import getargs_b
# b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX)
self.failUnlessEqual(3, getargs_b(3.14))
self.failUnlessEqual(99, getargs_b(Long()))
self.failUnlessEqual(99, getargs_b(Int()))
self.assertRaises(OverflowError, getargs_b, -1)
self.failUnlessEqual(0, getargs_b(0))
self.failUnlessEqual(UCHAR_MAX, getargs_b(UCHAR_MAX))
self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1)
self.failUnlessEqual(42, getargs_b(42))
self.failUnlessEqual(42, getargs_b(42L))
self.assertRaises(OverflowError, getargs_b, VERY_LARGE)
def test_B(self):
from _testcapi import getargs_B
# B returns 'unsigned char', no range checking
self.failUnlessEqual(3, getargs_B(3.14))
self.failUnlessEqual(99, getargs_B(Long()))
self.failUnlessEqual(99, getargs_B(Int()))
self.failUnlessEqual(UCHAR_MAX, getargs_B(-1))
self.failUnlessEqual(UCHAR_MAX, getargs_B(-1L))
self.failUnlessEqual(0, getargs_B(0))
self.failUnlessEqual(UCHAR_MAX, getargs_B(UCHAR_MAX))
self.failUnlessEqual(0, getargs_B(UCHAR_MAX+1))
self.failUnlessEqual(42, getargs_B(42))
self.failUnlessEqual(42, getargs_B(42L))
self.failUnlessEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE))
def test_H(self):
from _testcapi import getargs_H
# H returns 'unsigned short', no range checking
self.failUnlessEqual(3, getargs_H(3.14))
self.failUnlessEqual(99, getargs_H(Long()))
self.failUnlessEqual(99, getargs_H(Int()))
self.failUnlessEqual(USHRT_MAX, getargs_H(-1))
self.failUnlessEqual(0, getargs_H(0))
self.failUnlessEqual(USHRT_MAX, getargs_H(USHRT_MAX))
self.failUnlessEqual(0, getargs_H(USHRT_MAX+1))
self.failUnlessEqual(42, getargs_H(42))
self.failUnlessEqual(42, getargs_H(42L))
self.failUnlessEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE))
def test_I(self):
from _testcapi import getargs_I
# I returns 'unsigned int', no range checking
self.failUnlessEqual(3, getargs_I(3.14))
self.failUnlessEqual(99, getargs_I(Long()))
self.failUnlessEqual(99, getargs_I(Int()))
self.failUnlessEqual(UINT_MAX, getargs_I(-1))
self.failUnlessEqual(0, getargs_I(0))
self.failUnlessEqual(UINT_MAX, getargs_I(UINT_MAX))
self.failUnlessEqual(0, getargs_I(UINT_MAX+1))
self.failUnlessEqual(42, getargs_I(42))
self.failUnlessEqual(42, getargs_I(42L))
self.failUnlessEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE))
def test_k(self):
from _testcapi import getargs_k
# k returns 'unsigned long', no range checking
# it does not accept float, or instances with __int__
self.assertRaises(TypeError, getargs_k, 3.14)
self.assertRaises(TypeError, getargs_k, Long())
self.assertRaises(TypeError, getargs_k, Int())
self.failUnlessEqual(ULONG_MAX, getargs_k(-1))
self.failUnlessEqual(0, getargs_k(0))
self.failUnlessEqual(ULONG_MAX, getargs_k(ULONG_MAX))
self.failUnlessEqual(0, getargs_k(ULONG_MAX+1))
self.failUnlessEqual(42, getargs_k(42))
self.failUnlessEqual(42, getargs_k(42L))
self.failUnlessEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE))
class Signed_TestCase(unittest.TestCase):
def test_i(self):
from _testcapi import getargs_i
# i returns 'int', and does range checking (INT_MIN ... INT_MAX)
self.failUnlessEqual(3, getargs_i(3.14))
self.failUnlessEqual(99, getargs_i(Long()))
self.failUnlessEqual(99, getargs_i(Int()))
self.assertRaises(OverflowError, getargs_i, INT_MIN-1)
self.failUnlessEqual(INT_MIN, getargs_i(INT_MIN))
self.failUnlessEqual(INT_MAX, getargs_i(INT_MAX))
self.assertRaises(OverflowError, getargs_i, INT_MAX+1)
self.failUnlessEqual(42, getargs_i(42))
self.failUnlessEqual(42, getargs_i(42L))
self.assertRaises(OverflowError, getargs_i, VERY_LARGE)
def test_l(self):
from _testcapi import getargs_l
# l returns 'long', and does range checking (LONG_MIN ... LONG_MAX)
self.failUnlessEqual(3, getargs_l(3.14))
self.failUnlessEqual(99, getargs_l(Long()))
self.failUnlessEqual(99, getargs_l(Int()))
self.assertRaises(OverflowError, getargs_l, LONG_MIN-1)
self.failUnlessEqual(LONG_MIN, getargs_l(LONG_MIN))
self.failUnlessEqual(LONG_MAX, getargs_l(LONG_MAX))
self.assertRaises(OverflowError, getargs_l, LONG_MAX+1)
self.failUnlessEqual(42, getargs_l(42))
self.failUnlessEqual(42, getargs_l(42L))
self.assertRaises(OverflowError, getargs_l, VERY_LARGE)
class LongLong_TestCase(unittest.TestCase):
def test_L(self):
from _testcapi import getargs_L
# L returns 'long long', and does range checking (LLONG_MIN ... LLONG_MAX)
# XXX There's a bug in getargs.c, format code "L":
# If you pass something else than a Python long, you
# get "Bad argument to internal function".
# So these three tests are commented out:
## self.failUnlessEqual(3, getargs_L(3.14))
## self.failUnlessEqual(99, getargs_L(Long()))
## self.failUnlessEqual(99, getargs_L(Int()))
self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1)
self.failUnlessEqual(LLONG_MIN, getargs_L(LLONG_MIN))
self.failUnlessEqual(LLONG_MAX, getargs_L(LLONG_MAX))
self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1)
self.failUnlessEqual(42, getargs_L(42))
self.failUnlessEqual(42, getargs_L(42L))
self.assertRaises(OverflowError, getargs_L, VERY_LARGE)
def test_K(self):
from _testcapi import getargs_K
# K return 'unsigned long long', no range checking
self.assertRaises(TypeError, getargs_K, 3.14)
self.assertRaises(TypeError, getargs_K, Long())
self.assertRaises(TypeError, getargs_K, Int())
self.failUnlessEqual(ULLONG_MAX, getargs_K(ULLONG_MAX))
self.failUnlessEqual(0, getargs_K(0))
self.failUnlessEqual(0, getargs_K(ULLONG_MAX+1))
self.failUnlessEqual(42, getargs_K(42))
self.failUnlessEqual(42, getargs_K(42L))
self.failUnlessEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))
def test_main():
tests = [Signed_TestCase, Unsigned_TestCase]
try:
from _testcapi import getargs_L, getargs_K
except ImportError:
pass # PY_LONG_LONG not available
else:
tests.append(LongLong_TestCase)
test_support.run_unittest(*tests)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_heapq.py ---
"""Unittests for heapq."""
from test.test_support import verify, vereq, verbose, TestFailed
from heapq import heappush, heappop, heapify, heapreplace
import random
def check_invariant(heap):
# Check the heap invariant.
for pos, item in enumerate(heap):
if pos: # pos 0 has no parent
parentpos = (pos-1) >> 1
verify(heap[parentpos] <= item)
# An iterator returning a heap's elements, smallest-first.
class heapiter(object):
def __init__(self, heap):
self.heap = heap
def next(self):
try:
return heappop(self.heap)
except IndexError:
raise StopIteration
def __iter__(self):
return self
def test_main():
# 1) Push 100 random numbers and pop them off, verifying all's OK.
heap = []
data = []
check_invariant(heap)
for i in range(256):
item = random.random()
data.append(item)
heappush(heap, item)
check_invariant(heap)
results = []
while heap:
item = heappop(heap)
check_invariant(heap)
results.append(item)
data_sorted = data[:]
data_sorted.sort()
vereq(data_sorted, results)
# 2) Check that the invariant holds for a sorted array
check_invariant(results)
# 3) Naive "N-best" algorithm
heap = []
for item in data:
heappush(heap, item)
if len(heap) > 10:
heappop(heap)
heap.sort()
vereq(heap, data_sorted[-10:])
# 4) Test heapify.
for size in range(30):
heap = [random.random() for dummy in range(size)]
heapify(heap)
check_invariant(heap)
# 5) Less-naive "N-best" algorithm, much faster (if len(data) is big
# enough <wink>) than sorting all of data. However, if we had a max
# heap instead of a min heap, it could go faster still via
# heapify'ing all of data (linear time), then doing 10 heappops
# (10 log-time steps).
heap = data[:10]
heapify(heap)
for item in data[10:]:
if item > heap[0]: # this gets rarer the longer we run
heapreplace(heap, item)
vereq(list(heapiter(heap)), data_sorted[-10:])
# 6) Exercise everything with repeated heapsort checks
for trial in xrange(100):
size = random.randrange(50)
data = [random.randrange(25) for i in range(size)]
if trial & 1: # Half of the time, use heapify
heap = data[:]
heapify(heap)
else: # The rest of the time, use heappush
heap = []
for item in data:
heappush(heap,item)
data.sort()
sorted = [heappop(heap) for i in range(size)]
vereq(data, sorted)
# Make user happy
if verbose:
print "All OK"
if __name__ == "__main__":
test_main()
--- NEW FILE: test_hexoct.py ---
"""Test correct treatment of hex/oct constants.
This is complex because of changes due to PEP 237.
"""
import sys
platform_long_is_32_bits = sys.maxint == 2147483647
import unittest
from test import test_support
import warnings
warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
"<string>")
class TextHexOct(unittest.TestCase):
def test_hex_baseline(self):
# Baseline tests
self.assertEqual(0x0, 0)
self.assertEqual(0x10, 16)
if platform_long_is_32_bits:
self.assertEqual(0x7fffffff, 2147483647)
else:
self.assertEqual(0x7fffffffffffffff, 9223372036854775807)
# Ditto with a minus sign and parentheses
self.assertEqual(-(0x0), 0)
self.assertEqual(-(0x10), -16)
if platform_long_is_32_bits:
self.assertEqual(-(0x7fffffff), -2147483647)
else:
self.assertEqual(-(0x7fffffffffffffff), -9223372036854775807)
# Ditto with a minus sign and NO parentheses
self.assertEqual(-0x0, 0)
self.assertEqual(-0x10, -16)
if platform_long_is_32_bits:
self.assertEqual(-0x7fffffff, -2147483647)
else:
self.assertEqual(-0x7fffffffffffffff, -9223372036854775807)
def test_hex_unsigned(self):
if platform_long_is_32_bits:
# Positive constants
self.assertEqual(0x80000000, 2147483648L)
self.assertEqual(0xffffffff, 4294967295L)
# Ditto with a minus sign and parentheses
self.assertEqual(-(0x80000000), -2147483648L)
self.assertEqual(-(0xffffffff), -4294967295L)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
self.assertEqual(-0x80000000, -2147483648L)
self.assertEqual(-0xffffffff, -4294967295L)
else:
# Positive constants
self.assertEqual(0x8000000000000000, 9223372036854775808L)
self.assertEqual(0xffffffffffffffff, 18446744073709551615L)
# Ditto with a minus sign and parentheses
self.assertEqual(-(0x8000000000000000), -9223372036854775808L)
self.assertEqual(-(0xffffffffffffffff), -18446744073709551615L)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
self.assertEqual(-0x8000000000000000, -9223372036854775808L)
self.assertEqual(-0xffffffffffffffff, -18446744073709551615L)
def test_oct_baseline(self):
# Baseline tests
self.assertEqual(00, 0)
self.assertEqual(020, 16)
if platform_long_is_32_bits:
self.assertEqual(017777777777, 2147483647)
else:
self.assertEqual(0777777777777777777777, 9223372036854775807)
# Ditto with a minus sign and parentheses
self.assertEqual(-(00), 0)
self.assertEqual(-(020), -16)
if platform_long_is_32_bits:
self.assertEqual(-(017777777777), -2147483647)
else:
self.assertEqual(-(0777777777777777777777), -9223372036854775807)
# Ditto with a minus sign and NO parentheses
self.assertEqual(-00, 0)
self.assertEqual(-020, -16)
if platform_long_is_32_bits:
self.assertEqual(-017777777777, -2147483647)
else:
self.assertEqual(-0777777777777777777777, -9223372036854775807)
def test_oct_unsigned(self):
if platform_long_is_32_bits:
# Positive constants
self.assertEqual(020000000000, 2147483648L)
self.assertEqual(037777777777, 4294967295L)
# Ditto with a minus sign and parentheses
self.assertEqual(-(020000000000), -2147483648L)
self.assertEqual(-(037777777777), -4294967295L)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
self.assertEqual(-020000000000, -2147483648L)
self.assertEqual(-037777777777, -4294967295L)
else:
# Positive constants
self.assertEqual(01000000000000000000000, 9223372036854775808L)
self.assertEqual(01777777777777777777777, 18446744073709551615L)
# Ditto with a minus sign and parentheses
self.assertEqual(-(01000000000000000000000), -9223372036854775808L)
self.assertEqual(-(01777777777777777777777), -18446744073709551615L)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
self.assertEqual(-01000000000000000000000, -9223372036854775808L)
self.assertEqual(-01777777777777777777777, -18446744073709551615L)
def test_main():
test_support.run_unittest(TextHexOct)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_imaplib.py ---
import imaplib
import time
# We can check only that it successfully produces a result,
# not the correctness of the result itself, since the result
# depends on the timezone the machine is in.
timevalues = [2000000000, 2000000000.0, time.localtime(2000000000),
'"18-May-2033 05:33:20 +0200"']
for t in timevalues:
imaplib.Time2Internaldate(t)
--- NEW FILE: test_imp.py ---
import imp
from test.test_support import TestFailed
def verify_lock_state(expected):
if imp.lock_held() != expected:
raise TestFailed("expected imp.lock_held() to be %r" % expected)
def testLock():
LOOPS = 50
# The import lock may already be held, e.g. if the test suite is run
# via "import test.autotest".
lock_held_at_start = imp.lock_held()
verify_lock_state(lock_held_at_start)
for i in range(LOOPS):
imp.acquire_lock()
verify_lock_state(True)
for i in range(LOOPS):
imp.release_lock()
# The original state should be restored now.
verify_lock_state(lock_held_at_start)
if not lock_held_at_start:
try:
imp.release_lock()
except RuntimeError:
pass
else:
raise TestFailed("release_lock() without lock should raise "
"RuntimeError")
def test_main():
testLock()
if __name__ == "__main__":
test_main()
--- NEW FILE: test_importhooks.py ---
import sys
import imp
import os
import unittest
from test import test_support
test_src = """\
def get_name():
return __name__
def get_file():
return __file__
"""
test_co = compile(test_src, "<???>", "exec")
test_path = "!!!_test_!!!"
class ImportTracker:
"""Importer that only tracks attempted imports."""
def __init__(self):
self.imports = []
def find_module(self, fullname, path=None):
self.imports.append(fullname)
return None
class TestImporter:
modules = {
"hooktestmodule": (False, test_co),
"hooktestpackage": (True, test_co),
"hooktestpackage.sub": (True, test_co),
"hooktestpackage.sub.subber": (False, test_co),
}
def __init__(self, path=test_path):
if path != test_path:
# if out class is on sys.path_hooks, we must raise
# ImportError for any path item that we can't handle.
raise ImportError
self.path = path
def _get__path__(self):
raise NotImplementedError
def find_module(self, fullname, path=None):
if fullname in self.modules:
return self
else:
return None
def load_module(self, fullname):
ispkg, code = self.modules[fullname]
mod = imp.new_module(fullname)
sys.modules[fullname] = mod
mod.__file__ = "<%s>" % self.__class__.__name__
mod.__loader__ = self
if ispkg:
mod.__path__ = self._get__path__()
exec code in mod.__dict__
return mod
class MetaImporter(TestImporter):
def _get__path__(self):
return []
class PathImporter(TestImporter):
def _get__path__(self):
return [self.path]
class ImportBlocker:
"""Place an ImportBlocker instance on sys.meta_path and you
can be sure the modules you specified can't be imported, even
if it's a builtin."""
def __init__(self, *namestoblock):
self.namestoblock = dict.fromkeys(namestoblock)
def find_module(self, fullname, path=None):
if fullname in self.namestoblock:
return self
return None
def load_module(self, fullname):
raise ImportError, "I dare you"
class ImpWrapper:
def __init__(self, path=None):
if path is not None and not os.path.isdir(path):
raise ImportError
self.path = path
def find_module(self, fullname, path=None):
subname = fullname.split(".")[-1]
if subname != fullname and self.path is None:
return None
if self.path is None:
path = None
else:
path = [self.path]
try:
file, filename, stuff = imp.find_module(subname, path)
except ImportError:
return None
return ImpLoader(file, filename, stuff)
class ImpLoader:
def __init__(self, file, filename, stuff):
self.file = file
self.filename = filename
self.stuff = stuff
def load_module(self, fullname):
mod = imp.load_module(fullname, self.file, self.filename, self.stuff)
if self.file:
self.file.close()
mod.__loader__ = self # for introspection
return mod
class ImportHooksBaseTestCase(unittest.TestCase):
def setUp(self):
self.path = sys.path[:]
self.meta_path = sys.meta_path[:]
self.path_hooks = sys.path_hooks[:]
sys.path_importer_cache.clear()
self.tracker = ImportTracker()
sys.meta_path.insert(0, self.tracker)
def tearDown(self):
sys.path[:] = self.path
sys.meta_path[:] = self.meta_path
sys.path_hooks[:] = self.path_hooks
sys.path_importer_cache.clear()
for fullname in self.tracker.imports:
if fullname in sys.modules:
del sys.modules[fullname]
class ImportHooksTestCase(ImportHooksBaseTestCase):
def doTestImports(self, importer=None):
import hooktestmodule
import hooktestpackage
import hooktestpackage.sub
import hooktestpackage.sub.subber
self.assertEqual(hooktestmodule.get_name(),
"hooktestmodule")
self.assertEqual(hooktestpackage.get_name(),
"hooktestpackage")
self.assertEqual(hooktestpackage.sub.get_name(),
"hooktestpackage.sub")
self.assertEqual(hooktestpackage.sub.subber.get_name(),
"hooktestpackage.sub.subber")
if importer:
self.assertEqual(hooktestmodule.__loader__, importer)
self.assertEqual(hooktestpackage.__loader__, importer)
self.assertEqual(hooktestpackage.sub.__loader__, importer)
self.assertEqual(hooktestpackage.sub.subber.__loader__, importer)
def testMetaPath(self):
i = MetaImporter()
sys.meta_path.append(i)
self.doTestImports(i)
def testPathHook(self):
sys.path_hooks.append(PathImporter)
sys.path.append(test_path)
self.doTestImports()
def testBlocker(self):
mname = "exceptions" # an arbitrary harmless builtin module
if mname in sys.modules:
del sys.modules[mname]
sys.meta_path.append(ImportBlocker(mname))
try:
__import__(mname)
except ImportError:
pass
else:
self.fail("'%s' was not supposed to be importable" % mname)
def testImpWrapper(self):
i = ImpWrapper()
sys.meta_path.append(i)
sys.path_hooks.append(ImpWrapper)
mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc")
for mname in mnames:
parent = mname.split(".")[0]
for n in sys.modules.keys():
if n.startswith(parent):
del sys.modules[n]
for mname in mnames:
m = __import__(mname, globals(), locals(), ["__dummy__"])
m.__loader__ # to make sure we actually handled the import
def test_main():
test_support.run_unittest(ImportHooksTestCase)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_ioctl.py ---
import unittest
from test_support import TestSkipped, run_unittest
import os, struct
try:
import fcntl, termios
except ImportError:
raise TestSkipped("No fcntl or termios module")
if not hasattr(termios,'TIOCGPGRP'):
raise TestSkipped("termios module doesn't have TIOCGPGRP")
try:
tty = open("/dev/tty", "r")
tty.close()
except IOError:
raise TestSkipped("Unable to open /dev/tty")
class IoctlTests(unittest.TestCase):
def test_ioctl(self):
pgrp = os.getpgrp()
tty = open("/dev/tty", "r")
r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ")
self.assertEquals(pgrp, struct.unpack("i", r)[0])
def test_ioctl_mutate(self):
import array
buf = array.array('i', [0])
pgrp = os.getpgrp()
tty = open("/dev/tty", "r")
r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1)
self.assertEquals(r, 0)
self.assertEquals(pgrp, buf[0])
def test_main():
run_unittest(IoctlTests)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_isinstance.py ---
# Tests some corner cases with isinstance() and issubclass(). While these
# tests use new style classes and properties, they actually do whitebox
# testing of error conditions uncovered when using extension types.
import unittest
from test import test_support
import sys
class TestIsInstanceExceptions(unittest.TestCase):
# Test to make sure that an AttributeError when accessing the instance's
# class's bases is masked. This was actually a bug in Python 2.2 and
# 2.2.1 where the exception wasn't caught but it also wasn't being cleared
# (leading to an "undetected error" in the debug build). Set up is,
# isinstance(inst, cls) where:
#
# - inst isn't an InstanceType
# - cls isn't a ClassType, a TypeType, or a TupleType
# - cls has a __bases__ attribute
# - inst has a __class__ attribute
# - inst.__class__ as no __bases__ attribute
#
# Sounds complicated, I know, but this mimics a situation where an
# extension type raises an AttributeError when its __bases__ attribute is
# gotten. In that case, isinstance() should return False.
def test_class_has_no_bases(self):
class I(object):
def getclass(self):
# This must return an object that has no __bases__ attribute
return None
__class__ = property(getclass)
class C(object):
def getbases(self):
return ()
__bases__ = property(getbases)
self.assertEqual(False, isinstance(I(), C()))
# Like above except that inst.__class__.__bases__ raises an exception
# other than AttributeError
def test_bases_raises_other_than_attribute_error(self):
class E(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
class I(object):
def getclass(self):
return E()
__class__ = property(getclass)
class C(object):
def getbases(self):
return ()
__bases__ = property(getbases)
self.assertRaises(RuntimeError, isinstance, I(), C())
# Here's a situation where getattr(cls, '__bases__') raises an exception.
# If that exception is not AttributeError, it should not get masked
def test_dont_mask_non_attribute_error(self):
class I: pass
class C(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
self.assertRaises(RuntimeError, isinstance, I(), C())
# Like above, except that getattr(cls, '__bases__') raises an
# AttributeError, which /should/ get masked as a TypeError
def test_mask_attribute_error(self):
class I: pass
class C(object):
def getbases(self):
raise AttributeError
__bases__ = property(getbases)
self.assertRaises(TypeError, isinstance, I(), C())
# These tests are similar to above, but tickle certain code paths in
# issubclass() instead of isinstance() -- really PyObject_IsSubclass()
# vs. PyObject_IsInstance().
class TestIsSubclassExceptions(unittest.TestCase):
def test_dont_mask_non_attribute_error(self):
class C(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
class S(C): pass
self.assertRaises(RuntimeError, issubclass, C(), S())
def test_mask_attribute_error(self):
class C(object):
def getbases(self):
raise AttributeError
__bases__ = property(getbases)
class S(C): pass
self.assertRaises(TypeError, issubclass, C(), S())
# Like above, but test the second branch, where the __bases__ of the
# second arg (the cls arg) is tested. This means the first arg must
# return a valid __bases__, and it's okay for it to be a normal --
# unrelated by inheritance -- class.
def test_dont_mask_non_attribute_error_in_cls_arg(self):
class B: pass
class C(object):
def getbases(self):
raise RuntimeError
__bases__ = property(getbases)
self.assertRaises(RuntimeError, issubclass, B, C())
def test_mask_attribute_error_in_cls_arg(self):
class B: pass
class C(object):
def getbases(self):
raise AttributeError
__bases__ = property(getbases)
self.assertRaises(TypeError, issubclass, B, C())
# meta classes for creating abstract classes and instances
class AbstractClass(object):
def __init__(self, bases):
self.bases = bases
def getbases(self):
return self.bases
__bases__ = property(getbases)
def __call__(self):
return AbstractInstance(self)
class AbstractInstance(object):
def __init__(self, klass):
self.klass = klass
def getclass(self):
return self.klass
__class__ = property(getclass)
# abstract classes
AbstractSuper = AbstractClass(bases=())
AbstractChild = AbstractClass(bases=(AbstractSuper,))
# normal classes
class Super:
pass
class Child(Super):
pass
# new-style classes
class NewSuper(object):
pass
class NewChild(NewSuper):
pass
class TestIsInstanceIsSubclass(unittest.TestCase):
# Tests to ensure that isinstance and issubclass work on abstract
# classes and instances. Before the 2.2 release, TypeErrors were
# raised when boolean values should have been returned. The bug was
# triggered by mixing 'normal' classes and instances were with
# 'abstract' classes and instances. This case tries to test all
# combinations.
def test_isinstance_normal(self):
# normal instances
self.assertEqual(True, isinstance(Super(), Super))
self.assertEqual(False, isinstance(Super(), Child))
self.assertEqual(False, isinstance(Super(), AbstractSuper))
self.assertEqual(False, isinstance(Super(), AbstractChild))
self.assertEqual(True, isinstance(Child(), Super))
self.assertEqual(False, isinstance(Child(), AbstractSuper))
def test_isinstance_abstract(self):
# abstract instances
self.assertEqual(True, isinstance(AbstractSuper(), AbstractSuper))
self.assertEqual(False, isinstance(AbstractSuper(), AbstractChild))
self.assertEqual(False, isinstance(AbstractSuper(), Super))
self.assertEqual(False, isinstance(AbstractSuper(), Child))
self.assertEqual(True, isinstance(AbstractChild(), AbstractChild))
self.assertEqual(True, isinstance(AbstractChild(), AbstractSuper))
self.assertEqual(False, isinstance(AbstractChild(), Super))
self.assertEqual(False, isinstance(AbstractChild(), Child))
def test_subclass_normal(self):
# normal classes
self.assertEqual(True, issubclass(Super, Super))
self.assertEqual(False, issubclass(Super, AbstractSuper))
self.assertEqual(False, issubclass(Super, Child))
self.assertEqual(True, issubclass(Child, Child))
self.assertEqual(True, issubclass(Child, Super))
self.assertEqual(False, issubclass(Child, AbstractSuper))
def test_subclass_abstract(self):
# abstract classes
self.assertEqual(True, issubclass(AbstractSuper, AbstractSuper))
self.assertEqual(False, issubclass(AbstractSuper, AbstractChild))
self.assertEqual(False, issubclass(AbstractSuper, Child))
self.assertEqual(True, issubclass(AbstractChild, AbstractChild))
self.assertEqual(True, issubclass(AbstractChild, AbstractSuper))
self.assertEqual(False, issubclass(AbstractChild, Super))
self.assertEqual(False, issubclass(AbstractChild, Child))
def test_subclass_tuple(self):
# test with a tuple as the second argument classes
self.assertEqual(True, issubclass(Child, (Child,)))
self.assertEqual(True, issubclass(Child, (Super,)))
self.assertEqual(False, issubclass(Super, (Child,)))
self.assertEqual(True, issubclass(Super, (Child, Super)))
self.assertEqual(False, issubclass(Child, ()))
self.assertEqual(True, issubclass(Super, (Child, (Super,))))
self.assertEqual(True, issubclass(NewChild, (NewChild,)))
self.assertEqual(True, issubclass(NewChild, (NewSuper,)))
self.assertEqual(False, issubclass(NewSuper, (NewChild,)))
self.assertEqual(True, issubclass(NewSuper, (NewChild, NewSuper)))
self.assertEqual(False, issubclass(NewChild, ()))
self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,))))
self.assertEqual(True, issubclass(int, (long, (float, int))))
self.assertEqual(True, issubclass(str, (unicode, (Child, NewChild, basestring))))
def test_subclass_recursion_limit(self):
# make sure that issubclass raises RuntimeError before the C stack is
# blown
self.assertRaises(RuntimeError, blowstack, issubclass, str, str)
def test_isinstance_recursion_limit(self):
# make sure that issubclass raises RuntimeError before the C stack is
# blown
self.assertRaises(RuntimeError, blowstack, isinstance, '', str)
def blowstack(fxn, arg, compare_to):
# Make sure that calling isinstance with a deeply nested tuple for its
# argument will raise RuntimeError eventually.
tuple_arg = (compare_to,)
for cnt in xrange(sys.getrecursionlimit()+5):
tuple_arg = (tuple_arg,)
fxn(arg, tuple_arg)
def test_main():
test_support.run_unittest(
TestIsInstanceExceptions,
TestIsSubclassExceptions,
TestIsInstanceIsSubclass
)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_iterlen.py ---
""" Test Iterator Length Transparency
Some functions or methods which accept general iterable arguments have
optional, more efficient code paths if they know how many items to expect.
For instance, map(func, iterable), will pre-allocate the exact amount of
space required whenever the iterable can report its length.
The desired invariant is: len(it)==len(list(it)).
A complication is that an iterable and iterator can be the same object. To
maintain the invariant, an iterator needs to dynamically update its length.
For instance, an iterable such as xrange(10) always reports its length as ten,
but it=iter(xrange(10)) starts at ten, and then goes to nine after it.next().
Having this capability means that map() can ignore the distinction between
map(func, iterable) and map(func, iter(iterable)).
When the iterable is immutable, the implementation can straight-forwardly
report the original length minus the cumulative number of calls to next().
This is the case for tuples, xrange objects, and itertools.repeat().
Some containers become temporarily immutable during iteration. This includes
dicts, sets, and collections.deque. Their implementation is equally simple
though they need to permantently set their length to zero whenever there is
an attempt to iterate after a length mutation.
The situation slightly more involved whenever an object allows length mutation
during iteration. Lists and sequence iterators are dynanamically updatable.
So, if a list is extended during iteration, the iterator will continue through
the new items. If it shrinks to a point before the most recent iteration,
then no further items are available and the length is reported at zero.
Reversed objects can also be wrapped around mutable objects; however, any
appends after the current position are ignored. Any other approach leads
to confusion and possibly returning the same item more than once.
The iterators not listed above, such as enumerate and the other itertools,
are not length transparent because they have no way to distinguish between
iterables that report static length and iterators whose length changes with
each call (i.e. the difference between enumerate('abc') and
enumerate(iter('abc')).
"""
import unittest
from test import test_support
from itertools import repeat, count
from collections import deque
from UserList import UserList
n = 10
class TestInvariantWithoutMutations(unittest.TestCase):
def test_invariant(self):
it = self.it
for i in reversed(xrange(1, n+1)):
self.assertEqual(len(it), i)
it.next()
self.assertEqual(len(it), 0)
self.assertRaises(StopIteration, it.next)
self.assertEqual(len(it), 0)
class TestTemporarilyImmutable(TestInvariantWithoutMutations):
def test_immutable_during_iteration(self):
# objects such as deques, sets, and dictionaries enforce
# length immutability during iteration
it = self.it
self.assertEqual(len(it), n)
it.next()
self.assertEqual(len(it), n-1)
self.mutate()
self.assertRaises(RuntimeError, it.next)
self.assertEqual(len(it), 0)
## ------- Concrete Type Tests -------
class TestRepeat(TestInvariantWithoutMutations):
def setUp(self):
self.it = repeat(None, n)
def test_no_len_for_infinite_repeat(self):
# The repeat() object can also be infinite
self.assertRaises(TypeError, len, repeat(None))
class TestXrange(TestInvariantWithoutMutations):
def setUp(self):
self.it = iter(xrange(n))
class TestXrangeCustomReversed(TestInvariantWithoutMutations):
def setUp(self):
self.it = reversed(xrange(n))
class TestTuple(TestInvariantWithoutMutations):
def setUp(self):
self.it = iter(tuple(xrange(n)))
## ------- Types that should not be mutated during iteration -------
class TestDeque(TestTemporarilyImmutable):
def setUp(self):
d = deque(xrange(n))
self.it = iter(d)
self.mutate = d.pop
class TestDequeReversed(TestTemporarilyImmutable):
def setUp(self):
d = deque(xrange(n))
self.it = reversed(d)
self.mutate = d.pop
class TestDictKeys(TestTemporarilyImmutable):
def setUp(self):
d = dict.fromkeys(xrange(n))
self.it = iter(d)
self.mutate = d.popitem
class TestDictItems(TestTemporarilyImmutable):
def setUp(self):
d = dict.fromkeys(xrange(n))
self.it = d.iteritems()
self.mutate = d.popitem
class TestDictValues(TestTemporarilyImmutable):
def setUp(self):
d = dict.fromkeys(xrange(n))
self.it = d.itervalues()
self.mutate = d.popitem
class TestSet(TestTemporarilyImmutable):
def setUp(self):
d = set(xrange(n))
self.it = iter(d)
self.mutate = d.pop
## ------- Types that can mutate during iteration -------
class TestList(TestInvariantWithoutMutations):
def setUp(self):
self.it = iter(range(n))
def test_mutation(self):
d = range(n)
it = iter(d)
it.next()
it.next()
self.assertEqual(len(it), n-2)
d.append(n)
self.assertEqual(len(it), n-1) # grow with append
d[1:] = []
self.assertEqual(len(it), 0)
self.assertEqual(list(it), [])
d.extend(xrange(20))
self.assertEqual(len(it), 0)
class TestListReversed(TestInvariantWithoutMutations):
def setUp(self):
self.it = reversed(range(n))
def test_mutation(self):
d = range(n)
it = reversed(d)
it.next()
it.next()
self.assertEqual(len(it), n-2)
d.append(n)
self.assertEqual(len(it), n-2) # ignore append
d[1:] = []
self.assertEqual(len(it), 0)
self.assertEqual(list(it), []) # confirm invariant
d.extend(xrange(20))
self.assertEqual(len(it), 0)
class TestSeqIter(TestInvariantWithoutMutations):
def setUp(self):
self.it = iter(UserList(range(n)))
def test_mutation(self):
d = UserList(range(n))
it = iter(d)
it.next()
it.next()
self.assertEqual(len(it), n-2)
d.append(n)
self.assertEqual(len(it), n-1) # grow with append
d[1:] = []
self.assertEqual(len(it), 0)
self.assertEqual(list(it), [])
d.extend(xrange(20))
self.assertEqual(len(it), 0)
class TestSeqIterReversed(TestInvariantWithoutMutations):
def setUp(self):
self.it = reversed(UserList(range(n)))
def test_mutation(self):
d = UserList(range(n))
it = reversed(d)
it.next()
it.next()
self.assertEqual(len(it), n-2)
d.append(n)
self.assertEqual(len(it), n-2) # ignore append
d[1:] = []
self.assertEqual(len(it), 0)
self.assertEqual(list(it), []) # confirm invariant
d.extend(xrange(20))
self.assertEqual(len(it), 0)
if __name__ == "__main__":
unittests = [
TestRepeat,
TestXrange,
TestXrangeCustomReversed,
TestTuple,
TestDeque,
TestDequeReversed,
TestDictKeys,
TestDictItems,
TestDictValues,
TestSet,
TestList,
TestListReversed,
TestSeqIter,
TestSeqIterReversed,
]
test_support.run_unittest(*unittests)
--- NEW FILE: test_itertools.py ---
import unittest
from test import test_support
from itertools import *
import sys
import operator
import random
def onearg(x):
'Test function of one argument'
return 2*x
def errfunc(*args):
'Test function that raises an error'
raise ValueError
def gen3():
'Non-restartable source sequence'
for i in (0, 1, 2):
yield i
def isEven(x):
'Test predicate'
return x%2==0
def isOdd(x):
'Test predicate'
return x%2==1
class StopNow:
'Class emulating an empty iterable.'
def __iter__(self):
return self
def next(self):
raise StopIteration
def take(n, seq):
'Convenience function for partially consuming a long of infinite iterable'
return list(islice(seq, n))
class TestBasicOps(unittest.TestCase):
def test_chain(self):
self.assertEqual(list(chain('abc', 'def')), list('abcdef'))
self.assertEqual(list(chain('abc')), list('abc'))
self.assertEqual(list(chain('')), [])
self.assertEqual(take(4, chain('abc', 'def')), list('abcd'))
self.assertRaises(TypeError, chain, 2, 3)
def test_count(self):
self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
self.assertRaises(TypeError, count, 2, 3)
self.assertRaises(TypeError, count, 'a')
c = count(sys.maxint-2) # verify that rollover doesn't crash
c.next(); c.next(); c.next(); c.next(); c.next()
def test_cycle(self):
self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
self.assertEqual(list(cycle('')), [])
self.assertRaises(TypeError, cycle)
self.assertRaises(TypeError, cycle, 5)
self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
def test_groupby(self):
# Check whether it accepts arguments correctly
self.assertEqual([], list(groupby([])))
self.assertEqual([], list(groupby([], key=id)))
self.assertRaises(TypeError, list, groupby('abc', []))
self.assertRaises(TypeError, groupby, None)
# Check normal input
s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
(2,15,22), (3,16,23), (3,17,23)]
dup = []
for k, g in groupby(s, lambda r:r[0]):
for elem in g:
self.assertEqual(k, elem[0])
dup.append(elem)
self.assertEqual(s, dup)
# Check nested case
dup = []
for k, g in groupby(s, lambda r:r[0]):
for ik, ig in groupby(g, lambda r:r[2]):
for elem in ig:
self.assertEqual(k, elem[0])
self.assertEqual(ik, elem[2])
dup.append(elem)
self.assertEqual(s, dup)
# Check case where inner iterator is not used
keys = [k for k, g in groupby(s, lambda r:r[0])]
expectedkeys = set([r[0] for r in s])
self.assertEqual(set(keys), expectedkeys)
self.assertEqual(len(keys), len(expectedkeys))
# Exercise pipes and filters style
s = 'abracadabra'
# sort s | uniq
r = [k for k, g in groupby(sorted(s))]
self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
# sort s | uniq -d
r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
self.assertEqual(r, ['a', 'b', 'r'])
# sort s | uniq -c
r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
# sort s | uniq -c | sort -rn | head -3
r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
# iter.next failure
class ExpectedError(Exception):
pass
def delayed_raise(n=0):
for i in range(n):
yield 'yo'
raise ExpectedError
def gulp(iterable, keyp=None, func=list):
return [func(g) for k, g in groupby(iterable, keyp)]
# iter.next failure on outer object
self.assertRaises(ExpectedError, gulp, delayed_raise(0))
# iter.next failure on inner object
self.assertRaises(ExpectedError, gulp, delayed_raise(1))
# __cmp__ failure
class DummyCmp:
def __cmp__(self, dst):
raise ExpectedError
s = [DummyCmp(), DummyCmp(), None]
# __cmp__ failure on outer object
self.assertRaises(ExpectedError, gulp, s, func=id)
# __cmp__ failure on inner object
self.assertRaises(ExpectedError, gulp, s)
# keyfunc failure
def keyfunc(obj):
if keyfunc.skip > 0:
keyfunc.skip -= 1
return obj
else:
raise ExpectedError
# keyfunc failure on outer object
keyfunc.skip = 0
self.assertRaises(ExpectedError, gulp, [None], keyfunc)
keyfunc.skip = 1
self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
def test_ifilter(self):
self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6])
self.assertRaises(TypeError, ifilter)
self.assertRaises(TypeError, ifilter, lambda x:x)
self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
self.assertRaises(TypeError, ifilter, isEven, 3)
self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
def test_ifilterfalse(self):
self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7])
self.assertRaises(TypeError, ifilterfalse)
self.assertRaises(TypeError, ifilterfalse, lambda x:x)
self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
self.assertRaises(TypeError, ifilterfalse, isEven, 3)
self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
def test_izip(self):
ans = [(x,y) for x, y in izip('abc',count())]
self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3)))
self.assertEqual(list(izip('abcdef')), zip('abcdef'))
self.assertEqual(list(izip()), zip())
self.assertRaises(TypeError, izip, 3)
self.assertRaises(TypeError, izip, range(3), 3)
# Check tuple re-use (implementation detail)
self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
zip('abc', 'def'))
self.assertEqual([pair for pair in izip('abc', 'def')],
zip('abc', 'def'))
ids = map(id, izip('abc', 'def'))
self.assertEqual(min(ids), max(ids))
ids = map(id, list(izip('abc', 'def')))
self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def test_repeat(self):
self.assertEqual(zip(xrange(3),repeat('a')),
[(0, 'a'), (1, 'a'), (2, 'a')])
self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
self.assertEqual(list(repeat('a', 0)), [])
self.assertEqual(list(repeat('a', -3)), [])
self.assertRaises(TypeError, repeat)
self.assertRaises(TypeError, repeat, None, 3, 4)
self.assertRaises(TypeError, repeat, None, 'a')
def test_imap(self):
self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
[0**1, 1**2, 2**3])
self.assertEqual(list(imap(None, 'abc', range(5))),
[('a',0),('b',1),('c',2)])
self.assertEqual(list(imap(None, 'abc', count())),
[('a',0),('b',1),('c',2)])
self.assertEqual(take(2,imap(None, 'abc', count())),
[('a',0),('b',1)])
self.assertEqual(list(imap(operator.pow, [])), [])
self.assertRaises(TypeError, imap)
self.assertRaises(TypeError, imap, operator.neg)
self.assertRaises(TypeError, imap(10, range(5)).next)
self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
def test_starmap(self):
self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
[0**1, 1**2, 2**3])
self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))),
[0**1, 1**2, 2**3])
self.assertEqual(list(starmap(operator.pow, [])), [])
self.assertRaises(TypeError, list, starmap(operator.pow, [[4,5]]))
self.assertRaises(TypeError, starmap)
self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
def test_islice(self):
for args in [ # islice(args) should agree with range(args)
(10, 20, 3),
(10, 3, 20),
(10, 20),
(10, 3),
(20,)
]:
self.assertEqual(list(islice(xrange(100), *args)), range(*args))
for args, tgtargs in [ # Stop when seqn is exhausted
((10, 110, 3), ((10, 100, 3))),
((10, 110), ((10, 100))),
((110,), (100,))
]:
self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
# Test stop=None
self.assertEqual(list(islice(xrange(10), None)), range(10))
self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
# Test invalid arguments
self.assertRaises(TypeError, islice, xrange(10))
self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
self.assertRaises(ValueError, islice, xrange(10), 'a')
self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1)
def test_takewhile(self):
data = [1, 3, 5, 20, 2, 4, 6, 8]
underten = lambda x: x<10
self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
self.assertEqual(list(takewhile(underten, [])), [])
self.assertRaises(TypeError, takewhile)
self.assertRaises(TypeError, takewhile, operator.pow)
self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
def test_dropwhile(self):
data = [1, 3, 5, 20, 2, 4, 6, 8]
underten = lambda x: x<10
self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
self.assertEqual(list(dropwhile(underten, [])), [])
self.assertRaises(TypeError, dropwhile)
self.assertRaises(TypeError, dropwhile, operator.pow)
self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
def test_tee(self):
n = 200
def irange(n):
for i in xrange(n):
yield i
a, b = tee([]) # test empty iterator
self.assertEqual(list(a), [])
self.assertEqual(list(b), [])
a, b = tee(irange(n)) # test 100% interleaved
self.assertEqual(zip(a,b), zip(range(n),range(n)))
a, b = tee(irange(n)) # test 0% interleaved
self.assertEqual(list(a), range(n))
self.assertEqual(list(b), range(n))
a, b = tee(irange(n)) # test dealloc of leading iterator
for i in xrange(100):
self.assertEqual(a.next(), i)
del a
self.assertEqual(list(b), range(n))
a, b = tee(irange(n)) # test dealloc of trailing iterator
for i in xrange(100):
self.assertEqual(a.next(), i)
del b
self.assertEqual(list(a), range(100, n))
for j in xrange(5): # test randomly interleaved
order = [0]*n + [1]*n
random.shuffle(order)
lists = ([], [])
its = tee(irange(n))
for i in order:
value = its[i].next()
lists[i].append(value)
self.assertEqual(lists[0], range(n))
self.assertEqual(lists[1], range(n))
# test argument format checking
self.assertRaises(TypeError, tee)
self.assertRaises(TypeError, tee, 3)
self.assertRaises(TypeError, tee, [1,2], 'x')
self.assertRaises(TypeError, tee, [1,2], 3, 'x')
# tee object should be instantiable
a, b = tee('abc')
c = type(a)('def')
self.assertEqual(list(c), list('def'))
# test long-lagged and multi-way split
a, b, c = tee(xrange(2000), 3)
for i in xrange(100):
self.assertEqual(a.next(), i)
self.assertEqual(list(b), range(2000))
self.assertEqual([c.next(), c.next()], range(2))
self.assertEqual(list(a), range(100,2000))
self.assertEqual(list(c), range(2,2000))
# tee pass-through to copyable iterator
a, b = tee('abc')
c, d = tee(a)
self.assert_(a is c)
def test_StopIteration(self):
self.assertRaises(StopIteration, izip().next)
for f in (chain, cycle, izip, groupby):
self.assertRaises(StopIteration, f([]).next)
self.assertRaises(StopIteration, f(StopNow()).next)
self.assertRaises(StopIteration, islice([], None).next)
self.assertRaises(StopIteration, islice(StopNow(), None).next)
p, q = tee([])
self.assertRaises(StopIteration, p.next)
self.assertRaises(StopIteration, q.next)
p, q = tee(StopNow())
self.assertRaises(StopIteration, p.next)
self.assertRaises(StopIteration, q.next)
self.assertRaises(StopIteration, repeat(None, 0).next)
for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
self.assertRaises(StopIteration, f(lambda x:x, []).next)
self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
class TestGC(unittest.TestCase):
def makecycle(self, iterator, container):
container.append(iterator)
iterator.next()
del container, iterator
def test_chain(self):
a = []
self.makecycle(chain(a), a)
def test_cycle(self):
a = []
self.makecycle(cycle([a]*2), a)
def test_ifilter(self):
a = []
self.makecycle(ifilter(lambda x:True, [a]*2), a)
def test_ifilterfalse(self):
a = []
self.makecycle(ifilterfalse(lambda x:False, a), a)
def test_izip(self):
a = []
self.makecycle(izip([a]*2, [a]*3), a)
def test_imap(self):
a = []
self.makecycle(imap(lambda x:x, [a]*2), a)
def test_islice(self):
a = []
self.makecycle(islice([a]*2, None), a)
def test_starmap(self):
a = []
self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
def R(seqn):
'Regular generator'
for i in seqn:
yield i
class G:
'Sequence using __getitem__'
def __init__(self, seqn):
self.seqn = seqn
def __getitem__(self, i):
return self.seqn[i]
class I:
'Sequence using iterator protocol'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def next(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class Ig:
'Sequence using iterator protocol defined with a generator'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
for val in self.seqn:
yield val
class X:
'Missing __getitem__ and __iter__'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def next(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class N:
'Iterator missing next()'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
class E:
'Test propagation of exceptions'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def next(self):
3/0
class S:
'Test immediate stop'
def __init__(self, seqn):
pass
def __iter__(self):
return self
def next(self):
raise StopIteration
def L(seqn):
'Test multiple tiers of iterators'
return chain(imap(lambda x:x, R(Ig(G(seqn)))))
class TestVariousIteratorArgs(unittest.TestCase):
def test_chain(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(chain(g(s))), list(g(s)))
self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
self.assertRaises(TypeError, chain, X(s))
self.assertRaises(TypeError, list, chain(N(s)))
self.assertRaises(ZeroDivisionError, list, chain(E(s)))
def test_cycle(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
tgtlen = len(s) * 3
expected = list(g(s))*3
actual = list(islice(cycle(g(s)), tgtlen))
self.assertEqual(actual, expected)
self.assertRaises(TypeError, cycle, X(s))
self.assertRaises(TypeError, list, cycle(N(s)))
self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
def test_groupby(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
self.assertRaises(TypeError, groupby, X(s))
self.assertRaises(TypeError, list, groupby(N(s)))
self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
def test_ifilter(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
self.assertRaises(TypeError, ifilter, isEven, X(s))
self.assertRaises(TypeError, list, ifilter(isEven, N(s)))
self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
def test_ifilterfalse(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s)))
self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
def test_izip(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(izip(g(s))), zip(g(s)))
self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s)))
self.assertRaises(TypeError, izip, X(s))
self.assertRaises(TypeError, list, izip(N(s)))
self.assertRaises(ZeroDivisionError, list, izip(E(s)))
def test_imap(self):
for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
self.assertRaises(TypeError, imap, onearg, X(s))
self.assertRaises(TypeError, list, imap(onearg, N(s)))
self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
def test_islice(self):
for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
self.assertRaises(TypeError, islice, X(s), 10)
self.assertRaises(TypeError, list, islice(N(s), 10))
self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
def test_starmap(self):
for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
for g in (G, I, Ig, S, L, R):
ss = zip(s, s)
self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
self.assertRaises(TypeError, starmap, operator.pow, X(ss))
self.assertRaises(TypeError, list, starmap(operator.pow, N(ss)))
self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
def test_takewhile(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
tgt = []
for elem in g(s):
if not isEven(elem): break
tgt.append(elem)
self.assertEqual(list(takewhile(isEven, g(s))), tgt)
self.assertRaises(TypeError, takewhile, isEven, X(s))
self.assertRaises(TypeError, list, takewhile(isEven, N(s)))
self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
def test_dropwhile(self):
for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
tgt = []
for elem in g(s):
if not tgt and isOdd(elem): continue
tgt.append(elem)
self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
self.assertRaises(TypeError, dropwhile, isOdd, X(s))
self.assertRaises(TypeError, list, dropwhile(isOdd, N(s)))
self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
def test_tee(self):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
it1, it2 = tee(g(s))
self.assertEqual(list(it1), list(g(s)))
self.assertEqual(list(it2), list(g(s)))
self.assertRaises(TypeError, tee, X(s))
self.assertRaises(TypeError, list, tee(N(s))[0])
self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
class LengthTransparency(unittest.TestCase):
def test_repeat(self):
self.assertEqual(len(repeat(None, 50)), 50)
self.assertRaises(TypeError, len, repeat(None))
class RegressionTests(unittest.TestCase):
def test_sf_793826(self):
# Fix Armin Rigo's successful efforts to wreak havoc
def mutatingtuple(tuple1, f, tuple2):
# this builds a tuple t which is a copy of tuple1,
# then calls f(t), then mutates t to be equal to tuple2
# (needs len(tuple1) == len(tuple2)).
def g(value, first=[1]):
if first:
del first[:]
f(z.next())
return value
items = list(tuple2)
items[1:1] = list(tuple1)
gen = imap(g, items)
z = izip(*[gen]*len(tuple1))
z.next()
def f(t):
global T
T = t
first[:] = list(T)
first = []
mutatingtuple((1,2,3), f, (4,5,6))
second = list(T)
self.assertEqual(first, second)
libreftest = """ Doctest for examples in the library reference: libitertools.tex
>>> amounts = [120.15, 764.05, 823.14]
>>> for checknum, amount in izip(count(1200), amounts):
... print 'Check %d is for $%.2f' % (checknum, amount)
...
Check 1200 is for $120.15
Check 1201 is for $764.05
Check 1202 is for $823.14
>>> import operator
>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
... print cube
...
1
8
27
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
>>> for name in islice(reportlines, 3, None, 2):
... print name.title()
...
Alex
Laura
Martin
Walter
Samuele
>>> from operator import itemgetter
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
>>> di = sorted(d.iteritems(), key=itemgetter(1))
>>> for k, g in groupby(di, itemgetter(1)):
... print k, map(itemgetter(0), g)
...
1 ['a', 'c', 'e']
2 ['b', 'd', 'f']
3 ['g']
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
... print map(operator.itemgetter(1), g)
...
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]
>>> def take(n, seq):
... return list(islice(seq, n))
>>> def enumerate(iterable):
... return izip(count(), iterable)
>>> def tabulate(function):
... "Return function(0), function(1), ..."
... return imap(function, count())
>>> def iteritems(mapping):
... return izip(mapping.iterkeys(), mapping.itervalues())
>>> def nth(iterable, n):
... "Returns the nth item"
... return list(islice(iterable, n, n+1))
>>> def all(seq, pred=bool):
... "Returns True if pred(x) is True for every element in the iterable"
... return False not in imap(pred, seq)
>>> def any(seq, pred=bool):
... "Returns True if pred(x) is True for at least one element in the iterable"
... return True in imap(pred, seq)
>>> def no(seq, pred=bool):
... "Returns True if pred(x) is False for every element in the iterable"
... return True not in imap(pred, seq)
>>> def quantify(seq, pred=bool):
... "Count how many times the predicate is True in the sequence"
... return sum(imap(pred, seq))
>>> def padnone(seq):
... "Returns the sequence elements and then returns None indefinitely"
... return chain(seq, repeat(None))
>>> def ncycles(seq, n):
... "Returns the sequence elements n times"
... return chain(*repeat(seq, n))
>>> def dotproduct(vec1, vec2):
... return sum(imap(operator.mul, vec1, vec2))
>>> def flatten(listOfLists):
... return list(chain(*listOfLists))
>>> def repeatfunc(func, times=None, *args):
... "Repeat calls to func with specified arguments."
... " Example: repeatfunc(random.random)"
... if times is None:
... return starmap(func, repeat(args))
... else:
... return starmap(func, repeat(args, times))
>>> def pairwise(iterable):
... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
... a, b = tee(iterable)
... try:
... b.next()
... except StopIteration:
... pass
... return izip(a, b)
This is not part of the examples but it tests to make sure the definitions
perform as purported.
>>> take(10, count())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(enumerate('abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> list(islice(tabulate(lambda x: 2*x), 4))
[0, 2, 4, 6]
>>> nth('abcde', 3)
['d']
>>> all([2, 4, 6, 8], lambda x: x%2==0)
True
>>> all([2, 3, 6, 8], lambda x: x%2==0)
False
>>> any([2, 4, 6, 8], lambda x: x%2==0)
True
>>> any([1, 3, 5, 9], lambda x: x%2==0,)
False
>>> no([1, 3, 5, 9], lambda x: x%2==0)
True
>>> no([1, 2, 5, 9], lambda x: x%2==0)
False
>>> quantify(xrange(99), lambda x: x%2==0)
50
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> flatten(a)
[1, 2, 3, 4, 5, 6]
>>> list(repeatfunc(pow, 5, 2, 3))
[8, 8, 8, 8, 8]
>>> import random
>>> take(5, imap(int, repeatfunc(random.random)))
[0, 0, 0, 0, 0]
>>> list(pairwise('abcd'))
[('a', 'b'), ('b', 'c'), ('c', 'd')]
>>> list(pairwise([]))
[]
>>> list(pairwise('a'))
[]
>>> list(islice(padnone('abc'), 0, 6))
['a', 'b', 'c', None, None, None]
>>> list(ncycles('abc', 3))
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
>>> dotproduct([1,2,3], [4,5,6])
32
"""
__test__ = {'libreftest' : libreftest}
def test_main(verbose=None):
test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
RegressionTests, LengthTransparency)
test_support.run_unittest(*test_classes)
# verify reference counting
if verbose and hasattr(sys, "gettotalrefcount"):
import gc
counts = [None] * 5
for i in xrange(len(counts)):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
print counts
# doctest the examples in the library reference
test_support.run_doctest(sys.modules[__name__], verbose)
if __name__ == "__main__":
test_main(verbose=True)
--- NEW FILE: test_list.py ---
import unittest
from test import test_support, list_tests
class ListTest(list_tests.CommonTest):
type2test = list
def test_truth(self):
super(ListTest, self).test_truth()
self.assert_(not [])
self.assert_([42])
def test_identity(self):
self.assert_([] is not [])
def test_len(self):
super(ListTest, self).test_len()
self.assertEqual(len([]), 0)
self.assertEqual(len([0]), 1)
self.assertEqual(len([0, 1, 2]), 3)
def test_main():
test_support.run_unittest(ListTest)
if __name__=="__main__":
test_main()
--- NEW FILE: test_logging.py ---
#!/usr/bin/env python
#
# Copyright 2001-2002 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# This file is part of the Python logging distribution. See
# http://www.red-dove.com/python_logging.html
#
"""Test harness for the logging module. Run all tests.
Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
"""
import select
import os, sys, string, struct, types, cPickle, cStringIO
import socket, threading, time
import logging, logging.handlers, logging.config
BANNER = "-- %-10s %-6s ---------------------------------------------------\n"
FINISH_UP = "Finish up, it's closing time. Messages should bear numbers 0 through 24."
#----------------------------------------------------------------------------
# Log receiver
#----------------------------------------------------------------------------
TIMEOUT = 10
from SocketServer import ThreadingTCPServer, StreamRequestHandler
class LogRecordStreamHandler(StreamRequestHandler):
"""
Handler for a streaming logging request. It basically logs the record
using whatever logging policy is configured locally.
"""
def handle(self):
"""
Handle multiple requests - each expected to be a 4-byte length,
followed by the LogRecord in pickle format. Logs the record
according to whatever policy is configured locally.
"""
while 1:
try:
chunk = self.connection.recv(4)
if len(chunk) < 4:
break
slen = struct.unpack(">L", chunk)[0]
chunk = self.connection.recv(slen)
while len(chunk) < slen:
chunk = chunk + self.connection.recv(slen - len(chunk))
obj = self.unPickle(chunk)
record = logging.makeLogRecord(obj)
self.handleLogRecord(record)
except:
raise
def unPickle(self, data):
return cPickle.loads(data)
def handleLogRecord(self, record):
logname = "logrecv.tcp." + record.name
#If the end-of-messages sentinel is seen, tell the server to terminate
if record.msg == FINISH_UP:
self.server.abort = 1
record.msg = record.msg + " (via " + logname + ")"
logger = logging.getLogger(logname)
logger.handle(record)
# The server sets socketDataProcessed when it's done.
socketDataProcessed = threading.Event()
class LogRecordSocketReceiver(ThreadingTCPServer):
"""
A simple-minded TCP socket-based logging receiver suitable for test
purposes.
"""
allow_reuse_address = 1
def __init__(self, host='localhost',
port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
handler=LogRecordStreamHandler):
ThreadingTCPServer.__init__(self, (host, port), handler)
self.abort = 0
self.timeout = 1
def serve_until_stopped(self):
abort = 0
while not abort:
rd, wr, ex = select.select([self.socket.fileno()],
[], [],
self.timeout)
if rd:
self.handle_request()
abort = self.abort
#notify the main thread that we're about to exit
socketDataProcessed.set()
def process_request(self, request, client_address):
#import threading
t = threading.Thread(target = self.finish_request,
args = (request, client_address))
t.start()
def runTCP(tcpserver):
tcpserver.serve_until_stopped()
#----------------------------------------------------------------------------
# Test 0
#----------------------------------------------------------------------------
msgcount = 0
def nextmessage():
global msgcount
rv = "Message %d" % msgcount
msgcount = msgcount + 1
return rv
def test0():
ERR = logging.getLogger("ERR")
ERR.setLevel(logging.ERROR)
INF = logging.getLogger("INF")
INF.setLevel(logging.INFO)
INF_ERR = logging.getLogger("INF.ERR")
INF_ERR.setLevel(logging.ERROR)
DEB = logging.getLogger("DEB")
DEB.setLevel(logging.DEBUG)
INF_UNDEF = logging.getLogger("INF.UNDEF")
INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF")
UNDEF = logging.getLogger("UNDEF")
GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF")
CHILD = logging.getLogger("INF.BADPARENT")
#These should log
ERR.log(logging.FATAL, nextmessage())
ERR.error(nextmessage())
INF.log(logging.FATAL, nextmessage())
INF.error(nextmessage())
INF.warn(nextmessage())
INF.info(nextmessage())
INF_UNDEF.log(logging.FATAL, nextmessage())
INF_UNDEF.error(nextmessage())
INF_UNDEF.warn (nextmessage())
INF_UNDEF.info (nextmessage())
INF_ERR.log(logging.FATAL, nextmessage())
INF_ERR.error(nextmessage())
INF_ERR_UNDEF.log(logging.FATAL, nextmessage())
INF_ERR_UNDEF.error(nextmessage())
DEB.log(logging.FATAL, nextmessage())
DEB.error(nextmessage())
DEB.warn (nextmessage())
DEB.info (nextmessage())
DEB.debug(nextmessage())
UNDEF.log(logging.FATAL, nextmessage())
UNDEF.error(nextmessage())
UNDEF.warn (nextmessage())
UNDEF.info (nextmessage())
GRANDCHILD.log(logging.FATAL, nextmessage())
CHILD.log(logging.FATAL, nextmessage())
#These should not log
ERR.warn(nextmessage())
ERR.info(nextmessage())
ERR.debug(nextmessage())
INF.debug(nextmessage())
INF_UNDEF.debug(nextmessage())
INF_ERR.warn(nextmessage())
INF_ERR.info(nextmessage())
INF_ERR.debug(nextmessage())
INF_ERR_UNDEF.warn(nextmessage())
INF_ERR_UNDEF.info(nextmessage())
INF_ERR_UNDEF.debug(nextmessage())
INF.info(FINISH_UP)
#----------------------------------------------------------------------------
# Test 1
#----------------------------------------------------------------------------
#
# First, we define our levels. There can be as many as you want - the only
# limitations are that they should be integers, the lowest should be > 0 and
# larger values mean less information being logged. If you need specific
# level values which do not fit into these limitations, you can use a
# mapping dictionary to convert between your application levels and the
# logging system.
#
SILENT = 10
TACITURN = 9
TERSE = 8
EFFUSIVE = 7
SOCIABLE = 6
VERBOSE = 5
TALKATIVE = 4
GARRULOUS = 3
CHATTERBOX = 2
BORING = 1
LEVEL_RANGE = range(BORING, SILENT + 1)
#
# Next, we define names for our levels. You don't need to do this - in which
# case the system will use "Level n" to denote the text for the level.
#
my_logging_levels = {
SILENT : 'Silent',
TACITURN : 'Taciturn',
TERSE : 'Terse',
EFFUSIVE : 'Effusive',
SOCIABLE : 'Sociable',
VERBOSE : 'Verbose',
TALKATIVE : 'Talkative',
GARRULOUS : 'Garrulous',
CHATTERBOX : 'Chatterbox',
BORING : 'Boring',
}
#
# Now, to demonstrate filtering: suppose for some perverse reason we only
# want to print out all except GARRULOUS messages. Let's create a filter for
# this purpose...
#
class SpecificLevelFilter(logging.Filter):
def __init__(self, lvl):
self.level = lvl
def filter(self, record):
return self.level != record.levelno
class GarrulousFilter(SpecificLevelFilter):
def __init__(self):
SpecificLevelFilter.__init__(self, GARRULOUS)
#
# Now, let's demonstrate filtering at the logger. This time, use a filter
# which excludes SOCIABLE and TACITURN messages. Note that GARRULOUS events
# are still excluded.
#
class VerySpecificFilter(logging.Filter):
def filter(self, record):
return record.levelno not in [SOCIABLE, TACITURN]
def message(s):
sys.stdout.write("%s\n" % s)
SHOULD1 = "This should only be seen at the '%s' logging level (or lower)"
def test1():
#
# Now, tell the logging system to associate names with our levels.
#
for lvl in my_logging_levels.keys():
logging.addLevelName(lvl, my_logging_levels[lvl])
#
# Now, define a test function which logs an event at each of our levels.
#
def doLog(log):
for lvl in LEVEL_RANGE:
log.log(lvl, SHOULD1, logging.getLevelName(lvl))
log = logging.getLogger("")
hdlr = log.handlers[0]
#
# Set the logging level to each different value and call the utility
# function to log events.
# In the output, you should see that each time round the loop, the number of
# logging events which are actually output decreases.
#
for lvl in LEVEL_RANGE:
message("-- setting logging level to '%s' -----" %
logging.getLevelName(lvl))
log.setLevel(lvl)
doLog(log)
#
# Now, we demonstrate level filtering at the handler level. Tell the
# handler defined above to filter at level 'SOCIABLE', and repeat the
# above loop. Compare the output from the two runs.
#
hdlr.setLevel(SOCIABLE)
message("-- Filtering at handler level to SOCIABLE --")
for lvl in LEVEL_RANGE:
message("-- setting logging level to '%s' -----" %
logging.getLevelName(lvl))
log.setLevel(lvl)
doLog(log)
hdlr.setLevel(0) #turn off level filtering at the handler
garr = GarrulousFilter()
hdlr.addFilter(garr)
message("-- Filtering using GARRULOUS filter --")
for lvl in LEVEL_RANGE:
message("-- setting logging level to '%s' -----" %
logging.getLevelName(lvl))
log.setLevel(lvl)
doLog(log)
spec = VerySpecificFilter()
log.addFilter(spec)
message("-- Filtering using specific filter for SOCIABLE, TACITURN --")
for lvl in LEVEL_RANGE:
message("-- setting logging level to '%s' -----" %
logging.getLevelName(lvl))
log.setLevel(lvl)
doLog(log)
log.removeFilter(spec)
hdlr.removeFilter(garr)
#Undo the one level which clashes...for regression tests
logging.addLevelName(logging.DEBUG, "DEBUG")
#----------------------------------------------------------------------------
# Test 2
#----------------------------------------------------------------------------
MSG = "-- logging %d at INFO, messages should be seen every 10 events --"
def test2():
logger = logging.getLogger("")
sh = logger.handlers[0]
sh.close()
logger.removeHandler(sh)
mh = logging.handlers.MemoryHandler(10,logging.WARNING, sh)
logger.setLevel(logging.DEBUG)
logger.addHandler(mh)
message("-- logging at DEBUG, nothing should be seen yet --")
logger.debug("Debug message")
message("-- logging at INFO, nothing should be seen yet --")
logger.info("Info message")
message("-- logging at WARNING, 3 messages should be seen --")
logger.warn("Warn message")
for i in xrange(102):
message(MSG % i)
logger.info("Info index = %d", i)
mh.close()
logger.removeHandler(mh)
logger.addHandler(sh)
#----------------------------------------------------------------------------
# Test 3
#----------------------------------------------------------------------------
FILTER = "a.b"
def doLog3():
logging.getLogger("a").info("Info 1")
logging.getLogger("a.b").info("Info 2")
logging.getLogger("a.c").info("Info 3")
logging.getLogger("a.b.c").info("Info 4")
logging.getLogger("a.b.c.d").info("Info 5")
logging.getLogger("a.bb.c").info("Info 6")
logging.getLogger("b").info("Info 7")
logging.getLogger("b.a").info("Info 8")
logging.getLogger("c.a.b").info("Info 9")
logging.getLogger("a.bb").info("Info 10")
def test3():
root = logging.getLogger()
root.setLevel(logging.DEBUG)
hand = root.handlers[0]
message("Unfiltered...")
doLog3()
message("Filtered with '%s'..." % FILTER)
filt = logging.Filter(FILTER)
hand.addFilter(filt)
doLog3()
hand.removeFilter(filt)
#----------------------------------------------------------------------------
# Test Harness
#----------------------------------------------------------------------------
def banner(nm, typ):
sep = BANNER % (nm, typ)
sys.stdout.write(sep)
sys.stdout.flush()
def test_main_inner():
rootLogger = logging.getLogger("")
rootLogger.setLevel(logging.DEBUG)
hdlr = logging.StreamHandler(sys.stdout)
fmt = logging.Formatter(logging.BASIC_FORMAT)
hdlr.setFormatter(fmt)
rootLogger.addHandler(hdlr)
#Set up a handler such that all events are sent via a socket to the log
#receiver (logrecv).
#The handler will only be added to the rootLogger for some of the tests
hdlr = logging.handlers.SocketHandler('localhost',
logging.handlers.DEFAULT_TCP_LOGGING_PORT)
#Configure the logger for logrecv so events do not propagate beyond it.
#The sockLogger output is buffered in memory until the end of the test,
#and printed at the end.
sockOut = cStringIO.StringIO()
sockLogger = logging.getLogger("logrecv")
sockLogger.setLevel(logging.DEBUG)
sockhdlr = logging.StreamHandler(sockOut)
sockhdlr.setFormatter(logging.Formatter(
"%(name)s -> %(levelname)s: %(message)s"))
sockLogger.addHandler(sockhdlr)
sockLogger.propagate = 0
#Set up servers
threads = []
tcpserver = LogRecordSocketReceiver()
#sys.stdout.write("About to start TCP server...\n")
threads.append(threading.Thread(target=runTCP, args=(tcpserver,)))
for thread in threads:
thread.start()
try:
banner("log_test0", "begin")
rootLogger.addHandler(hdlr)
test0()
hdlr.close()
rootLogger.removeHandler(hdlr)
banner("log_test0", "end")
banner("log_test1", "begin")
test1()
banner("log_test1", "end")
banner("log_test2", "begin")
test2()
banner("log_test2", "end")
banner("log_test3", "begin")
test3()
banner("log_test3", "end")
finally:
#wait for TCP receiver to terminate
socketDataProcessed.wait()
for thread in threads:
thread.join()
banner("logrecv output", "begin")
sys.stdout.write(sockOut.getvalue())
sockhdlr.close()
sockOut.close()
banner("logrecv output", "end")
sys.stdout.flush()
def test_main():
import locale
# Set the locale to the platform-dependent default. I have no idea
# why the test does this, but in any case we save the current locale
# first so we can restore it at the end.
try:
original_locale = locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_ALL, '')
except (ValueError, locale.Error):
# this happens on a Solaris box which only supports "C" locale
# or a Mac OS X box which supports very little locale stuff at all
original_locale = None
try:
test_main_inner()
finally:
if original_locale is not None:
locale.setlocale(locale.LC_ALL, original_locale)
if __name__ == "__main__":
sys.stdout.write("test_logging\n")
test_main()
--- NEW FILE: test_macfs.py ---
# Copyright (C) 2003 Python Software Foundation
import unittest
import warnings
warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
import macfs
import os
import sys
import tempfile
from test import test_support
class TestMacfs(unittest.TestCase):
def setUp(self):
fp = open(test_support.TESTFN, 'w')
fp.write('hello world\n')
fp.close()
def tearDown(self):
try:
os.unlink(test_support.TESTFN)
except:
pass
def test_fsspec(self):
fss = macfs.FSSpec(test_support.TESTFN)
self.assertEqual(os.path.realpath(test_support.TESTFN), fss.as_pathname())
def test_fsref(self):
fsr = macfs.FSRef(test_support.TESTFN)
self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
def test_fsref_unicode(self):
if sys.getfilesystemencoding():
testfn_unicode = unicode(test_support.TESTFN)
fsr = macfs.FSRef(testfn_unicode)
self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
def test_coercion(self):
fss = macfs.FSSpec(test_support.TESTFN)
fsr = macfs.FSRef(test_support.TESTFN)
fss2 = fsr.as_fsspec()
fsr2 = fss.as_fsref()
self.assertEqual(fss.as_pathname(), fss2.as_pathname())
self.assertEqual(fsr.as_pathname(), fsr2.as_pathname())
def test_dates(self):
import time
fss = macfs.FSSpec(test_support.TESTFN)
now = int(time.time())
fss.SetDates(now, now-1, now-2)
dates = fss.GetDates()
self.assertEqual(dates, (now, now-1, now-2))
def test_ctor_type(self):
fss = macfs.FSSpec(test_support.TESTFN)
fss.SetCreatorType('Pyth', 'TEXT')
filecr, filetp = fss.GetCreatorType()
self.assertEqual((filecr, filetp), ('Pyth', 'TEXT'))
def test_alias(self):
fss = macfs.FSSpec(test_support.TESTFN)
alias = fss.NewAlias()
fss2, changed = alias.Resolve()
self.assertEqual(changed, 0)
self.assertEqual(fss.as_pathname(), fss2.as_pathname())
def test_fss_alias(self):
fss = macfs.FSSpec(test_support.TESTFN)
def test_main():
test_support.run_unittest(TestMacfs)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_macostools.py ---
# Copyright (C) 2003 Python Software Foundation
import unittest
import macostools
import Carbon.File
import MacOS
import os
import sys
from test import test_support
TESTFN2 = test_support.TESTFN + '2'
class TestMacostools(unittest.TestCase):
def setUp(self):
fp = open(test_support.TESTFN, 'w')
fp.write('hello world\n')
fp.close()
rfp = MacOS.openrf(test_support.TESTFN, '*wb')
rfp.write('goodbye world\n')
rfp.close()
def tearDown(self):
try:
os.unlink(test_support.TESTFN)
except:
pass
try:
os.unlink(TESTFN2)
except:
pass
def compareData(self):
fp = open(test_support.TESTFN, 'r')
data1 = fp.read()
fp.close()
fp = open(TESTFN2, 'r')
data2 = fp.read()
fp.close()
if data1 != data2:
return 'Data forks differ'
rfp = MacOS.openrf(test_support.TESTFN, '*rb')
data1 = rfp.read(1000)
rfp.close()
rfp = MacOS.openrf(TESTFN2, '*rb')
data2 = rfp.read(1000)
rfp.close()
if data1 != data2:
return 'Resource forks differ'
return ''
def test_touched(self):
# This really only tests that nothing unforeseen happens.
macostools.touched(test_support.TESTFN)
def test_copy(self):
try:
os.unlink(TESTFN2)
except:
pass
macostools.copy(test_support.TESTFN, TESTFN2)
self.assertEqual(self.compareData(), '')
def test_mkalias(self):
try:
os.unlink(TESTFN2)
except:
pass
macostools.mkalias(test_support.TESTFN, TESTFN2)
fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0)
self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN))
def test_mkalias_relative(self):
try:
os.unlink(TESTFN2)
except:
pass
macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix)
fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0)
self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN))
def test_main():
test_support.run_unittest(TestMacostools)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_macpath.py ---
import macpath
from test import test_support
import unittest
class MacPathTestCase(unittest.TestCase):
def test_abspath(self):
self.assert_(macpath.abspath("xx:yy") == "xx:yy")
def test_isabs(self):
isabs = macpath.isabs
self.assert_(isabs("xx:yy"))
self.assert_(isabs("xx:yy:"))
self.assert_(isabs("xx:"))
self.failIf(isabs("foo"))
self.failIf(isabs(":foo"))
self.failIf(isabs(":foo:bar"))
self.failIf(isabs(":foo:bar:"))
def test_commonprefix(self):
commonprefix = macpath.commonprefix
self.assert_(commonprefix(["home:swenson:spam", "home:swen:spam"])
== "home:swen")
self.assert_(commonprefix([":home:swen:spam", ":home:swen:eggs"])
== ":home:swen:")
self.assert_(commonprefix([":home:swen:spam", ":home:swen:spam"])
== ":home:swen:spam")
def test_split(self):
split = macpath.split
self.assertEquals(split("foo:bar"),
('foo:', 'bar'))
self.assertEquals(split("conky:mountpoint:foo:bar"),
('conky:mountpoint:foo', 'bar'))
self.assertEquals(split(":"), ('', ''))
self.assertEquals(split(":conky:mountpoint:"),
(':conky:mountpoint', ''))
def test_splitdrive(self):
splitdrive = macpath.splitdrive
self.assertEquals(splitdrive("foo:bar"), ('', 'foo:bar'))
self.assertEquals(splitdrive(":foo:bar"), ('', ':foo:bar'))
def test_splitext(self):
splitext = macpath.splitext
self.assertEquals(splitext(":foo.ext"), (':foo', '.ext'))
self.assertEquals(splitext("foo:foo.ext"), ('foo:foo', '.ext'))
self.assertEquals(splitext(".ext"), ('', '.ext'))
self.assertEquals(splitext("foo.ext:foo"), ('foo.ext:foo', ''))
self.assertEquals(splitext(":foo.ext:"), (':foo.ext:', ''))
self.assertEquals(splitext(""), ('', ''))
self.assertEquals(splitext("foo.bar.ext"), ('foo.bar', '.ext'))
def test_main():
test_support.run_unittest(MacPathTestCase)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_module.py ---
# Test the module type
from test.test_support import verify, vereq, verbose, TestFailed
import sys
module = type(sys)
# An uninitialized module has no __dict__ or __name__, and __doc__ is None
foo = module.__new__(module)
verify(foo.__dict__ is None)
try:
s = foo.__name__
except AttributeError:
pass
else:
raise TestFailed, "__name__ = %s" % repr(s)
vereq(foo.__doc__, module.__doc__)
# Regularly initialized module, no docstring
foo = module("foo")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, None)
vereq(foo.__dict__, {"__name__": "foo", "__doc__": None})
# ASCII docstring
foo = module("foo", "foodoc")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, "foodoc")
vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc"})
# Unicode docstring
foo = module("foo", u"foodoc\u1234")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, u"foodoc\u1234")
vereq(foo.__dict__, {"__name__": "foo", "__doc__": u"foodoc\u1234"})
# Reinitialization should not replace the __dict__
foo.bar = 42
d = foo.__dict__
foo.__init__("foo", "foodoc")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, "foodoc")
vereq(foo.bar, 42)
vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc", "bar": 42})
verify(foo.__dict__ is d)
if verbose:
print "All OK"
--- NEW FILE: test_mpz.py ---
import mpz
from test.test_support import vereq, TestFailed
def check_conversion(num):
mpz_num = mpz.mpz(num)
vereq(int(mpz_num), num)
vereq(long(mpz_num), num)
vereq(str(mpz_num), 'mpz(%d)' % int(num))
check_conversion(10)
check_conversion(10L)
# FIXME: should check strings, but I'm not sure it works, this seems odd:
# mpz.mpz('10') == mpz(12337)
vereq(mpz.divm(100, 200, 3), 2)
vereq(mpz.divm(100L, 200, 3), 2)
vereq(mpz.divm(100, 200L, 3), 2)
vereq(mpz.divm(100L, 200L, 3), 2)
vereq(mpz.gcd(100, 200), 100)
vereq(mpz.gcd(100L, 200), 100)
vereq(mpz.gcd(100, 200L), 100)
vereq(mpz.gcd(100L, 200L), 100)
vereq(mpz.gcdext(100, 200), (100, 1, 0))
vereq(mpz.gcdext(100L, 200), (100, 1, 0))
vereq(mpz.gcdext(100, 200L), (100, 1, 0))
vereq(mpz.gcdext(100L, 200L), (100, 1, 0))
vereq(mpz.powm(100, 0, 3), 1)
vereq(mpz.powm(100L, 0, 3), 1)
vereq(mpz.powm(100, 0L, 3), 1)
vereq(mpz.powm(100L, 0L, 3), 1)
vereq(mpz.powm(101, 5, 3333), 1616)
vereq(mpz.powm(101L, 5, 3333), 1616)
vereq(mpz.powm(101, 5L, 3333), 1616)
vereq(mpz.powm(101L, 5L, 3333), 1616)
vereq(mpz.sqrt(100), 10)
vereq(mpz.sqrt(100L), 10)
vereq(mpz.sqrt(200), 14)
vereq(mpz.sqrt(200L), 14)
vereq(mpz.sqrtrem(100), (10, 0))
vereq(mpz.sqrtrem(100L), (10, 0))
vereq(mpz.sqrtrem(200), (14, 4))
vereq(mpz.sqrtrem(200L), (14, 4))
try: mpz.mpz(10.)
except TypeError: pass
else: raise TestFailed, 'mpz(10.) should raise a TypeError'
try: mpz.powm(10.)
except TypeError: pass
else: raise TestFailed, 'powm(10.) should raise a TypeError'
try: mpz.powm(100, 1, 0)
except ValueError: pass
else: raise TestFailed, 'powm(100, 1, 0) should raise a ValueError'
try: mpz.divm(10, 10)
except TypeError: pass
else: raise TestFailed, 'divm(10, 10) should raise a TypeError'
try: mpz.divm(10, 10, 10.)
except TypeError: pass
else: raise TestFailed, 'divm(10, 10, 10.) should raise a TypeError'
try: mpz.gcd(10)
except TypeError: pass
else: raise TestFailed, 'gcd(10) should raise a TypeError'
try: mpz.gcd(10, 10.)
except TypeError: pass
else: raise TestFailed, 'gcd(10, 10.) should raise a TypeError'
try: mpz.gcdext(10)
except TypeError: pass
else: raise TestFailed, 'gcdext(10) should raise a TypeError'
try: mpz.gcdext(10, 10.)
except TypeError: pass
else: raise TestFailed, 'gcdext(10, 10.) should raise a TypeError'
try: mpz.mpz(-10).binary()
except ValueError: pass
else: raise TestFailed, 'mpz(-10).binary() should raise a ValueError'
--- NEW FILE: test_multibytecodec.py ---
#!/usr/bin/env python
#
# test_multibytecodec.py
# Unit test for multibytecodec itself
#
# $CJKCodecs: test_multibytecodec.py,v 1.5 2004/01/06 02:26:28 perky Exp $
from test import test_support
from test import test_multibytecodec_support
import unittest, StringIO, codecs
class Test_StreamWriter(unittest.TestCase):
if len(u'\U00012345') == 2: # UCS2
def test_gb18030(self):
s= StringIO.StringIO()
c = codecs.lookup('gb18030')[3](s)
c.write(u'123')
self.assertEqual(s.getvalue(), '123')
c.write(u'\U00012345')
self.assertEqual(s.getvalue(), '123\x907\x959')
c.write(u'\U00012345'[0])
self.assertEqual(s.getvalue(), '123\x907\x959')
c.write(u'\U00012345'[1] + u'\U00012345' + u'\uac00\u00ac')
self.assertEqual(s.getvalue(),
'123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851')
c.write(u'\U00012345'[0])
self.assertEqual(s.getvalue(),
'123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851')
self.assertRaises(UnicodeError, c.reset)
self.assertEqual(s.getvalue(),
'123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851')
# standard utf-8 codecs has broken StreamReader
if test_multibytecodec_support.__cjkcodecs__:
def test_utf_8(self):
s= StringIO.StringIO()
c = codecs.lookup('utf-8')[3](s)
c.write(u'123')
self.assertEqual(s.getvalue(), '123')
c.write(u'\U00012345')
self.assertEqual(s.getvalue(), '123\xf0\x92\x8d\x85')
c.write(u'\U00012345'[0])
self.assertEqual(s.getvalue(), '123\xf0\x92\x8d\x85')
c.write(u'\U00012345'[1] + u'\U00012345' + u'\uac00\u00ac')
self.assertEqual(s.getvalue(),
'123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85'
'\xea\xb0\x80\xc2\xac')
c.write(u'\U00012345'[0])
self.assertEqual(s.getvalue(),
'123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85'
'\xea\xb0\x80\xc2\xac')
c.reset()
self.assertEqual(s.getvalue(),
'123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85'
'\xea\xb0\x80\xc2\xac\xed\xa0\x88')
c.write(u'\U00012345'[1])
self.assertEqual(s.getvalue(),
'123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85'
'\xea\xb0\x80\xc2\xac\xed\xa0\x88\xed\xbd\x85')
else: # UCS4
pass
def test_nullcoding(self):
self.assertEqual(''.decode('gb18030'), u'')
self.assertEqual(unicode('', 'gb18030'), u'')
self.assertEqual(u''.encode('gb18030'), '')
def test_str_decode(self):
self.assertEqual('abcd'.encode('gb18030'), 'abcd')
def test_main():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Test_StreamWriter))
test_support.run_suite(suite)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_multibytecodec_support.py ---
#!/usr/bin/env python
#
# test_multibytecodec_support.py
# Common Unittest Routines for CJK codecs
#
# $CJKCodecs: test_multibytecodec_support.py,v 1.5 2004/01/17 12:47:19 perky Exp $
import sys, codecs, os.path
import unittest
from test import test_support
from StringIO import StringIO
__cjkcodecs__ = 0 # define this as 0 for python
class TestBase:
encoding = '' # codec name
codec = None # codec tuple (with 4 elements)
tstring = '' # string to test StreamReader
codectests = None # must set. codec test tuple
roundtriptest = 1 # set if roundtrip is possible with unicode
has_iso10646 = 0 # set if this encoding contains whole iso10646 map
xmlcharnametest = None # string to test xmlcharrefreplace
def setUp(self):
if self.codec is None:
self.codec = codecs.lookup(self.encoding)
self.encode, self.decode, self.reader, self.writer = self.codec
def test_chunkcoding(self):
for native, utf8 in zip(*[StringIO(f).readlines()
for f in self.tstring]):
u = self.decode(native)[0]
self.assertEqual(u, utf8.decode('utf-8'))
if self.roundtriptest:
self.assertEqual(native, self.encode(u)[0])
def test_errorhandle(self):
for source, scheme, expected in self.codectests:
if type(source) == type(''):
func = self.decode
else:
func = self.encode
if expected:
result = func(source, scheme)[0]
self.assertEqual(result, expected)
else:
self.assertRaises(UnicodeError, func, source, scheme)
if sys.hexversion >= 0x02030000:
def test_xmlcharrefreplace(self):
if self.has_iso10646:
return
s = u"\u0b13\u0b23\u0b60 nd eggs"
self.assertEqual(
self.encode(s, "xmlcharrefreplace")[0],
"ଓଣୠ nd eggs"
)
def test_customreplace(self):
if self.has_iso10646:
return
import htmlentitydefs
names = {}
for (key, value) in htmlentitydefs.entitydefs.items():
if len(value)==1:
names[value.decode('latin-1')] = self.decode(key)[0]
else:
names[unichr(int(value[2:-1]))] = self.decode(key)[0]
def xmlcharnamereplace(exc):
if not isinstance(exc, UnicodeEncodeError):
raise TypeError("don't know how to handle %r" % exc)
l = []
for c in exc.object[exc.start:exc.end]:
try:
l.append(u"&%s;" % names[c])
except KeyError:
l.append(u"&#%d;" % ord(c))
return (u"".join(l), exc.end)
codecs.register_error(
"test.xmlcharnamereplace", xmlcharnamereplace)
if self.xmlcharnametest:
sin, sout = self.xmlcharnametest
else:
sin = u"\xab\u211c\xbb = \u2329\u1234\u232a"
sout = "«ℜ» = ⟨ሴ⟩"
self.assertEqual(self.encode(sin,
"test.xmlcharnamereplace")[0], sout)
def test_streamreader(self):
UTF8Writer = codecs.getwriter('utf-8')
for name in ["read", "readline", "readlines"]:
for sizehint in [None, -1] + range(1, 33) + \
[64, 128, 256, 512, 1024]:
istream = self.reader(StringIO(self.tstring[0]))
ostream = UTF8Writer(StringIO())
func = getattr(istream, name)
while 1:
data = func(sizehint)
if not data:
break
if name == "readlines":
ostream.writelines(data)
else:
ostream.write(data)
self.assertEqual(ostream.getvalue(), self.tstring[1])
def test_streamwriter(self):
if __cjkcodecs__:
readfuncs = ('read', 'readline', 'readlines')
else:
# standard utf8 codec has broken readline and readlines.
readfuncs = ('read',)
UTF8Reader = codecs.getreader('utf-8')
for name in readfuncs:
for sizehint in [None] + range(1, 33) + \
[64, 128, 256, 512, 1024]:
istream = UTF8Reader(StringIO(self.tstring[1]))
ostream = self.writer(StringIO())
func = getattr(istream, name)
while 1:
if sizehint is not None:
data = func(sizehint)
else:
data = func()
if not data:
break
if name == "readlines":
ostream.writelines(data)
else:
ostream.write(data)
self.assertEqual(ostream.getvalue(), self.tstring[0])
if len(u'\U00012345') == 2: # ucs2 build
_unichr = unichr
def unichr(v):
if v >= 0x10000:
return _unichr(0xd800 + ((v - 0x10000) >> 10)) + \
_unichr(0xdc00 + ((v - 0x10000) & 0x3ff))
else:
return _unichr(v)
_ord = ord
def ord(c):
if len(c) == 2:
return 0x10000 + ((_ord(c[0]) - 0xd800) << 10) + \
(ord(c[1]) - 0xdc00)
else:
return _ord(c)
class TestBase_Mapping(unittest.TestCase):
pass_enctest = []
pass_dectest = []
supmaps = []
def __init__(self, *args, **kw):
unittest.TestCase.__init__(self, *args, **kw)
if not os.path.exists(self.mapfilename):
raise test_support.TestSkipped('%s not found, download from %s' %
(self.mapfilename, self.mapfileurl))
def test_mapping_file(self):
unichrs = lambda s: u''.join(map(unichr, map(eval, s.split('+'))))
urt_wa = {}
for line in open(self.mapfilename):
if not line:
break
data = line.split('#')[0].strip().split()
if len(data) != 2:
continue
csetval = eval(data[0])
if csetval <= 0x7F:
csetch = chr(csetval & 0xff)
elif csetval >= 0x1000000:
csetch = chr(csetval >> 24) + chr((csetval >> 16) & 0xff) + \
chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
elif csetval >= 0x10000:
csetch = chr(csetval >> 16) + \
chr((csetval >> 8) & 0xff) + chr(csetval & 0xff)
elif csetval >= 0x100:
csetch = chr(csetval >> 8) + chr(csetval & 0xff)
else:
continue
unich = unichrs(data[1])
if ord(unich) == 0xfffd or urt_wa.has_key(unich):
continue
urt_wa[unich] = csetch
self._testpoint(csetch, unich)
def test_mapping_supplemental(self):
for mapping in self.supmaps:
self._testpoint(*mapping)
def _testpoint(self, csetch, unich):
if (csetch, unich) not in self.pass_enctest:
self.assertEqual(unich.encode(self.encoding), csetch)
if (csetch, unich) not in self.pass_dectest:
self.assertEqual(unicode(csetch, self.encoding), unich)
def load_teststring(encoding):
if __cjkcodecs__:
etxt = open(os.path.join('sampletexts', encoding) + '.txt').read()
utxt = open(os.path.join('sampletexts', encoding) + '.utf8').read()
return (etxt, utxt)
else:
from test import cjkencodings_test
return cjkencodings_test.teststring[encoding]
def register_skip_expected(*cases):
for case in cases: # len(cases) must be 1 at least.
for path in [os.path.curdir, os.path.pardir]:
fn = os.path.join(path, case.mapfilename)
if os.path.exists(fn):
case.mapfilename = fn
break
else:
sys.modules[case.__module__].skip_expected = True
break
else:
sys.modules[case.__module__].skip_expected = False
--- NEW FILE: test_normalization.py ---
from test.test_support import verbose, TestFailed, TestSkipped, verify
import sys
import os
from unicodedata import normalize
TESTDATAFILE = "NormalizationTest-3.2.0" + os.extsep + "txt"
# This search allows using a build directory just inside the source
# directory, and saving just one copy of the test data in the source
# tree, rather than having a copy in each build directory.
# There might be a better way to do this.
for path in [os.path.curdir, os.path.pardir]:
fn = os.path.join(path, TESTDATAFILE)
skip_expected = not os.path.exists(fn)
if not skip_expected:
TESTDATAFILE = fn
break
class RangeError:
pass
def NFC(str):
return normalize("NFC", str)
def NFKC(str):
return normalize("NFKC", str)
def NFD(str):
return normalize("NFD", str)
def NFKD(str):
return normalize("NFKD", str)
def unistr(data):
data = [int(x, 16) for x in data.split(" ")]
for x in data:
if x > sys.maxunicode:
raise RangeError
return u"".join([unichr(x) for x in data])
def test_main():
if skip_expected:
raise TestSkipped(TESTDATAFILE + " not found, download from " +
"http://www.unicode.org/Public/3.2-Update/" + TESTDATAFILE)
part1_data = {}
for line in open(TESTDATAFILE):
if '#' in line:
line = line.split('#')[0]
line = line.strip()
if not line:
continue
if line.startswith("@Part"):
part = line
continue
try:
c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]]
except RangeError:
# Skip unsupported characters
continue
if verbose:
print line
# Perform tests
verify(c2 == NFC(c1) == NFC(c2) == NFC(c3), line)
verify(c4 == NFC(c4) == NFC(c5), line)
verify(c3 == NFD(c1) == NFD(c2) == NFD(c3), line)
verify(c5 == NFD(c4) == NFD(c5), line)
verify(c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5),
line)
verify(c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5),
line)
# Record part 1 data
if part == "@Part1":
part1_data[c1] = 1
# Perform tests for all other data
for c in range(sys.maxunicode+1):
X = unichr(c)
if X in part1_data:
continue
assert X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c
# Check for bug 834676
normalize('NFC',u'\ud55c\uae00')
if __name__ == "__main__":
test_main()
--- NEW FILE: test_optparse.py ---
#!/usr/bin/python
#
# Test suite for Optik. Supplied by Johannes Gijsbers
# (taradino at softhome.net) -- translated from the original Optik
# test suite to this PyUnit-based version.
#
# $Id: test_optparse.py,v 1.1 2004/05/01 00:54:16 tismer Exp $
#
import sys
import os
import copy
import unittest
from cStringIO import StringIO
from pprint import pprint
from test import test_support
[...1180 lines suppressed...]
"--fie": None,
"--f": None}),
"--f")
def test_match_abbrev_error(self):
s = "--f"
wordmap = {"--foz": None, "--foo": None, "--fie": None}
possibilities = ", ".join(wordmap.keys())
self.assertRaises(_match_abbrev, BadOptionError,
"ambiguous option: --f (%s?)" % possibilities,
funcargs=[s, wordmap])
def test_main():
mod = sys.modules[__name__]
test_support.run_unittest(
*[getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
)
if __name__ == '__main__':
unittest.main()
--- NEW FILE: test_ossaudiodev.py ---
from test import test_support
test_support.requires('audio')
from test.test_support import verbose, findfile, TestFailed, TestSkipped
import errno
import fcntl
import ossaudiodev
import os
import sys
import select
import sunaudio
import time
import audioop
# Arggh, AFMT_S16_NE not defined on all platforms -- seems to be a
# fairly recent addition to OSS.
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
if sys.byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
SND_FORMAT_MULAW_8 = 1
def read_sound_file(path):
fp = open(path, 'rb')
size, enc, rate, nchannels, extra = sunaudio.gethdr(fp)
data = fp.read()
fp.close()
if enc != SND_FORMAT_MULAW_8:
print "Expect .au file with 8-bit mu-law samples"
return
# Convert the data to 16-bit signed.
data = audioop.ulaw2lin(data, 2)
return (data, rate, 16, nchannels)
def play_sound_file(data, rate, ssize, nchannels):
try:
dsp = ossaudiodev.open('w')
except IOError, msg:
if msg[0] in (errno.EACCES, errno.ENODEV, errno.EBUSY):
raise TestSkipped, msg
raise TestFailed, msg
# at least check that these methods can be invoked
dsp.bufsize()
dsp.obufcount()
dsp.obuffree()
dsp.getptr()
dsp.fileno()
# set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate)
t1 = time.time()
print "playing test sound file..."
dsp.write(data)
dsp.close()
t2 = time.time()
print "elapsed time: %.1f sec" % (t2-t1)
def test_setparameters():
dsp = ossaudiodev.open("w")
# Two configurations for testing:
# config1 (8-bit, mono, 8 kHz) should work on even the most
# ancient and crufty sound card, but maybe not on special-
# purpose high-end hardware
# config2 (16-bit, stereo, 44.1kHz) should work on all but the
# most ancient and crufty hardware
config1 = (ossaudiodev.AFMT_U8, 1, 8000)
config2 = (AFMT_S16_NE, 2, 44100)
for config in [config1, config2]:
(fmt, channels, rate) = config
if (dsp.setfmt(fmt) == fmt and
dsp.channels(channels) == channels and
dsp.speed(rate) == rate):
break
else:
raise RuntimeError("unable to set audio sampling parameters: "
"you must have really weird audio hardware")
# setparameters() should be able to set this configuration in
# either strict or non-strict mode.
result = dsp.setparameters(fmt, channels, rate, False)
assert result == (fmt, channels, rate), \
"setparameters%r: returned %r" % (config + result)
result = dsp.setparameters(fmt, channels, rate, True)
assert result == (fmt, channels, rate), \
"setparameters%r: returned %r" % (config + result)
# Now try some configurations that are presumably bogus: eg. 300
# channels currently exceeds even Hollywood's ambitions, and
# negative sampling rate is utter nonsense. setparameters() should
# accept these in non-strict mode, returning something other than
# was requested, but should barf in strict mode.
for config in [(fmt, 300, rate), # ridiculous nchannels
(fmt, -5, rate), # impossible nchannels
(fmt, channels, -50), # impossible rate
]:
(fmt, channels, rate) = config
result = dsp.setparameters(fmt, channels, rate, False)
assert result != config, \
"setparameters: unexpectedly got requested configuration"
try:
result = dsp.setparameters(fmt, channels, rate, True)
raise AssertionError("setparameters: expected OSSAudioError")
except ossaudiodev.OSSAudioError, err:
print "setparameters: got OSSAudioError as expected"
def test():
(data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
play_sound_file(data, rate, ssize, nchannels)
test_setparameters()
test()
--- NEW FILE: test_pep263.py ---
#! -*- coding: koi8-r -*-
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"ðÉÔÏÎ".encode("utf-8"),
'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
self.assertEqual(
u"\ð".encode("utf-8"),
'\\\xd0\x9f'
)
def test_main():
test_support.run_unittest(PEP263Test)
if __name__=="__main__":
test_main()
--- NEW FILE: test_pep277.py ---
# Test the Unicode versions of normal file functions
# open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir
import sys, os, unittest
from test import test_support
if not os.path.supports_unicode_filenames:
raise test_support.TestSkipped, "test works only on NT+"
filenames = [
'abc',
u'ascii',
u'Gr\xfc\xdf-Gott',
u'\u0393\u03b5\u03b9\u03ac-\u03c3\u03b1\u03c2',
u'\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435',
u'\u306b\u307d\u3093',
u'\u05d4\u05e9\u05e7\u05e6\u05e5\u05e1',
u'\u66e8\u66e9\u66eb',
u'\u66e8\u05e9\u3093\u0434\u0393\xdf',
]
# Destroy directory dirname and all files under it, to one level.
def deltree(dirname):
# Don't hide legitimate errors: if one of these suckers exists, it's
# an error if we can't remove it.
if os.path.exists(dirname):
# must pass unicode to os.listdir() so we get back unicode results.
for fname in os.listdir(unicode(dirname)):
os.unlink(os.path.join(dirname, fname))
os.rmdir(dirname)
class UnicodeFileTests(unittest.TestCase):
files = [os.path.join(test_support.TESTFN, f) for f in filenames]
def setUp(self):
try:
os.mkdir(test_support.TESTFN)
except OSError:
pass
for name in self.files:
f = open(name, 'w')
f.write((name+'\n').encode("utf-8"))
f.close()
os.stat(name)
def tearDown(self):
deltree(test_support.TESTFN)
def _apply_failure(self, fn, filename, expected_exception,
check_fn_in_exception = True):
try:
fn(filename)
raise test_support.TestFailed("Expected to fail calling '%s(%r)'"
% (fn.__name__, filename))
except expected_exception, details:
if check_fn_in_exception and details.filename != filename:
raise test_support.TestFailed("Function '%s(%r) failed with "
"bad filename in the exception: %r"
% (fn.__name__, filename,
details.filename))
def test_failures(self):
# Pass non-existing Unicode filenames all over the place.
for name in self.files:
name = "not_" + name
self._apply_failure(open, name, IOError)
self._apply_failure(os.stat, name, OSError)
self._apply_failure(os.chdir, name, OSError)
self._apply_failure(os.rmdir, name, OSError)
self._apply_failure(os.remove, name, OSError)
# listdir may append a wildcard to the filename, so dont check
self._apply_failure(os.listdir, name, OSError, False)
def test_open(self):
for name in self.files:
f = open(name, 'w')
f.write((name+'\n').encode("utf-8"))
f.close()
os.stat(name)
def test_listdir(self):
f1 = os.listdir(test_support.TESTFN)
f1.sort()
f2 = os.listdir(unicode(test_support.TESTFN,
sys.getfilesystemencoding()))
f2.sort()
print f1
print f2
def test_rename(self):
for name in self.files:
os.rename(name,"tmp")
os.rename("tmp",name)
def test_directory(self):
dirname = os.path.join(test_support.TESTFN,u'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
filename = u'\xdf-\u66e8\u66e9\u66eb'
oldwd = os.getcwd()
os.mkdir(dirname)
os.chdir(dirname)
f = open(filename, 'w')
f.write((filename + '\n').encode("utf-8"))
f.close()
print repr(filename)
os.access(filename,os.R_OK)
os.remove(filename)
os.chdir(oldwd)
os.rmdir(dirname)
def test_main():
try:
test_support.run_unittest(UnicodeFileTests)
finally:
deltree(test_support.TESTFN)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_pickletools.py ---
import pickletools
from test import test_support
test_support.run_doctest(pickletools)
--- NEW FILE: test_plistlib.py ---
# Copyright (C) 2003 Python Software Foundation
import unittest
import plistlib
import os
from test import test_support
class TestPlistlib(unittest.TestCase):
def tearDown(self):
try:
os.unlink(test_support.TESTFN)
except:
pass
def _create(self):
pl = plistlib.Plist(
aString="Doodah",
aList=["A", "B", 12, 32.1, [1, 2, 3]],
aFloat = 0.1,
anInt = 728,
aDict=plistlib.Dict(
anotherString="<hello & hi there!>",
aUnicodeValue=u'M\xe4ssig, Ma\xdf',
aTrueValue=True,
aFalseValue=False,
),
someData = plistlib.Data("<binary gunk>"),
someMoreData = plistlib.Data("<lots of binary gunk>" * 10),
)
pl['anotherInt'] = 42
try:
from xml.utils.iso8601 import parse
import time
except ImportError:
pass
else:
pl['aDate'] = plistlib.Date(time.mktime(time.gmtime()))
return pl
def test_create(self):
pl = self._create()
self.assertEqual(pl["aString"], "Doodah")
self.assertEqual(pl["aDict"]["aFalseValue"], False)
def test_io(self):
pl = self._create()
pl.write(test_support.TESTFN)
pl2 = plistlib.Plist.fromFile(test_support.TESTFN)
self.assertEqual(dict(pl), dict(pl2))
def test_stringio(self):
from StringIO import StringIO
f = StringIO()
pl = self._create()
pl.write(f)
pl2 = plistlib.Plist.fromFile(StringIO(f.getvalue()))
self.assertEqual(dict(pl), dict(pl2))
def test_cstringio(self):
from cStringIO import StringIO
f = StringIO()
pl = self._create()
pl.write(f)
pl2 = plistlib.Plist.fromFile(StringIO(f.getvalue()))
self.assertEqual(dict(pl), dict(pl2))
def test_main():
test_support.run_unittest(TestPlistlib)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_popen.py ---
#! /usr/bin/env python
"""Basic tests for os.popen()
Particularly useful for platforms that fake popen.
"""
import os
import sys
from test.test_support import TestSkipped
from os import popen
# Test that command-lines get down as we expect.
# To do this we execute:
# python -c "import sys;print sys.argv" {rest_of_commandline}
# This results in Python being spawned and printing the sys.argv list.
# We can then eval() the result of this, and see what each argv was.
python = sys.executable
if ' ' in python:
python = '"' + python + '"' # quote embedded space for cmdline
def _do_test_commandline(cmdline, expected):
cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline)
data = popen(cmd).read()
got = eval(data)[1:] # strip off argv[0]
if got != expected:
print "Error in popen commandline handling."
print " executed '%s', expected '%r', but got '%r'" \
% (cmdline, expected, got)
def _test_commandline():
_do_test_commandline("foo bar", ["foo", "bar"])
_do_test_commandline('foo "spam and eggs" "silly walk"', ["foo", "spam and eggs", "silly walk"])
_do_test_commandline('foo "a \\"quoted\\" arg" bar', ["foo", 'a "quoted" arg', "bar"])
print "popen seemed to process the command-line correctly"
def main():
print "Test popen:"
_test_commandline()
main()
--- NEW FILE: test_posix.py ---
"Test posix functions"
from test import test_support
try:
import posix
except ImportError:
raise test_support.TestSkipped, "posix is not available"
import time
import os
import sys
import unittest
import warnings
warnings.filterwarnings('ignore', '.* potential security risk .*',
RuntimeWarning)
class PosixTester(unittest.TestCase):
def setUp(self):
# create empty file
fp = open(test_support.TESTFN, 'w+')
fp.close()
def tearDown(self):
os.unlink(test_support.TESTFN)
def testNoArgFunctions(self):
# test posix functions which take no arguments and have
# no side-effects which we need to cleanup (e.g., fork, wait, abort)
NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname",
"times", "getloadavg", "tmpnam",
"getegid", "geteuid", "getgid", "getgroups",
"getpid", "getpgrp", "getppid", "getuid",
]
for name in NO_ARG_FUNCTIONS:
posix_func = getattr(posix, name, None)
if posix_func is not None:
posix_func()
self.assertRaises(TypeError, posix_func, 1)
def test_statvfs(self):
if hasattr(posix, 'statvfs'):
self.assert_(posix.statvfs(os.curdir))
def test_fstatvfs(self):
if hasattr(posix, 'fstatvfs'):
fp = open(test_support.TESTFN)
try:
self.assert_(posix.fstatvfs(fp.fileno()))
finally:
fp.close()
def test_ftruncate(self):
if hasattr(posix, 'ftruncate'):
fp = open(test_support.TESTFN, 'w+')
try:
# we need to have some data to truncate
fp.write('test')
fp.flush()
posix.ftruncate(fp.fileno(), 0)
finally:
fp.close()
def test_dup(self):
if hasattr(posix, 'dup'):
fp = open(test_support.TESTFN)
try:
fd = posix.dup(fp.fileno())
self.assert_(isinstance(fd, int))
os.close(fd)
finally:
fp.close()
def test_dup2(self):
if hasattr(posix, 'dup2'):
fp1 = open(test_support.TESTFN)
fp2 = open(test_support.TESTFN)
try:
posix.dup2(fp1.fileno(), fp2.fileno())
finally:
fp1.close()
fp2.close()
def fdopen_helper(self, *args):
fd = os.open(test_support.TESTFN, os.O_RDONLY)
fp2 = posix.fdopen(fd, *args)
fp2.close()
def test_fdopen(self):
if hasattr(posix, 'fdopen'):
self.fdopen_helper()
self.fdopen_helper('r')
self.fdopen_helper('r', 100)
def test_fstat(self):
if hasattr(posix, 'fstat'):
fp = open(test_support.TESTFN)
try:
self.assert_(posix.fstat(fp.fileno()))
finally:
fp.close()
def test_stat(self):
if hasattr(posix, 'stat'):
self.assert_(posix.stat(test_support.TESTFN))
def test_chdir(self):
if hasattr(posix, 'chdir'):
posix.chdir(os.curdir)
self.assertRaises(OSError, posix.chdir, test_support.TESTFN)
def test_lsdir(self):
if hasattr(posix, 'lsdir'):
self.assert_(test_support.TESTFN in posix.lsdir(os.curdir))
def test_access(self):
if hasattr(posix, 'access'):
self.assert_(posix.access(test_support.TESTFN, os.R_OK))
def test_umask(self):
if hasattr(posix, 'umask'):
old_mask = posix.umask(0)
self.assert_(isinstance(old_mask, int))
posix.umask(old_mask)
def test_strerror(self):
if hasattr(posix, 'strerror'):
self.assert_(posix.strerror(0))
def test_pipe(self):
if hasattr(posix, 'pipe'):
reader, writer = posix.pipe()
os.close(reader)
os.close(writer)
def test_tempnam(self):
if hasattr(posix, 'tempnam'):
self.assert_(posix.tempnam())
self.assert_(posix.tempnam(os.curdir))
self.assert_(posix.tempnam(os.curdir, 'blah'))
def test_tmpfile(self):
if hasattr(posix, 'tmpfile'):
fp = posix.tmpfile()
fp.close()
def test_utime(self):
if hasattr(posix, 'utime'):
now = time.time()
posix.utime(test_support.TESTFN, None)
posix.utime(test_support.TESTFN, (now, now))
def test_main():
test_support.run_unittest(PosixTester)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_resource.py ---
import os
import resource
from test.test_support import TESTFN
# This test is checking a few specific problem spots. RLIMIT_FSIZE
# should be RLIM_INFINITY, which will be a really big number on a
# platform with large file support. On these platforms, we need to
# test that the get/setrlimit functions properly convert the number to
# a C long long and that the conversion doesn't raise an error.
try:
cur, max = resource.getrlimit(resource.RLIMIT_FSIZE)
except AttributeError:
pass
else:
print resource.RLIM_INFINITY == max
resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
# Now check to see what happens when the RLIMIT_FSIZE is small. Some
# versions of Python were terminated by an uncaught SIGXFSZ, but
# pythonrun.c has been fixed to ignore that exception. If so, the
# write() should return EFBIG when the limit is exceeded.
# At least one platform has an unlimited RLIMIT_FSIZE and attempts to
# change it raise ValueError instead.
try:
try:
resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max))
limit_set = 1
except ValueError:
limit_set = 0
f = open(TESTFN, "wb")
f.write("X" * 1024)
try:
f.write("Y")
f.flush()
except IOError:
if not limit_set:
raise
f.close()
os.unlink(TESTFN)
finally:
resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
# And be sure that setrlimit is checking for really large values
too_big = 10L**50
try:
resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max))
except (OverflowError, ValueError):
pass
try:
resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big))
except (OverflowError, ValueError):
pass
--- NEW FILE: test_robotparser.py ---
import unittest, StringIO, robotparser
from test import test_support
class RobotTestCase(unittest.TestCase):
def __init__(self, index, parser, url, good, agent):
unittest.TestCase.__init__(self)
if good:
self.str = "RobotTest(%d, good, %s)" % (index, url)
else:
self.str = "RobotTest(%d, bad, %s)" % (index, url)
self.parser = parser
self.url = url
self.good = good
self.agent = agent
def runTest(self):
if isinstance(self.url, tuple):
agent, url = self.url
else:
url = self.url
agent = self.agent
if self.good:
self.failUnless(self.parser.can_fetch(agent, url))
else:
self.failIf(self.parser.can_fetch(agent, url))
def __str__(self):
return self.str
tests = unittest.TestSuite()
def RobotTest(index, robots_txt, good_urls, bad_urls,
agent="test_robotparser"):
lines = StringIO.StringIO(robots_txt).readlines()
parser = robotparser.RobotFileParser()
parser.parse(lines)
for url in good_urls:
tests.addTest(RobotTestCase(index, parser, url, 1, agent))
for url in bad_urls:
tests.addTest(RobotTestCase(index, parser, url, 0, agent))
# Examples from http://www.robotstxt.org/wc/norobots.html (fetched 2002)
# 1.
doc = """
User-agent: *
Disallow: /cyberworld/map/ # This is an infinite virtual URL space
Disallow: /tmp/ # these will soon disappear
Disallow: /foo.html
"""
good = ['/','/test.html']
bad = ['/cyberworld/map/index.html','/tmp/xxx','/foo.html']
RobotTest(1, doc, good, bad)
# 2.
doc = """
# robots.txt for http://www.example.com/
User-agent: *
Disallow: /cyberworld/map/ # This is an infinite virtual URL space
# Cybermapper knows where to go.
User-agent: cybermapper
Disallow:
"""
good = ['/','/test.html',('cybermapper','/cyberworld/map/index.html')]
bad = ['/cyberworld/map/index.html']
RobotTest(2, doc, good, bad)
# 3.
doc = """
# go away
User-agent: *
Disallow: /
"""
good = []
bad = ['/cyberworld/map/index.html','/','/tmp/']
RobotTest(3, doc, good, bad)
# Examples from http://www.robotstxt.org/wc/norobots-rfc.html (fetched 2002)
# 4.
doc = """
User-agent: figtree
Disallow: /tmp
Disallow: /a%3cd.html
Disallow: /a%2fb.html
Disallow: /%7ejoe/index.html
"""
good = [] # XFAIL '/a/b.html'
bad = ['/tmp','/tmp.html','/tmp/a.html',
'/a%3cd.html','/a%3Cd.html','/a%2fb.html',
'/~joe/index.html'
]
RobotTest(4, doc, good, bad, 'figtree')
RobotTest(5, doc, good, bad, 'FigTree Robot libwww-perl/5.04')
# 6.
doc = """
User-agent: *
Disallow: /tmp/
Disallow: /a%3Cd.html
Disallow: /a/b.html
Disallow: /%7ejoe/index.html
"""
good = ['/tmp',] # XFAIL: '/a%2fb.html'
bad = ['/tmp/','/tmp/a.html',
'/a%3cd.html','/a%3Cd.html',"/a/b.html",
'/%7Ejoe/index.html']
RobotTest(6, doc, good, bad)
# From bug report #523041
# 7.
doc = """
User-Agent: *
Disallow: /.
"""
good = ['/foo.html']
bad = [] # Bug report says "/" should be denied, but that is not in the RFC
RobotTest(7, doc, good, bad)
def test_main():
test_support.run_suite(tests)
if __name__=='__main__':
test_support.Verbose = 1
test_support.run_suite(tests)
--- NEW FILE: test_scriptpackages.py ---
# Copyright (C) 2003 Python Software Foundation
import unittest
import os
import sys
import tempfile
from test import test_support
import aetools
class TestScriptpackages(unittest.TestCase):
def _test_scriptpackage(self, package, testobject=1):
# Check that we can import the package
mod = __import__(package)
# Test that we can get the main event class
klass = getattr(mod, package)
# Test that we can instantiate that class
talker = klass()
if testobject:
# Test that we can get an application object
obj = mod.application(0)
def test__builtinSuites(self):
self._test_scriptpackage('_builtinSuites', testobject=0)
def test_StdSuites(self):
self._test_scriptpackage('StdSuites')
def test_SystemEvents(self):
self._test_scriptpackage('SystemEvents')
def test_Finder(self):
self._test_scriptpackage('Finder')
def test_Terminal(self):
self._test_scriptpackage('Terminal')
def test_Netscape(self):
self._test_scriptpackage('Netscape')
def test_Explorer(self):
self._test_scriptpackage('Explorer')
def test_CodeWarrior(self):
self._test_scriptpackage('CodeWarrior')
def test_main():
test_support.run_unittest(TestScriptpackages)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_set.py ---
import unittest
from test import test_support
import operator
import copy
import pickle
class PassThru(Exception):
pass
def check_pass_thru():
raise PassThru
yield 1
class TestJointOps(unittest.TestCase):
# Tests common to both set and frozenset
def setUp(self):
self.word = word = 'simsalabim'
self.otherword = 'madagascar'
[...1289 lines suppressed...]
TestCopyingTuple,
TestCopyingNested,
TestIdentities,
TestVariousIteratorArgs,
)
test_support.run_unittest(*test_classes)
# verify reference counting
if verbose and hasattr(sys, "gettotalrefcount"):
import gc
counts = [None] * 5
for i in xrange(len(counts)):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
print counts
if __name__ == "__main__":
test_main(verbose=True)
--- NEW FILE: test_sets.py ---
#!/usr/bin/env python
import unittest, operator, copy, pickle, random
from sets import Set, ImmutableSet
from test import test_support
empty_set = Set()
#==============================================================================
class TestBasicOps(unittest.TestCase):
def test_repr(self):
if self.repr is not None:
self.assertEqual(repr(self.set), self.repr)
def test_length(self):
self.assertEqual(len(self.set), self.length)
def test_self_equality(self):
self.assertEqual(self.set, self.set)
def test_equivalent_equality(self):
self.assertEqual(self.set, self.dup)
def test_copy(self):
self.assertEqual(self.set.copy(), self.dup)
def test_self_union(self):
result = self.set | self.set
self.assertEqual(result, self.dup)
def test_empty_union(self):
result = self.set | empty_set
self.assertEqual(result, self.dup)
def test_union_empty(self):
result = empty_set | self.set
self.assertEqual(result, self.dup)
def test_self_intersection(self):
result = self.set & self.set
self.assertEqual(result, self.dup)
def test_empty_intersection(self):
result = self.set & empty_set
self.assertEqual(result, empty_set)
def test_intersection_empty(self):
result = empty_set & self.set
self.assertEqual(result, empty_set)
def test_self_symmetric_difference(self):
result = self.set ^ self.set
self.assertEqual(result, empty_set)
def checkempty_symmetric_difference(self):
result = self.set ^ empty_set
self.assertEqual(result, self.set)
def test_self_difference(self):
result = self.set - self.set
self.assertEqual(result, empty_set)
def test_empty_difference(self):
result = self.set - empty_set
self.assertEqual(result, self.dup)
def test_empty_difference_rev(self):
result = empty_set - self.set
self.assertEqual(result, empty_set)
def test_iteration(self):
for v in self.set:
self.assert_(v in self.values)
def test_pickling(self):
p = pickle.dumps(self.set)
copy = pickle.loads(p)
self.assertEqual(self.set, copy,
"%s != %s" % (self.set, copy))
#------------------------------------------------------------------------------
class TestBasicOpsEmpty(TestBasicOps):
def setUp(self):
self.case = "empty set"
self.values = []
self.set = Set(self.values)
self.dup = Set(self.values)
self.length = 0
self.repr = "Set([])"
#------------------------------------------------------------------------------
class TestBasicOpsSingleton(TestBasicOps):
def setUp(self):
self.case = "unit set (number)"
self.values = [3]
self.set = Set(self.values)
self.dup = Set(self.values)
self.length = 1
self.repr = "Set([3])"
def test_in(self):
self.failUnless(3 in self.set)
def test_not_in(self):
self.failUnless(2 not in self.set)
#------------------------------------------------------------------------------
class TestBasicOpsTuple(TestBasicOps):
def setUp(self):
self.case = "unit set (tuple)"
self.values = [(0, "zero")]
self.set = Set(self.values)
self.dup = Set(self.values)
self.length = 1
self.repr = "Set([(0, 'zero')])"
def test_in(self):
self.failUnless((0, "zero") in self.set)
def test_not_in(self):
self.failUnless(9 not in self.set)
#------------------------------------------------------------------------------
class TestBasicOpsTriple(TestBasicOps):
def setUp(self):
self.case = "triple set"
self.values = [0, "zero", operator.add]
self.set = Set(self.values)
self.dup = Set(self.values)
self.length = 3
self.repr = None
#==============================================================================
def baditer():
raise TypeError
yield True
def gooditer():
yield True
class TestExceptionPropagation(unittest.TestCase):
"""SF 628246: Set constructor should not trap iterator TypeErrors"""
def test_instanceWithException(self):
self.assertRaises(TypeError, Set, baditer())
def test_instancesWithoutException(self):
# All of these iterables should load without exception.
Set([1,2,3])
Set((1,2,3))
Set({'one':1, 'two':2, 'three':3})
Set(xrange(3))
Set('abc')
Set(gooditer())
#==============================================================================
class TestSetOfSets(unittest.TestCase):
def test_constructor(self):
inner = Set([1])
outer = Set([inner])
element = outer.pop()
self.assertEqual(type(element), ImmutableSet)
outer.add(inner) # Rebuild set of sets with .add method
outer.remove(inner)
self.assertEqual(outer, Set()) # Verify that remove worked
outer.discard(inner) # Absence of KeyError indicates working fine
#==============================================================================
class TestBinaryOps(unittest.TestCase):
def setUp(self):
self.set = Set((2, 4, 6))
def test_eq(self): # SF bug 643115
self.assertEqual(self.set, Set({2:1,4:3,6:5}))
def test_union_subset(self):
result = self.set | Set([2])
self.assertEqual(result, Set((2, 4, 6)))
def test_union_superset(self):
result = self.set | Set([2, 4, 6, 8])
self.assertEqual(result, Set([2, 4, 6, 8]))
def test_union_overlap(self):
result = self.set | Set([3, 4, 5])
self.assertEqual(result, Set([2, 3, 4, 5, 6]))
def test_union_non_overlap(self):
result = self.set | Set([8])
self.assertEqual(result, Set([2, 4, 6, 8]))
def test_intersection_subset(self):
result = self.set & Set((2, 4))
self.assertEqual(result, Set((2, 4)))
def test_intersection_superset(self):
result = self.set & Set([2, 4, 6, 8])
self.assertEqual(result, Set([2, 4, 6]))
def test_intersection_overlap(self):
result = self.set & Set([3, 4, 5])
self.assertEqual(result, Set([4]))
def test_intersection_non_overlap(self):
result = self.set & Set([8])
self.assertEqual(result, empty_set)
def test_sym_difference_subset(self):
result = self.set ^ Set((2, 4))
self.assertEqual(result, Set([6]))
def test_sym_difference_superset(self):
result = self.set ^ Set((2, 4, 6, 8))
self.assertEqual(result, Set([8]))
def test_sym_difference_overlap(self):
result = self.set ^ Set((3, 4, 5))
self.assertEqual(result, Set([2, 3, 5, 6]))
def test_sym_difference_non_overlap(self):
result = self.set ^ Set([8])
self.assertEqual(result, Set([2, 4, 6, 8]))
def test_cmp(self):
a, b = Set('a'), Set('b')
self.assertRaises(TypeError, cmp, a, b)
# You can view this as a buglet: cmp(a, a) does not raise TypeError,
# because __eq__ is tried before __cmp__, and a.__eq__(a) returns True,
# which Python thinks is good enough to synthesize a cmp() result
# without calling __cmp__.
self.assertEqual(cmp(a, a), 0)
self.assertRaises(TypeError, cmp, a, 12)
self.assertRaises(TypeError, cmp, "abc", a)
#==============================================================================
class TestUpdateOps(unittest.TestCase):
def setUp(self):
self.set = Set((2, 4, 6))
def test_union_subset(self):
self.set |= Set([2])
self.assertEqual(self.set, Set((2, 4, 6)))
def test_union_superset(self):
self.set |= Set([2, 4, 6, 8])
self.assertEqual(self.set, Set([2, 4, 6, 8]))
def test_union_overlap(self):
self.set |= Set([3, 4, 5])
self.assertEqual(self.set, Set([2, 3, 4, 5, 6]))
def test_union_non_overlap(self):
self.set |= Set([8])
self.assertEqual(self.set, Set([2, 4, 6, 8]))
def test_union_method_call(self):
self.set.union_update(Set([3, 4, 5]))
self.assertEqual(self.set, Set([2, 3, 4, 5, 6]))
def test_intersection_subset(self):
self.set &= Set((2, 4))
self.assertEqual(self.set, Set((2, 4)))
def test_intersection_superset(self):
self.set &= Set([2, 4, 6, 8])
self.assertEqual(self.set, Set([2, 4, 6]))
def test_intersection_overlap(self):
self.set &= Set([3, 4, 5])
self.assertEqual(self.set, Set([4]))
def test_intersection_non_overlap(self):
self.set &= Set([8])
self.assertEqual(self.set, empty_set)
def test_intersection_method_call(self):
self.set.intersection_update(Set([3, 4, 5]))
self.assertEqual(self.set, Set([4]))
def test_sym_difference_subset(self):
self.set ^= Set((2, 4))
self.assertEqual(self.set, Set([6]))
def test_sym_difference_superset(self):
self.set ^= Set((2, 4, 6, 8))
self.assertEqual(self.set, Set([8]))
def test_sym_difference_overlap(self):
self.set ^= Set((3, 4, 5))
self.assertEqual(self.set, Set([2, 3, 5, 6]))
def test_sym_difference_non_overlap(self):
self.set ^= Set([8])
self.assertEqual(self.set, Set([2, 4, 6, 8]))
def test_sym_difference_method_call(self):
self.set.symmetric_difference_update(Set([3, 4, 5]))
self.assertEqual(self.set, Set([2, 3, 5, 6]))
def test_difference_subset(self):
self.set -= Set((2, 4))
self.assertEqual(self.set, Set([6]))
def test_difference_superset(self):
self.set -= Set((2, 4, 6, 8))
self.assertEqual(self.set, Set([]))
def test_difference_overlap(self):
self.set -= Set((3, 4, 5))
self.assertEqual(self.set, Set([2, 6]))
def test_difference_non_overlap(self):
self.set -= Set([8])
self.assertEqual(self.set, Set([2, 4, 6]))
def test_difference_method_call(self):
self.set.difference_update(Set([3, 4, 5]))
self.assertEqual(self.set, Set([2, 6]))
#==============================================================================
class TestMutate(unittest.TestCase):
def setUp(self):
self.values = ["a", "b", "c"]
self.set = Set(self.values)
def test_add_present(self):
self.set.add("c")
self.assertEqual(self.set, Set("abc"))
def test_add_absent(self):
self.set.add("d")
self.assertEqual(self.set, Set("abcd"))
def test_add_until_full(self):
tmp = Set()
expected_len = 0
for v in self.values:
tmp.add(v)
expected_len += 1
self.assertEqual(len(tmp), expected_len)
self.assertEqual(tmp, self.set)
def test_remove_present(self):
self.set.remove("b")
self.assertEqual(self.set, Set("ac"))
def test_remove_absent(self):
try:
self.set.remove("d")
self.fail("Removing missing element should have raised LookupError")
except LookupError:
pass
def test_remove_until_empty(self):
expected_len = len(self.set)
for v in self.values:
self.set.remove(v)
expected_len -= 1
self.assertEqual(len(self.set), expected_len)
def test_discard_present(self):
self.set.discard("c")
self.assertEqual(self.set, Set("ab"))
def test_discard_absent(self):
self.set.discard("d")
self.assertEqual(self.set, Set("abc"))
def test_clear(self):
self.set.clear()
self.assertEqual(len(self.set), 0)
def test_pop(self):
popped = {}
while self.set:
popped[self.set.pop()] = None
self.assertEqual(len(popped), len(self.values))
for v in self.values:
self.failUnless(v in popped)
def test_update_empty_tuple(self):
self.set.union_update(())
self.assertEqual(self.set, Set(self.values))
def test_update_unit_tuple_overlap(self):
self.set.union_update(("a",))
self.assertEqual(self.set, Set(self.values))
def test_update_unit_tuple_non_overlap(self):
self.set.union_update(("a", "z"))
self.assertEqual(self.set, Set(self.values + ["z"]))
#==============================================================================
class TestSubsets(unittest.TestCase):
case2method = {"<=": "issubset",
">=": "issuperset",
}
reverse = {"==": "==",
"!=": "!=",
"<": ">",
">": "<",
"<=": ">=",
">=": "<=",
}
def test_issubset(self):
x = self.left
y = self.right
for case in "!=", "==", "<", "<=", ">", ">=":
expected = case in self.cases
# Test the binary infix spelling.
result = eval("x" + case + "y", locals())
self.assertEqual(result, expected)
# Test the "friendly" method-name spelling, if one exists.
if case in TestSubsets.case2method:
method = getattr(x, TestSubsets.case2method[case])
result = method(y)
self.assertEqual(result, expected)
# Now do the same for the operands reversed.
rcase = TestSubsets.reverse[case]
result = eval("y" + rcase + "x", locals())
self.assertEqual(result, expected)
if rcase in TestSubsets.case2method:
method = getattr(y, TestSubsets.case2method[rcase])
result = method(x)
self.assertEqual(result, expected)
#------------------------------------------------------------------------------
class TestSubsetEqualEmpty(TestSubsets):
left = Set()
right = Set()
name = "both empty"
cases = "==", "<=", ">="
#------------------------------------------------------------------------------
class TestSubsetEqualNonEmpty(TestSubsets):
left = Set([1, 2])
right = Set([1, 2])
name = "equal pair"
cases = "==", "<=", ">="
#------------------------------------------------------------------------------
class TestSubsetEmptyNonEmpty(TestSubsets):
left = Set()
right = Set([1, 2])
name = "one empty, one non-empty"
cases = "!=", "<", "<="
#------------------------------------------------------------------------------
class TestSubsetPartial(TestSubsets):
left = Set([1])
right = Set([1, 2])
name = "one a non-empty proper subset of other"
cases = "!=", "<", "<="
#------------------------------------------------------------------------------
class TestSubsetNonOverlap(TestSubsets):
left = Set([1])
right = Set([2])
name = "neither empty, neither contains"
cases = "!="
#==============================================================================
class TestOnlySetsInBinaryOps(unittest.TestCase):
def test_eq_ne(self):
# Unlike the others, this is testing that == and != *are* allowed.
self.assertEqual(self.other == self.set, False)
self.assertEqual(self.set == self.other, False)
self.assertEqual(self.other != self.set, True)
self.assertEqual(self.set != self.other, True)
def test_ge_gt_le_lt(self):
self.assertRaises(TypeError, lambda: self.set < self.other)
self.assertRaises(TypeError, lambda: self.set <= self.other)
self.assertRaises(TypeError, lambda: self.set > self.other)
self.assertRaises(TypeError, lambda: self.set >= self.other)
self.assertRaises(TypeError, lambda: self.other < self.set)
self.assertRaises(TypeError, lambda: self.other <= self.set)
self.assertRaises(TypeError, lambda: self.other > self.set)
self.assertRaises(TypeError, lambda: self.other >= self.set)
def test_union_update_operator(self):
try:
self.set |= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_union_update(self):
if self.otherIsIterable:
self.set.union_update(self.other)
else:
self.assertRaises(TypeError, self.set.union_update, self.other)
def test_union(self):
self.assertRaises(TypeError, lambda: self.set | self.other)
self.assertRaises(TypeError, lambda: self.other | self.set)
if self.otherIsIterable:
self.set.union(self.other)
else:
self.assertRaises(TypeError, self.set.union, self.other)
def test_intersection_update_operator(self):
try:
self.set &= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_intersection_update(self):
if self.otherIsIterable:
self.set.intersection_update(self.other)
else:
self.assertRaises(TypeError,
self.set.intersection_update,
self.other)
def test_intersection(self):
self.assertRaises(TypeError, lambda: self.set & self.other)
self.assertRaises(TypeError, lambda: self.other & self.set)
if self.otherIsIterable:
self.set.intersection(self.other)
else:
self.assertRaises(TypeError, self.set.intersection, self.other)
def test_sym_difference_update_operator(self):
try:
self.set ^= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_sym_difference_update(self):
if self.otherIsIterable:
self.set.symmetric_difference_update(self.other)
else:
self.assertRaises(TypeError,
self.set.symmetric_difference_update,
self.other)
def test_sym_difference(self):
self.assertRaises(TypeError, lambda: self.set ^ self.other)
self.assertRaises(TypeError, lambda: self.other ^ self.set)
if self.otherIsIterable:
self.set.symmetric_difference(self.other)
else:
self.assertRaises(TypeError, self.set.symmetric_difference, self.other)
def test_difference_update_operator(self):
try:
self.set -= self.other
except TypeError:
pass
else:
self.fail("expected TypeError")
def test_difference_update(self):
if self.otherIsIterable:
self.set.difference_update(self.other)
else:
self.assertRaises(TypeError,
self.set.difference_update,
self.other)
def test_difference(self):
self.assertRaises(TypeError, lambda: self.set - self.other)
self.assertRaises(TypeError, lambda: self.other - self.set)
if self.otherIsIterable:
self.set.difference(self.other)
else:
self.assertRaises(TypeError, self.set.difference, self.other)
#------------------------------------------------------------------------------
class TestOnlySetsNumeric(TestOnlySetsInBinaryOps):
def setUp(self):
self.set = Set((1, 2, 3))
self.other = 19
self.otherIsIterable = False
#------------------------------------------------------------------------------
class TestOnlySetsDict(TestOnlySetsInBinaryOps):
def setUp(self):
self.set = Set((1, 2, 3))
self.other = {1:2, 3:4}
self.otherIsIterable = True
#------------------------------------------------------------------------------
class TestOnlySetsOperator(TestOnlySetsInBinaryOps):
def setUp(self):
self.set = Set((1, 2, 3))
self.other = operator.add
self.otherIsIterable = False
#------------------------------------------------------------------------------
class TestOnlySetsTuple(TestOnlySetsInBinaryOps):
def setUp(self):
self.set = Set((1, 2, 3))
self.other = (2, 4, 6)
self.otherIsIterable = True
#------------------------------------------------------------------------------
class TestOnlySetsString(TestOnlySetsInBinaryOps):
def setUp(self):
self.set = Set((1, 2, 3))
self.other = 'abc'
self.otherIsIterable = True
#------------------------------------------------------------------------------
class TestOnlySetsGenerator(TestOnlySetsInBinaryOps):
def setUp(self):
def gen():
for i in xrange(0, 10, 2):
yield i
self.set = Set((1, 2, 3))
self.other = gen()
self.otherIsIterable = True
#------------------------------------------------------------------------------
class TestOnlySetsofSets(TestOnlySetsInBinaryOps):
def setUp(self):
self.set = Set((1, 2, 3))
self.other = [Set('ab'), ImmutableSet('cd')]
self.otherIsIterable = True
#==============================================================================
class TestCopying(unittest.TestCase):
def test_copy(self):
dup = self.set.copy()
dup_list = list(dup); dup_list.sort()
set_list = list(self.set); set_list.sort()
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.failUnless(dup_list[i] is set_list[i])
def test_deep_copy(self):
dup = copy.deepcopy(self.set)
##print type(dup), repr(dup)
dup_list = list(dup); dup_list.sort()
set_list = list(self.set); set_list.sort()
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.assertEqual(dup_list[i], set_list[i])
#------------------------------------------------------------------------------
class TestCopyingEmpty(TestCopying):
def setUp(self):
self.set = Set()
#------------------------------------------------------------------------------
class TestCopyingSingleton(TestCopying):
def setUp(self):
self.set = Set(["hello"])
#------------------------------------------------------------------------------
class TestCopyingTriple(TestCopying):
def setUp(self):
self.set = Set(["zero", 0, None])
#------------------------------------------------------------------------------
class TestCopyingTuple(TestCopying):
def setUp(self):
self.set = Set([(1, 2)])
#------------------------------------------------------------------------------
class TestCopyingNested(TestCopying):
def setUp(self):
self.set = Set([((1, 2), (3, 4))])
#==============================================================================
class TestIdentities(unittest.TestCase):
def setUp(self):
self.a = Set([random.randrange(100) for i in xrange(50)])
self.b = Set([random.randrange(100) for i in xrange(50)])
def test_binopsVsSubsets(self):
a, b = self.a, self.b
self.assert_(a - b <= a)
self.assert_(b - a <= b)
self.assert_(a & b <= a)
self.assert_(a & b <= b)
self.assert_(a | b >= a)
self.assert_(a | b >= b)
self.assert_(a ^ b <= a | b)
def test_commutativity(self):
a, b = self.a, self.b
self.assertEqual(a&b, b&a)
self.assertEqual(a|b, b|a)
self.assertEqual(a^b, b^a)
if a != b:
self.assertNotEqual(a-b, b-a)
def test_reflexsive_relations(self):
a, zero = self.a, Set()
self.assertEqual(a ^ a, zero)
self.assertEqual(a - a, zero)
self.assertEqual(a | a, a)
self.assertEqual(a & a, a)
self.assert_(a <= a)
self.assert_(a >= a)
self.assert_(a == a)
def test_summations(self):
# check that sums of parts equal the whole
a, b = self.a, self.b
self.assertEqual((a-b)|(a&b)|(b-a), a|b)
self.assertEqual((a&b)|(a^b), a|b)
self.assertEqual(a|(b-a), a|b)
self.assertEqual((a-b)|b, a|b)
self.assertEqual((a-b)|(a&b), a)
self.assertEqual((b-a)|(a&b), b)
self.assertEqual((a-b)|(b-a), a^b)
def test_exclusion(self):
# check that inverse operations do not overlap
a, b, zero = self.a, self.b, Set()
self.assertEqual((a-b)&b, zero)
self.assertEqual((b-a)&a, zero)
self.assertEqual((a&b)&(a^b), zero)
def test_cardinality_relations(self):
a, b = self.a, self.b
self.assertEqual(len(a), len(a-b) + len(a&b))
self.assertEqual(len(b), len(b-a) + len(a&b))
self.assertEqual(len(a^b), len(a-b) + len(b-a))
self.assertEqual(len(a|b), len(a-b) + len(a&b) + len(b-a))
self.assertEqual(len(a^b) + len(a&b), len(a|b))
#==============================================================================
libreftest = """
Example from the Library Reference: Doc/lib/libsets.tex
>>> from sets import Set as Base # override _repr to get sorted output
>>> class Set(Base):
... def _repr(self):
... return Base._repr(self, sorted=True)
>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
>>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
>>> employees = engineers | programmers | managers # union
>>> engineering_management = engineers & managers # intersection
>>> fulltime_management = managers - engineers - programmers # difference
>>> engineers.add('Marvin')
>>> print engineers
Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin'])
>>> employees.issuperset(engineers) # superset test
False
>>> employees.union_update(engineers) # update from another set
>>> employees.issuperset(engineers)
True
>>> for group in [engineers, programmers, managers, employees]:
... group.discard('Susan') # unconditionally remove element
... print group
...
Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin'])
Set(['Jack', 'Janice', 'Sam'])
Set(['Jack', 'Jane', 'Zack'])
Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin', 'Sam', 'Zack'])
"""
#==============================================================================
__test__ = {'libreftest' : libreftest}
def test_main(verbose=None):
from test import test_sets
test_support.run_unittest(
TestSetOfSets,
TestExceptionPropagation,
TestBasicOpsEmpty,
TestBasicOpsSingleton,
TestBasicOpsTuple,
TestBasicOpsTriple,
TestBinaryOps,
TestUpdateOps,
TestMutate,
TestSubsetEqualEmpty,
TestSubsetEqualNonEmpty,
TestSubsetEmptyNonEmpty,
TestSubsetPartial,
TestSubsetNonOverlap,
TestOnlySetsNumeric,
TestOnlySetsDict,
TestOnlySetsOperator,
TestOnlySetsTuple,
TestOnlySetsString,
TestOnlySetsGenerator,
TestOnlySetsofSets,
TestCopyingEmpty,
TestCopyingSingleton,
TestCopyingTriple,
TestCopyingTuple,
TestCopyingNested,
TestIdentities,
)
test_support.run_doctest(test_sets, verbose)
if __name__ == "__main__":
test_main(verbose=True)
--- NEW FILE: test_shelve.py ---
import os
import unittest
import shelve
import glob
from test import test_support
class TestCase(unittest.TestCase):
fn = "shelftemp" + os.extsep + "db"
def test_ascii_file_shelf(self):
try:
s = shelve.open(self.fn, binary=False)
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
s.close()
finally:
for f in glob.glob(self.fn+"*"):
os.unlink(f)
def test_binary_file_shelf(self):
try:
s = shelve.open(self.fn, binary=True)
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
s.close()
finally:
for f in glob.glob(self.fn+"*"):
os.unlink(f)
def test_proto2_file_shelf(self):
try:
s = shelve.open(self.fn, protocol=2)
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
s.close()
finally:
for f in glob.glob(self.fn+"*"):
os.unlink(f)
def test_in_memory_shelf(self):
d1 = {}
s = shelve.Shelf(d1, binary=False)
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
s.close()
d2 = {}
s = shelve.Shelf(d2, binary=True)
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
s.close()
self.assertEqual(len(d1), 1)
self.assertNotEqual(d1, d2)
def test_mutable_entry(self):
d1 = {}
s = shelve.Shelf(d1, protocol=2, writeback=False)
s['key1'] = [1,2,3,4]
self.assertEqual(s['key1'], [1,2,3,4])
s['key1'].append(5)
self.assertEqual(s['key1'], [1,2,3,4])
s.close()
d2 = {}
s = shelve.Shelf(d2, protocol=2, writeback=True)
s['key1'] = [1,2,3,4]
self.assertEqual(s['key1'], [1,2,3,4])
s['key1'].append(5)
self.assertEqual(s['key1'], [1,2,3,4,5])
s.close()
self.assertEqual(len(d1), 1)
self.assertEqual(len(d2), 1)
from test_userdict import TestMappingProtocol
class TestShelveBase(TestMappingProtocol):
fn = "shelftemp.db"
counter = 0
def __init__(self, *args, **kw):
self._db = []
TestMappingProtocol.__init__(self, *args, **kw)
_tested_class = shelve.Shelf
def _reference(self):
return {"key1":"value1", "key2":2, "key3":(1,2,3)}
def _empty_mapping(self):
if self._in_mem:
x= shelve.Shelf({}, **self._args)
else:
self.counter+=1
x= shelve.open(self.fn+str(self.counter), **self._args)
self._db.append(x)
return x
def tearDown(self):
for db in self._db:
db.close()
self._db = []
if not self._in_mem:
for f in glob.glob(self.fn+"*"):
os.unlink(f)
class TestAsciiFileShelve(TestShelveBase):
_args={'binary':False}
_in_mem = False
class TestBinaryFileShelve(TestShelveBase):
_args={'binary':True}
_in_mem = False
class TestProto2FileShelve(TestShelveBase):
_args={'protocol':2}
_in_mem = False
class TestAsciiMemShelve(TestShelveBase):
_args={'binary':False}
_in_mem = True
class TestBinaryMemShelve(TestShelveBase):
_args={'binary':True}
_in_mem = True
class TestProto2MemShelve(TestShelveBase):
_args={'protocol':2}
_in_mem = True
def test_main():
test_support.run_unittest(
TestAsciiFileShelve,
TestBinaryFileShelve,
TestProto2FileShelve,
TestAsciiMemShelve,
TestBinaryMemShelve,
TestProto2MemShelve,
TestCase
)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_shlex.py ---
# -*- coding: iso-8859-1 -*-
import unittest
import os, sys
import shlex
from test import test_support
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
# The original test data set was from shellwords, by Hartmut Goebel.
data = r"""x|x|
foo bar|foo|bar|
foo bar|foo|bar|
foo bar |foo|bar|
foo bar bla fasel|foo|bar|bla|fasel|
x y z xxxx|x|y|z|xxxx|
\x bar|\|x|bar|
\ x bar|\|x|bar|
\ bar|\|bar|
foo \x bar|foo|\|x|bar|
foo \ x bar|foo|\|x|bar|
foo \ bar|foo|\|bar|
foo "bar" bla|foo|"bar"|bla|
"foo" "bar" "bla"|"foo"|"bar"|"bla"|
"foo" bar "bla"|"foo"|bar|"bla"|
"foo" bar bla|"foo"|bar|bla|
foo 'bar' bla|foo|'bar'|bla|
'foo' 'bar' 'bla'|'foo'|'bar'|'bla'|
'foo' bar 'bla'|'foo'|bar|'bla'|
'foo' bar bla|'foo'|bar|bla|
blurb foo"bar"bar"fasel" baz|blurb|foo"bar"bar"fasel"|baz|
blurb foo'bar'bar'fasel' baz|blurb|foo'bar'bar'fasel'|baz|
""|""|
''|''|
foo "" bar|foo|""|bar|
foo '' bar|foo|''|bar|
foo "" "" "" bar|foo|""|""|""|bar|
foo '' '' '' bar|foo|''|''|''|bar|
\""|\|""|
"\"|"\"|
"foo\ bar"|"foo\ bar"|
"foo\\ bar"|"foo\\ bar"|
"foo\\ bar\"|"foo\\ bar\"|
"foo\\" bar\""|"foo\\"|bar|\|""|
"foo\\ bar\" dfadf"|"foo\\ bar\"|dfadf"|
"foo\\\ bar\" dfadf"|"foo\\\ bar\"|dfadf"|
"foo\\\x bar\" dfadf"|"foo\\\x bar\"|dfadf"|
"foo\x bar\" dfadf"|"foo\x bar\"|dfadf"|
\''|\|''|
'foo\ bar'|'foo\ bar'|
'foo\\ bar'|'foo\\ bar'|
"foo\\\x bar\" df'a\ 'df'|"foo\\\x bar\"|df'a|\|'df'|
\"foo"|\|"foo"|
\"foo"\x|\|"foo"|\|x|
"foo\x"|"foo\x"|
"foo\ "|"foo\ "|
foo\ xx|foo|\|xx|
foo\ x\x|foo|\|x|\|x|
foo\ x\x\""|foo|\|x|\|x|\|""|
"foo\ x\x"|"foo\ x\x"|
"foo\ x\x\\"|"foo\ x\x\\"|
"foo\ x\x\\""foobar"|"foo\ x\x\\"|"foobar"|
"foo\ x\x\\"\''"foobar"|"foo\ x\x\\"|\|''|"foobar"|
"foo\ x\x\\"\'"fo'obar"|"foo\ x\x\\"|\|'"fo'|obar"|
"foo\ x\x\\"\'"fo'obar" 'don'\''t'|"foo\ x\x\\"|\|'"fo'|obar"|'don'|\|''|t'|
'foo\ bar'|'foo\ bar'|
'foo\\ bar'|'foo\\ bar'|
foo\ bar|foo|\|bar|
foo#bar\nbaz|foobaz|
:-) ;-)|:|-|)|;|-|)|
áéíóú|á|é|í|ó|ú|
"""
posix_data = r"""x|x|
foo bar|foo|bar|
foo bar|foo|bar|
foo bar |foo|bar|
foo bar bla fasel|foo|bar|bla|fasel|
x y z xxxx|x|y|z|xxxx|
\x bar|x|bar|
\ x bar| x|bar|
\ bar| bar|
foo \x bar|foo|x|bar|
foo \ x bar|foo| x|bar|
foo \ bar|foo| bar|
foo "bar" bla|foo|bar|bla|
"foo" "bar" "bla"|foo|bar|bla|
"foo" bar "bla"|foo|bar|bla|
"foo" bar bla|foo|bar|bla|
foo 'bar' bla|foo|bar|bla|
'foo' 'bar' 'bla'|foo|bar|bla|
'foo' bar 'bla'|foo|bar|bla|
'foo' bar bla|foo|bar|bla|
blurb foo"bar"bar"fasel" baz|blurb|foobarbarfasel|baz|
blurb foo'bar'bar'fasel' baz|blurb|foobarbarfasel|baz|
""||
''||
foo "" bar|foo||bar|
foo '' bar|foo||bar|
foo "" "" "" bar|foo||||bar|
foo '' '' '' bar|foo||||bar|
\"|"|
"\""|"|
"foo\ bar"|foo\ bar|
"foo\\ bar"|foo\ bar|
"foo\\ bar\""|foo\ bar"|
"foo\\" bar\"|foo\|bar"|
"foo\\ bar\" dfadf"|foo\ bar" dfadf|
"foo\\\ bar\" dfadf"|foo\\ bar" dfadf|
"foo\\\x bar\" dfadf"|foo\\x bar" dfadf|
"foo\x bar\" dfadf"|foo\x bar" dfadf|
\'|'|
'foo\ bar'|foo\ bar|
'foo\\ bar'|foo\\ bar|
"foo\\\x bar\" df'a\ 'df"|foo\\x bar" df'a\ 'df|
\"foo|"foo|
\"foo\x|"foox|
"foo\x"|foo\x|
"foo\ "|foo\ |
foo\ xx|foo xx|
foo\ x\x|foo xx|
foo\ x\x\"|foo xx"|
"foo\ x\x"|foo\ x\x|
"foo\ x\x\\"|foo\ x\x\|
"foo\ x\x\\""foobar"|foo\ x\x\foobar|
"foo\ x\x\\"\'"foobar"|foo\ x\x\'foobar|
"foo\ x\x\\"\'"fo'obar"|foo\ x\x\'fo'obar|
"foo\ x\x\\"\'"fo'obar" 'don'\''t'|foo\ x\x\'fo'obar|don't|
"foo\ x\x\\"\'"fo'obar" 'don'\''t' \\|foo\ x\x\'fo'obar|don't|\|
'foo\ bar'|foo\ bar|
'foo\\ bar'|foo\\ bar|
foo\ bar|foo bar|
foo#bar\nbaz|foo|baz|
:-) ;-)|:-)|;-)|
áéíóú|áéíóú|
"""
class ShlexTest(unittest.TestCase):
def setUp(self):
self.data = [x.split("|")[:-1]
for x in data.splitlines()]
self.posix_data = [x.split("|")[:-1]
for x in posix_data.splitlines()]
for item in self.data:
item[0] = item[0].replace(r"\n", "\n")
for item in self.posix_data:
item[0] = item[0].replace(r"\n", "\n")
def splitTest(self, data, comments):
for i in range(len(data)):
l = shlex.split(data[i][0], comments=comments)
self.assertEqual(l, data[i][1:],
"%s: %s != %s" %
(data[i][0], l, data[i][1:]))
def oldSplit(self, s):
ret = []
lex = shlex.shlex(StringIO(s))
tok = lex.get_token()
while tok:
ret.append(tok)
tok = lex.get_token()
return ret
def testSplitPosix(self):
"""Test data splitting with posix parser"""
self.splitTest(self.posix_data, comments=True)
def testCompat(self):
"""Test compatibility interface"""
for i in range(len(self.data)):
l = self.oldSplit(self.data[i][0])
self.assertEqual(l, self.data[i][1:],
"%s: %s != %s" %
(self.data[i][0], l, self.data[i][1:]))
# Allow this test to be used with old shlex.py
if not getattr(shlex, "split", None):
for methname in dir(ShlexTest):
if methname.startswith("test") and methname != "testCompat":
delattr(ShlexTest, methname)
def test_main():
test_support.run_unittest(ShlexTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_shutil.py ---
# Copyright (C) 2003 Python Software Foundation
import unittest
import shutil
import tempfile
from test import test_support
class TestShutil(unittest.TestCase):
def test_rmtree_errors(self):
# filename is guaranteed not to exist
filename = tempfile.mktemp()
self.assertRaises(OSError, shutil.rmtree, filename)
self.assertEqual(shutil.rmtree(filename, True), None)
def test_main():
test_support.run_unittest(TestShutil)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_slice.py ---
# tests for slice objects; in particular the indices method.
import unittest
from test import test_support
import sys
class SliceTest(unittest.TestCase):
def test_constructor(self):
self.assertRaises(TypeError, slice)
self.assertRaises(TypeError, slice, 1, 2, 3, 4)
def test_repr(self):
self.assertEqual(repr(slice(1, 2, 3)), "slice(1, 2, 3)")
def test_hash(self):
# Verify clearing of SF bug #800796
self.assertRaises(TypeError, hash, slice(5))
self.assertRaises(TypeError, slice(5).__hash__)
def test_cmp(self):
s1 = slice(1, 2, 3)
s2 = slice(1, 2, 3)
s3 = slice(1, 2, 4)
self.assertEqual(s1, s2)
self.assertNotEqual(s1, s3)
class Exc(Exception):
pass
class BadCmp(object):
def __eq__(self, other):
raise Exc
s1 = slice(BadCmp())
s2 = slice(BadCmp())
self.assertRaises(Exc, cmp, s1, s2)
self.assertEqual(s1, s1)
s1 = slice(1, BadCmp())
s2 = slice(1, BadCmp())
self.assertEqual(s1, s1)
self.assertRaises(Exc, cmp, s1, s2)
s1 = slice(1, 2, BadCmp())
s2 = slice(1, 2, BadCmp())
self.assertEqual(s1, s1)
self.assertRaises(Exc, cmp, s1, s2)
def test_members(self):
s = slice(1)
self.assertEqual(s.start, None)
self.assertEqual(s.stop, 1)
self.assertEqual(s.step, None)
s = slice(1, 2)
self.assertEqual(s.start, 1)
self.assertEqual(s.stop, 2)
self.assertEqual(s.step, None)
s = slice(1, 2, 3)
self.assertEqual(s.start, 1)
self.assertEqual(s.stop, 2)
self.assertEqual(s.step, 3)
class AnyClass:
pass
obj = AnyClass()
s = slice(obj)
self.assert_(s.stop is obj)
def test_indices(self):
self.assertEqual(slice(None ).indices(10), (0, 10, 1))
self.assertEqual(slice(None, None, 2).indices(10), (0, 10, 2))
self.assertEqual(slice(1, None, 2).indices(10), (1, 10, 2))
self.assertEqual(slice(None, None, -1).indices(10), (9, -1, -1))
self.assertEqual(slice(None, None, -2).indices(10), (9, -1, -2))
self.assertEqual(slice(3, None, -2).indices(10), (3, -1, -2))
self.assertEqual(
slice(-100, 100 ).indices(10),
slice(None).indices(10)
)
self.assertEqual(
slice(100, -100, -1).indices(10),
slice(None, None, -1).indices(10)
)
self.assertEqual(slice(-100L, 100L, 2L).indices(10), (0, 10, 2))
self.assertEqual(range(10)[::sys.maxint - 1], [0])
self.assertRaises(OverflowError, slice(None).indices, 1L<<100)
def test_main():
test_support.run_unittest(SliceTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_softspace.py ---
from test import test_support
import StringIO
# SF bug 480215: softspace confused in nested print
f = StringIO.StringIO()
class C:
def __str__(self):
print >> f, 'a'
return 'b'
print >> f, C(), 'c ', 'd\t', 'e'
print >> f, 'f', 'g'
# In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n'
test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n')
--- NEW FILE: test_sort.py ---
from test.test_support import verbose
import random
from UserList import UserList
nerrors = 0
def check(tag, expected, raw, compare=None):
global nerrors
if verbose:
print " checking", tag
orig = raw[:] # save input in case of error
if compare:
raw.sort(compare)
else:
raw.sort()
if len(expected) != len(raw):
print "error in", tag
print "length mismatch;", len(expected), len(raw)
print expected
print orig
print raw
nerrors += 1
return
for i, good in enumerate(expected):
maybe = raw[i]
if good is not maybe:
print "error in", tag
print "out of order at index", i, good, maybe
print expected
print orig
print raw
nerrors += 1
return
# Try a variety of sizes at and around powers of 2, and at powers of 10.
sizes = [0]
for power in range(1, 10):
n = 2 ** power
sizes.extend(range(n-1, n+2))
sizes.extend([10, 100, 1000])
class Complains(object):
maybe_complain = True
def __init__(self, i):
self.i = i
def __lt__(self, other):
if Complains.maybe_complain and random.random() < 0.001:
if verbose:
print " complaining at", self, other
raise RuntimeError
return self.i < other.i
def __repr__(self):
return "Complains(%d)" % self.i
class Stable(object):
def __init__(self, key, i):
self.key = key
self.index = i
def __cmp__(self, other):
return cmp(self.key, other.key)
def __repr__(self):
return "Stable(%d, %d)" % (self.key, self.index)
for n in sizes:
x = range(n)
if verbose:
print "Testing size", n
s = x[:]
check("identity", x, s)
s = x[:]
s.reverse()
check("reversed", x, s)
s = x[:]
random.shuffle(s)
check("random permutation", x, s)
y = x[:]
y.reverse()
s = x[:]
check("reversed via function", y, s, lambda a, b: cmp(b, a))
if verbose:
print " Checking against an insane comparison function."
print " If the implementation isn't careful, this may segfault."
s = x[:]
s.sort(lambda a, b: int(random.random() * 3) - 1)
check("an insane function left some permutation", x, s)
x = [Complains(i) for i in x]
s = x[:]
random.shuffle(s)
Complains.maybe_complain = True
it_complained = False
try:
s.sort()
except RuntimeError:
it_complained = True
if it_complained:
Complains.maybe_complain = False
check("exception during sort left some permutation", x, s)
s = [Stable(random.randrange(10), i) for i in xrange(n)]
augmented = [(e, e.index) for e in s]
augmented.sort() # forced stable because ties broken by index
x = [e for e, i in augmented] # a stable sort of s
check("stability", x, s)
import unittest
from test import test_support
import sys
#==============================================================================
class TestBugs(unittest.TestCase):
def test_bug453523(self):
# bug 453523 -- list.sort() crasher.
# If this fails, the most likely outcome is a core dump.
# Mutations during a list sort should raise a ValueError.
class C:
def __lt__(self, other):
if L and random.random() < 0.75:
L.pop()
else:
L.append(3)
return random.random() < 0.5
L = [C() for i in range(50)]
self.assertRaises(ValueError, L.sort)
def test_cmpNone(self):
# Testing None as a comparison function.
L = range(50)
random.shuffle(L)
L.sort(None)
self.assertEqual(L, range(50))
#==============================================================================
class TestDecorateSortUndecorate(unittest.TestCase):
def test_decorated(self):
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
copy = data[:]
random.shuffle(data)
data.sort(key=str.lower)
copy.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
def test_baddecorator(self):
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
self.assertRaises(TypeError, data.sort, None, lambda x,y: 0)
def test_stability(self):
data = [(random.randrange(100), i) for i in xrange(200)]
copy = data[:]
data.sort(key=lambda (x,y): x) # sort on the random first field
copy.sort() # sort using both fields
self.assertEqual(data, copy) # should get the same result
def test_cmp_and_key_combination(self):
# Verify that the wrapper has been removed
def compare(x, y):
self.assertEqual(type(x), str)
self.assertEqual(type(x), str)
return cmp(x, y)
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
data.sort(cmp=compare, key=str.lower)
def test_badcmp_with_key(self):
# Verify that the wrapper has been removed
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
self.assertRaises(TypeError, data.sort, "bad", str.lower)
def test_key_with_exception(self):
# Verify that the wrapper has been removed
data = range(-2,2)
dup = data[:]
self.assertRaises(ZeroDivisionError, data.sort, None, lambda x: 1/x)
self.assertEqual(data, dup)
def test_key_with_mutation(self):
data = range(10)
def k(x):
del data[:]
data[:] = range(20)
return x
self.assertRaises(ValueError, data.sort, key=k)
def test_key_with_mutating_del(self):
data = range(10)
class SortKiller(object):
def __init__(self, x):
pass
def __del__(self):
del data[:]
data[:] = range(20)
self.assertRaises(ValueError, data.sort, key=SortKiller)
def test_key_with_mutating_del_and_exception(self):
data = range(10)
## dup = data[:]
class SortKiller(object):
def __init__(self, x):
if x > 2:
raise RuntimeError
def __del__(self):
del data[:]
data[:] = range(20)
self.assertRaises(RuntimeError, data.sort, key=SortKiller)
## major honking subtlety: we *can't* do:
##
## self.assertEqual(data, dup)
##
## because there is a reference to a SortKiller in the
## traceback and by the time it dies we're outside the call to
## .sort() and so the list protection gimmicks are out of
## date (this cost some brain cells to figure out...).
def test_reverse(self):
data = range(100)
random.shuffle(data)
data.sort(reverse=True)
self.assertEqual(data, range(99,-1,-1))
self.assertRaises(TypeError, data.sort, "wrong type")
def test_reverse_stability(self):
data = [(random.randrange(100), i) for i in xrange(200)]
copy1 = data[:]
copy2 = data[:]
data.sort(cmp=lambda x,y: cmp(x[0],y[0]), reverse=True)
copy1.sort(cmp=lambda x,y: cmp(y[0],x[0]))
self.assertEqual(data, copy1)
copy2.sort(key=lambda x: x[0], reverse=True)
self.assertEqual(data, copy2)
#==============================================================================
def test_main(verbose=None):
test_classes = (
TestDecorateSortUndecorate,
TestBugs,
)
test_support.run_unittest(*test_classes)
# verify reference counting
if verbose and hasattr(sys, "gettotalrefcount"):
import gc
counts = [None] * 5
for i in xrange(len(counts)):
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
print counts
if __name__ == "__main__":
test_main(verbose=True)
--- NEW FILE: test_str.py ---
import unittest
from test import test_support, string_tests
class StrTest(
string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
string_tests.MixinStrUserStringTest
):
type2test = str
# We don't need to propagate to str
def fixtype(self, obj):
return obj
def test_formatting(self):
string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
self.assertRaises(OverflowError, '%c'.__mod__, 0x1234)
def test_main():
test_support.run_unittest(StrTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_stringprep.py ---
# To fully test this module, we would need a copy of the stringprep tables.
# Since we don't have them, this test checks only a few codepoints.
from test.test_support import verify, vereq
import sha
import stringprep
from stringprep import *
verify(in_table_a1(u"\u0221"))
verify(not in_table_a1(u"\u0222"))
verify(in_table_b1(u"\u00ad"))
verify(not in_table_b1(u"\u00ae"))
verify(map_table_b2(u"\u0041"), u"\u0061")
verify(map_table_b2(u"\u0061"), u"\u0061")
verify(map_table_b3(u"\u0041"), u"\u0061")
verify(map_table_b3(u"\u0061"), u"\u0061")
verify(in_table_c11(u"\u0020"))
verify(not in_table_c11(u"\u0021"))
verify(in_table_c12(u"\u00a0"))
verify(not in_table_c12(u"\u00a1"))
verify(in_table_c12(u"\u00a0"))
verify(not in_table_c12(u"\u00a1"))
verify(in_table_c11_c12(u"\u00a0"))
verify(not in_table_c11_c12(u"\u00a1"))
verify(in_table_c21(u"\u001f"))
verify(not in_table_c21(u"\u0020"))
verify(in_table_c22(u"\u009f"))
verify(not in_table_c22(u"\u00a0"))
verify(in_table_c21_c22(u"\u009f"))
verify(not in_table_c21_c22(u"\u00a0"))
verify(in_table_c3(u"\ue000"))
verify(not in_table_c3(u"\uf900"))
verify(in_table_c4(u"\uffff"))
verify(not in_table_c4(u"\u0000"))
verify(in_table_c5(u"\ud800"))
verify(not in_table_c5(u"\ud7ff"))
verify(in_table_c6(u"\ufff9"))
verify(not in_table_c6(u"\ufffe"))
verify(in_table_c7(u"\u2ff0"))
verify(not in_table_c7(u"\u2ffc"))
verify(in_table_c8(u"\u0340"))
verify(not in_table_c8(u"\u0342"))
# C.9 is not in the bmp
# verify(in_table_c9(u"\U000E0001"))
# verify(not in_table_c8(u"\U000E0002"))
verify(in_table_d1(u"\u05be"))
verify(not in_table_d1(u"\u05bf"))
verify(in_table_d2(u"\u0041"))
verify(not in_table_d2(u"\u0040"))
# This would generate a hash of all predicates. However, running
# it is quite expensive, and only serves to detect changes in the
# unicode database. Instead, stringprep.py asserts the version of
# the database.
# predicates = [k for k in dir(stringprep) if k.startswith("in_table")]
# predicates.sort()
# for p in predicates:
# f = getattr(stringprep, p)
# # Collect all BMP code points
# data = ["0"] * 0x10000
# for i in range(0x10000):
# if f(unichr(i)):
# data[i] = "1"
# data = "".join(data)
# h = sha.sha()
# h.update(data)
# print p,h.hexdigest()
--- NEW FILE: test_strptime.py ---
"""PyUnit testing against strptime"""
import unittest
import time
import locale
import re
import sys
from test import test_support
import _strptime
class getlang_Tests(unittest.TestCase):
"""Test _getlang"""
def test_basic(self):
self.failUnlessEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
class LocaleTime_Tests(unittest.TestCase):
"""Tests for _strptime.LocaleTime.
All values are lower-cased when stored in LocaleTime, so make sure to
compare values after running ``lower`` on them.
"""
def setUp(self):
"""Create time tuple based on current time."""
self.time_tuple = time.localtime()
self.LT_ins = _strptime.LocaleTime()
def compare_against_time(self, testing, directive, tuple_position,
error_msg):
"""Helper method that tests testing against directive based on the
tuple_position of time_tuple. Uses error_msg as error message.
"""
strftime_output = time.strftime(directive, self.time_tuple).lower()
comparison = testing[self.time_tuple[tuple_position]]
self.failUnless(strftime_output in testing, "%s: not found in tuple" %
error_msg)
self.failUnless(comparison == strftime_output,
"%s: position within tuple incorrect; %s != %s" %
(error_msg, comparison, strftime_output))
def test_weekday(self):
# Make sure that full and abbreviated weekday names are correct in
# both string and position with tuple
self.compare_against_time(self.LT_ins.f_weekday, '%A', 6,
"Testing of full weekday name failed")
self.compare_against_time(self.LT_ins.a_weekday, '%a', 6,
"Testing of abbreviated weekday name failed")
def test_month(self):
# Test full and abbreviated month names; both string and position
# within the tuple
self.compare_against_time(self.LT_ins.f_month, '%B', 1,
"Testing against full month name failed")
self.compare_against_time(self.LT_ins.a_month, '%b', 1,
"Testing against abbreviated month name failed")
def test_am_pm(self):
# Make sure AM/PM representation done properly
strftime_output = time.strftime("%p", self.time_tuple).lower()
self.failUnless(strftime_output in self.LT_ins.am_pm,
"AM/PM representation not in tuple")
if self.time_tuple[3] < 12: position = 0
else: position = 1
self.failUnless(strftime_output == self.LT_ins.am_pm[position],
"AM/PM representation in the wrong position within the tuple")
def test_timezone(self):
# Make sure timezone is correct
timezone = time.strftime("%Z", self.time_tuple).lower()
if timezone:
self.failUnless(timezone in self.LT_ins.timezone[0] or \
timezone in self.LT_ins.timezone[1],
"timezone %s not found in %s" %
(timezone, self.LT_ins.timezone))
def test_date_time(self):
# Check that LC_date_time, LC_date, and LC_time are correct
# the magic date is used so as to not have issues with %c when day of
# the month is a single digit and has a leading space. This is not an
# issue since strptime still parses it correctly. The problem is
# testing these directives for correctness by comparing strftime
# output.
magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0)
strftime_output = time.strftime("%c", magic_date)
self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date_time,
magic_date),
"LC_date_time incorrect")
strftime_output = time.strftime("%x", magic_date)
self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date,
magic_date),
"LC_date incorrect")
strftime_output = time.strftime("%X", magic_date)
self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_time,
magic_date),
"LC_time incorrect")
LT = _strptime.LocaleTime()
LT.am_pm = ('', '')
self.failUnless(LT.LC_time, "LocaleTime's LC directives cannot handle "
"empty strings")
def test_lang(self):
# Make sure lang is set to what _getlang() returns
# Assuming locale has not changed between now and when self.LT_ins was created
self.failUnlessEqual(self.LT_ins.lang, _strptime._getlang())
class TimeRETests(unittest.TestCase):
"""Tests for TimeRE."""
def setUp(self):
"""Construct generic TimeRE object."""
self.time_re = _strptime.TimeRE()
self.locale_time = _strptime.LocaleTime()
def test_pattern(self):
# Test TimeRE.pattern
pattern_string = self.time_re.pattern(r"%a %A %d")
self.failUnless(pattern_string.find(self.locale_time.a_weekday[2]) != -1,
"did not find abbreviated weekday in pattern string '%s'" %
pattern_string)
self.failUnless(pattern_string.find(self.locale_time.f_weekday[4]) != -1,
"did not find full weekday in pattern string '%s'" %
pattern_string)
self.failUnless(pattern_string.find(self.time_re['d']) != -1,
"did not find 'd' directive pattern string '%s'" %
pattern_string)
def test_pattern_escaping(self):
# Make sure any characters in the format string that might be taken as
# regex syntax is escaped.
pattern_string = self.time_re.pattern("\d+")
self.failUnless(r"\\d\+" in pattern_string,
"%s does not have re characters escaped properly" %
pattern_string)
def test_compile(self):
# Check that compiled regex is correct
found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6])
self.failUnless(found and found.group('A') == self.locale_time.f_weekday[6],
"re object for '%A' failed")
compiled = self.time_re.compile(r"%a %b")
found = compiled.match("%s %s" % (self.locale_time.a_weekday[4],
self.locale_time.a_month[4]))
self.failUnless(found,
"Match failed with '%s' regex and '%s' string" %
(compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4],
self.locale_time.a_month[4])))
self.failUnless(found.group('a') == self.locale_time.a_weekday[4] and
found.group('b') == self.locale_time.a_month[4],
"re object couldn't find the abbreviated weekday month in "
"'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" %
(found.string, found.re.pattern, found.group('a'),
found.group('b')))
for directive in ('a','A','b','B','c','d','H','I','j','m','M','p','S',
'U','w','W','x','X','y','Y','Z','%'):
compiled = self.time_re.compile("%" + directive)
found = compiled.match(time.strftime("%" + directive))
self.failUnless(found, "Matching failed on '%s' using '%s' regex" %
(time.strftime("%" + directive),
compiled.pattern))
def test_blankpattern(self):
# Make sure when tuple or something has no values no regex is generated.
# Fixes bug #661354
test_locale = _strptime.LocaleTime()
test_locale.timezone = (frozenset(), frozenset())
self.failUnless(_strptime.TimeRE(test_locale).pattern("%Z") == '',
"with timezone == ('',''), TimeRE().pattern('%Z') != ''")
def test_matching_with_escapes(self):
# Make sure a format that requires escaping of characters works
compiled_re = self.time_re.compile("\w+ %m")
found = compiled_re.match("\w+ 10")
self.failUnless(found, "Escaping failed of format '\w+ 10'")
class StrptimeTests(unittest.TestCase):
"""Tests for _strptime.strptime."""
def setUp(self):
"""Create testing time tuple."""
self.time_tuple = time.gmtime()
def test_TypeError(self):
# Make sure ValueError is raised when match fails
self.assertRaises(ValueError, _strptime.strptime, data_string="%d",
format="%A")
def test_unconverteddata(self):
# Check ValueError is raised when there is unconverted data
self.assertRaises(ValueError, _strptime.strptime, "10 12", "%m")
def helper(self, directive, position):
"""Helper fxn in testing."""
strf_output = time.strftime("%" + directive, self.time_tuple)
strp_output = _strptime.strptime(strf_output, "%" + directive)
self.failUnless(strp_output[position] == self.time_tuple[position],
"testing of '%s' directive failed; '%s' -> %s != %s" %
(directive, strf_output, strp_output[position],
self.time_tuple[position]))
def test_year(self):
# Test that the year is handled properly
for directive in ('y', 'Y'):
self.helper(directive, 0)
# Must also make sure %y values are correct for bounds set by Open Group
for century, bounds in ((1900, ('69', '99')), (2000, ('00', '68'))):
for bound in bounds:
strp_output = _strptime.strptime(bound, '%y')
expected_result = century + int(bound)
self.failUnless(strp_output[0] == expected_result,
"'y' test failed; passed in '%s' "
"and returned '%s'" % (bound, strp_output[0]))
def test_month(self):
# Test for month directives
for directive in ('B', 'b', 'm'):
self.helper(directive, 1)
def test_day(self):
# Test for day directives
self.helper('d', 2)
def test_hour(self):
# Test hour directives
self.helper('H', 3)
strf_output = time.strftime("%I %p", self.time_tuple)
strp_output = _strptime.strptime(strf_output, "%I %p")
self.failUnless(strp_output[3] == self.time_tuple[3],
"testing of '%%I %%p' directive failed; '%s' -> %s != %s" %
(strf_output, strp_output[3], self.time_tuple[3]))
def test_minute(self):
# Test minute directives
self.helper('M', 4)
def test_second(self):
# Test second directives
self.helper('S', 5)
def test_weekday(self):
# Test weekday directives
for directive in ('A', 'a', 'w'):
self.helper(directive,6)
def test_julian(self):
# Test julian directives
self.helper('j', 7)
def test_timezone(self):
# Test timezone directives.
# When gmtime() is used with %Z, entire result of strftime() is empty.
# Check for equal timezone names deals with bad locale info when this
# occurs; first found in FreeBSD 4.4.
strp_output = _strptime.strptime("UTC", "%Z")
self.failUnlessEqual(strp_output.tm_isdst, 0)
strp_output = _strptime.strptime("GMT", "%Z")
self.failUnlessEqual(strp_output.tm_isdst, 0)
if sys.platform == "mac":
# Timezones don't really work on MacOS9
return
time_tuple = time.localtime()
strf_output = time.strftime("%Z") #UTC does not have a timezone
strp_output = _strptime.strptime(strf_output, "%Z")
locale_time = _strptime.LocaleTime()
if time.tzname[0] != time.tzname[1] or not time.daylight:
self.failUnless(strp_output[8] == time_tuple[8],
"timezone check failed; '%s' -> %s != %s" %
(strf_output, strp_output[8], time_tuple[8]))
else:
self.failUnless(strp_output[8] == -1,
"LocaleTime().timezone has duplicate values and "
"time.daylight but timezone value not set to -1")
def test_bad_timezone(self):
# Explicitly test possibility of bad timezone;
# when time.tzname[0] == time.tzname[1] and time.daylight
if sys.platform == "mac":
return #MacOS9 has severely broken timezone support.
tz_name= time.tzname[0]
try:
original_tzname = time.tzname
original_daylight = time.daylight
time.tzname = (tz_name, tz_name)
time.daylight = 1
tz_value = _strptime.strptime(tz_name, "%Z")[8]
self.failUnlessEqual(tz_value, -1)
finally:
time.tzname = original_tzname
time.daylight = original_daylight
def test_date_time(self):
# Test %c directive
for position in range(6):
self.helper('c', position)
def test_date(self):
# Test %x directive
for position in range(0,3):
self.helper('x', position)
def test_time(self):
# Test %X directive
for position in range(3,6):
self.helper('X', position)
def test_percent(self):
# Make sure % signs are handled properly
strf_output = time.strftime("%m %% %Y", self.time_tuple)
strp_output = _strptime.strptime(strf_output, "%m %% %Y")
self.failUnless(strp_output[0] == self.time_tuple[0] and
strp_output[1] == self.time_tuple[1],
"handling of percent sign failed")
def test_caseinsensitive(self):
# Should handle names case-insensitively.
strf_output = time.strftime("%B", self.time_tuple)
self.failUnless(_strptime.strptime(strf_output.upper(), "%B"),
"strptime does not handle ALL-CAPS names properly")
self.failUnless(_strptime.strptime(strf_output.lower(), "%B"),
"strptime does not handle lowercase names properly")
self.failUnless(_strptime.strptime(strf_output.capitalize(), "%B"),
"strptime does not handle capword names properly")
def test_defaults(self):
# Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0)
defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1)
strp_output = _strptime.strptime('1', '%m')
self.failUnless(strp_output == defaults,
"Default values for strptime() are incorrect;"
" %s != %s" % (strp_output, defaults))
def test_escaping(self):
# Make sure all characters that have regex significance are escaped.
# Parentheses are in a purposeful order; will cause an error of
# unbalanced parentheses when the regex is compiled if they are not
# escaped.
# Test instigated by bug #796149 .
need_escaping = ".^$*+?{}\[]|)("
self.failUnless(_strptime.strptime(need_escaping, need_escaping))
class Strptime12AMPMTests(unittest.TestCase):
"""Test a _strptime regression in '%I %p' at 12 noon (12 PM)"""
def test_twelve_noon_midnight(self):
eq = self.assertEqual
eq(time.strptime('12 PM', '%I %p')[3], 12)
eq(time.strptime('12 AM', '%I %p')[3], 0)
eq(_strptime.strptime('12 PM', '%I %p')[3], 12)
eq(_strptime.strptime('12 AM', '%I %p')[3], 0)
class JulianTests(unittest.TestCase):
"""Test a _strptime regression that all julian (1-366) are accepted"""
def test_all_julian_days(self):
eq = self.assertEqual
for i in range(1, 367):
# use 2004, since it is a leap year, we have 366 days
eq(_strptime.strptime('%d 2004' % i, '%j %Y')[7], i)
class CalculationTests(unittest.TestCase):
"""Test that strptime() fills in missing info correctly"""
def setUp(self):
self.time_tuple = time.gmtime()
def test_julian_calculation(self):
# Make sure that when Julian is missing that it is calculated
format_string = "%Y %m %d %H %M %S %w %Z"
result = _strptime.strptime(time.strftime(format_string, self.time_tuple),
format_string)
self.failUnless(result.tm_yday == self.time_tuple.tm_yday,
"Calculation of tm_yday failed; %s != %s" %
(result.tm_yday, self.time_tuple.tm_yday))
def test_gregorian_calculation(self):
# Test that Gregorian date can be calculated from Julian day
format_string = "%Y %H %M %S %w %j %Z"
result = _strptime.strptime(time.strftime(format_string, self.time_tuple),
format_string)
self.failUnless(result.tm_year == self.time_tuple.tm_year and
result.tm_mon == self.time_tuple.tm_mon and
result.tm_mday == self.time_tuple.tm_mday,
"Calculation of Gregorian date failed;"
"%s-%s-%s != %s-%s-%s" %
(result.tm_year, result.tm_mon, result.tm_mday,
self.time_tuple.tm_year, self.time_tuple.tm_mon,
self.time_tuple.tm_mday))
def test_day_of_week_calculation(self):
# Test that the day of the week is calculated as needed
format_string = "%Y %m %d %H %S %j %Z"
result = _strptime.strptime(time.strftime(format_string, self.time_tuple),
format_string)
self.failUnless(result.tm_wday == self.time_tuple.tm_wday,
"Calculation of day of the week failed;"
"%s != %s" % (result.tm_wday, self.time_tuple.tm_wday))
class CacheTests(unittest.TestCase):
"""Test that caching works properly."""
def test_time_re_recreation(self):
# Make sure cache is recreated when current locale does not match what
# cached object was created with.
_strptime.strptime("10", "%d")
_strptime._TimeRE_cache.locale_time.lang = "Ni"
original_time_re = id(_strptime._TimeRE_cache)
_strptime.strptime("10", "%d")
self.failIfEqual(original_time_re, id(_strptime._TimeRE_cache))
def test_regex_cleanup(self):
# Make sure cached regexes are discarded when cache becomes "full".
try:
del _strptime._regex_cache['%d']
except KeyError:
pass
bogus_key = 0
while len(_strptime._regex_cache) <= _strptime._CACHE_MAX_SIZE:
_strptime._regex_cache[bogus_key] = None
bogus_key += 1
_strptime.strptime("10", "%d")
self.failUnlessEqual(len(_strptime._regex_cache), 1)
def test_new_localetime(self):
# A new LocaleTime instance should be created when a new TimeRE object
# is created.
locale_time_id = id(_strptime._TimeRE_cache.locale_time)
_strptime._TimeRE_cache.locale_time.lang = "Ni"
_strptime.strptime("10", "%d")
self.failIfEqual(locale_time_id,
id(_strptime._TimeRE_cache.locale_time))
def test_main():
test_support.run_unittest(
getlang_Tests,
LocaleTime_Tests,
TimeRETests,
StrptimeTests,
Strptime12AMPMTests,
JulianTests,
CalculationTests,
CacheTests
)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_syntax.py ---
import re
import unittest
import warnings
from test import test_support
class SyntaxTestCase(unittest.TestCase):
def _check_error(self, code, errtext,
filename="<testcase>", mode="exec"):
"""Check that compiling code raises SyntaxError with errtext.
errtest is a regular expression that must be present in the
test of the exception raised.
"""
try:
compile(code, filename, mode)
except SyntaxError, err:
mo = re.search(errtext, str(err))
if mo is None:
self.fail("SyntaxError did not contain '%r'" % (errtext,))
else:
self.fail("compile() did not raise SyntaxError")
def test_assign_call(self):
self._check_error("f() = 1", "assign")
def test_assign_del(self):
self._check_error("del f()", "delete")
def test_global_err_then_warn(self):
# Bug tickler: The SyntaxError raised for one global statement
# shouldn't be clobbered by a SyntaxWarning issued for a later one.
source = re.sub('(?m)^ *:', '', """\
:def error(a):
: global a # SyntaxError
:def warning():
: b = 1
: global b # SyntaxWarning
:""")
warnings.filterwarnings(action='ignore', category=SyntaxWarning)
self._check_error(source, "global")
warnings.filters.pop(0)
def test_main():
test_support.run_unittest(SyntaxTestCase)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_sys.py ---
# -*- coding: iso-8859-1 -*-
import unittest, test.test_support
import sys, cStringIO
class SysModuleTest(unittest.TestCase):
def test_original_displayhook(self):
import __builtin__
savestdout = sys.stdout
out = cStringIO.StringIO()
sys.stdout = out
dh = sys.__displayhook__
self.assertRaises(TypeError, dh)
if hasattr(__builtin__, "_"):
del __builtin__._
dh(None)
self.assertEqual(out.getvalue(), "")
self.assert_(not hasattr(__builtin__, "_"))
dh(42)
self.assertEqual(out.getvalue(), "42\n")
self.assertEqual(__builtin__._, 42)
del sys.stdout
self.assertRaises(RuntimeError, dh, 42)
sys.stdout = savestdout
def test_lost_displayhook(self):
olddisplayhook = sys.displayhook
del sys.displayhook
code = compile("42", "<string>", "single")
self.assertRaises(RuntimeError, eval, code)
sys.displayhook = olddisplayhook
def test_custom_displayhook(self):
olddisplayhook = sys.displayhook
def baddisplayhook(obj):
raise ValueError
sys.displayhook = baddisplayhook
code = compile("42", "<string>", "single")
self.assertRaises(ValueError, eval, code)
sys.displayhook = olddisplayhook
def test_original_excepthook(self):
savestderr = sys.stderr
err = cStringIO.StringIO()
sys.stderr = err
eh = sys.__excepthook__
self.assertRaises(TypeError, eh)
try:
raise ValueError(42)
except ValueError, exc:
eh(*sys.exc_info())
sys.stderr = savestderr
self.assert_(err.getvalue().endswith("ValueError: 42\n"))
# FIXME: testing the code for a lost or replaced excepthook in
# Python/pythonrun.c::PyErr_PrintEx() is tricky.
def test_exc_clear(self):
self.assertRaises(TypeError, sys.exc_clear, 42)
# Verify that exc_info is present and matches exc, then clear it, and
# check that it worked.
def clear_check(exc):
typ, value, traceback = sys.exc_info()
self.assert_(typ is not None)
self.assert_(value is exc)
self.assert_(traceback is not None)
sys.exc_clear()
typ, value, traceback = sys.exc_info()
self.assert_(typ is None)
self.assert_(value is None)
self.assert_(traceback is None)
def clear():
try:
raise ValueError, 42
except ValueError, exc:
clear_check(exc)
# Raise an exception and check that it can be cleared
clear()
# Verify that a frame currently handling an exception is
# unaffected by calling exc_clear in a nested frame.
try:
raise ValueError, 13
except ValueError, exc:
typ1, value1, traceback1 = sys.exc_info()
clear()
typ2, value2, traceback2 = sys.exc_info()
self.assert_(typ1 is typ2)
self.assert_(value1 is exc)
self.assert_(value1 is value2)
self.assert_(traceback1 is traceback2)
# Check that an exception can be cleared outside of an except block
clear_check(exc)
def test_exit(self):
self.assertRaises(TypeError, sys.exit, 42, 42)
# call without argument
try:
sys.exit(0)
except SystemExit, exc:
self.assertEquals(exc.code, 0)
except:
self.fail("wrong exception")
else:
self.fail("no exception")
# call with tuple argument with one entry
# entry will be unpacked
try:
sys.exit(42)
except SystemExit, exc:
self.assertEquals(exc.code, 42)
except:
self.fail("wrong exception")
else:
self.fail("no exception")
# call with integer argument
try:
sys.exit((42,))
except SystemExit, exc:
self.assertEquals(exc.code, 42)
except:
self.fail("wrong exception")
else:
self.fail("no exception")
# call with string argument
try:
sys.exit("exit")
except SystemExit, exc:
self.assertEquals(exc.code, "exit")
except:
self.fail("wrong exception")
else:
self.fail("no exception")
# call with tuple argument with two entries
try:
sys.exit((17, 23))
except SystemExit, exc:
self.assertEquals(exc.code, (17, 23))
except:
self.fail("wrong exception")
else:
self.fail("no exception")
def test_getdefaultencoding(self):
if test.test_support.have_unicode:
self.assertRaises(TypeError, sys.getdefaultencoding, 42)
# can't check more than the type, as the user might have changed it
self.assert_(isinstance(sys.getdefaultencoding(), str))
# testing sys.settrace() is done in test_trace.py
# testing sys.setprofile() is done in test_profile.py
def test_setcheckinterval(self):
self.assertRaises(TypeError, sys.setcheckinterval)
orig = sys.getcheckinterval()
for n in 0, 100, 120, orig: # orig last to restore starting state
sys.setcheckinterval(n)
self.assertEquals(sys.getcheckinterval(), n)
def test_recursionlimit(self):
self.assertRaises(TypeError, sys.getrecursionlimit, 42)
oldlimit = sys.getrecursionlimit()
self.assertRaises(TypeError, sys.setrecursionlimit)
self.assertRaises(ValueError, sys.setrecursionlimit, -42)
sys.setrecursionlimit(10000)
self.assertEqual(sys.getrecursionlimit(), 10000)
sys.setrecursionlimit(oldlimit)
def test_getwindowsversion(self):
if hasattr(sys, "getwindowsversion"):
v = sys.getwindowsversion()
self.assert_(isinstance(v, tuple))
self.assertEqual(len(v), 5)
self.assert_(isinstance(v[0], int))
self.assert_(isinstance(v[1], int))
self.assert_(isinstance(v[2], int))
self.assert_(isinstance(v[3], int))
self.assert_(isinstance(v[4], str))
def test_dlopenflags(self):
if hasattr(sys, "setdlopenflags"):
self.assert_(hasattr(sys, "getdlopenflags"))
self.assertRaises(TypeError, sys.getdlopenflags, 42)
oldflags = sys.getdlopenflags()
self.assertRaises(TypeError, sys.setdlopenflags)
sys.setdlopenflags(oldflags+1)
self.assertEqual(sys.getdlopenflags(), oldflags+1)
sys.setdlopenflags(oldflags)
def test_refcount(self):
self.assertRaises(TypeError, sys.getrefcount)
c = sys.getrefcount(None)
n = None
self.assertEqual(sys.getrefcount(None), c+1)
del n
self.assertEqual(sys.getrefcount(None), c)
if hasattr(sys, "gettotalrefcount"):
self.assert_(isinstance(sys.gettotalrefcount(), int))
def test_getframe(self):
self.assertRaises(TypeError, sys._getframe, 42, 42)
self.assertRaises(ValueError, sys._getframe, 2000000000)
self.assert_(
SysModuleTest.test_getframe.im_func.func_code \
is sys._getframe().f_code
)
def test_attributes(self):
self.assert_(isinstance(sys.api_version, int))
self.assert_(isinstance(sys.argv, list))
self.assert_(sys.byteorder in ("little", "big"))
self.assert_(isinstance(sys.builtin_module_names, tuple))
self.assert_(isinstance(sys.copyright, basestring))
self.assert_(isinstance(sys.exec_prefix, basestring))
self.assert_(isinstance(sys.executable, basestring))
self.assert_(isinstance(sys.hexversion, int))
self.assert_(isinstance(sys.maxint, int))
self.assert_(isinstance(sys.maxunicode, int))
self.assert_(isinstance(sys.platform, basestring))
self.assert_(isinstance(sys.prefix, basestring))
self.assert_(isinstance(sys.version, basestring))
vi = sys.version_info
self.assert_(isinstance(vi, tuple))
self.assertEqual(len(vi), 5)
self.assert_(isinstance(vi[0], int))
self.assert_(isinstance(vi[1], int))
self.assert_(isinstance(vi[2], int))
self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
self.assert_(isinstance(vi[4], int))
def test_main():
test.test_support.run_unittest(SysModuleTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_tarfile.py ---
import sys
import os
import shutil
import tempfile
import unittest
import tarfile
from test import test_support
# Check for our compression modules.
try:
import gzip
gzip.GzipFile
except (ImportError, AttributeError):
gzip = None
try:
import bz2
except ImportError:
bz2 = None
def path(path):
return test_support.findfile(path)
testtar = path("testtar.tar")
tempdir = os.path.join(tempfile.gettempdir(), "testtar" + os.extsep + "dir")
tempname = test_support.TESTFN
membercount = 10
def tarname(comp=""):
if not comp:
return testtar
return os.path.join(tempdir, "%s%s%s" % (testtar, os.extsep, comp))
def dirname():
if not os.path.exists(tempdir):
os.mkdir(tempdir)
return tempdir
def tmpname():
return tempname
class BaseTest(unittest.TestCase):
comp = ''
mode = 'r'
sep = ':'
def setUp(self):
mode = self.mode + self.sep + self.comp
self.tar = tarfile.open(tarname(self.comp), mode)
def tearDown(self):
self.tar.close()
class ReadTest(BaseTest):
def test(self):
"""Test member extraction.
"""
members = 0
for tarinfo in self.tar:
members += 1
if not tarinfo.isreg():
continue
f = self.tar.extractfile(tarinfo)
self.assert_(len(f.read()) == tarinfo.size,
"size read does not match expected size")
f.close()
self.assert_(members == membercount,
"could not find all members")
def test_sparse(self):
"""Test sparse member extraction.
"""
if self.sep != "|":
f1 = self.tar.extractfile("S-SPARSE")
f2 = self.tar.extractfile("S-SPARSE-WITH-NULLS")
self.assert_(f1.read() == f2.read(),
"_FileObject failed on sparse file member")
def test_readlines(self):
"""Test readlines() method of _FileObject.
"""
if self.sep != "|":
filename = "0-REGTYPE-TEXT"
self.tar.extract(filename, dirname())
lines1 = file(os.path.join(dirname(), filename), "rU").readlines()
lines2 = self.tar.extractfile(filename).readlines()
self.assert_(lines1 == lines2,
"_FileObject.readline() does not work correctly")
def test_seek(self):
"""Test seek() method of _FileObject, incl. random reading.
"""
if self.sep != "|":
filename = "0-REGTYPE"
self.tar.extract(filename, dirname())
data = file(os.path.join(dirname(), filename), "rb").read()
tarinfo = self.tar.getmember(filename)
fobj = self.tar.extractfile(tarinfo)
text = fobj.read()
fobj.seek(0)
self.assert_(0 == fobj.tell(),
"seek() to file's start failed")
fobj.seek(2048, 0)
self.assert_(2048 == fobj.tell(),
"seek() to absolute position failed")
fobj.seek(-1024, 1)
self.assert_(1024 == fobj.tell(),
"seek() to negative relative position failed")
fobj.seek(1024, 1)
self.assert_(2048 == fobj.tell(),
"seek() to positive relative position failed")
s = fobj.read(10)
self.assert_(s == data[2048:2058],
"read() after seek failed")
fobj.seek(0, 2)
self.assert_(tarinfo.size == fobj.tell(),
"seek() to file's end failed")
self.assert_(fobj.read() == "",
"read() at file's end did not return empty string")
fobj.seek(-tarinfo.size, 2)
self.assert_(0 == fobj.tell(),
"relative seek() to file's start failed")
fobj.seek(512)
s1 = fobj.readlines()
fobj.seek(512)
s2 = fobj.readlines()
self.assert_(s1 == s2,
"readlines() after seek failed")
fobj.close()
class ReadStreamTest(ReadTest):
sep = "|"
def test(self):
"""Test member extraction, and for StreamError when
seeking backwards.
"""
ReadTest.test(self)
tarinfo = self.tar.getmembers()[0]
f = self.tar.extractfile(tarinfo)
self.assertRaises(tarfile.StreamError, f.read)
def test_stream(self):
"""Compare the normal tar and the stream tar.
"""
stream = self.tar
tar = tarfile.open(tarname(), 'r')
while 1:
t1 = tar.next()
t2 = stream.next()
if t1 is None:
break
self.assert_(t2 is not None, "stream.next() failed.")
if t2.islnk() or t2.issym():
self.assertRaises(tarfile.StreamError, stream.extractfile, t2)
continue
v1 = tar.extractfile(t1)
v2 = stream.extractfile(t2)
if v1 is None:
continue
self.assert_(v2 is not None, "stream.extractfile() failed")
self.assert_(v1.read() == v2.read(), "stream extraction failed")
stream.close()
class WriteTest(BaseTest):
mode = 'w'
def setUp(self):
mode = self.mode + self.sep + self.comp
self.src = tarfile.open(tarname(self.comp), 'r')
self.dst = tarfile.open(tmpname(), mode)
def tearDown(self):
self.src.close()
self.dst.close()
def test_posix(self):
self.dst.posix = 1
self._test()
def test_nonposix(self):
self.dst.posix = 0
self._test()
def _test(self):
for tarinfo in self.src:
if not tarinfo.isreg():
continue
f = self.src.extractfile(tarinfo)
if self.dst.posix and len(tarinfo.name) > tarfile.LENGTH_NAME:
self.assertRaises(ValueError, self.dst.addfile,
tarinfo, f)
else:
self.dst.addfile(tarinfo, f)
class WriteStreamTest(WriteTest):
sep = '|'
# Gzip TestCases
class ReadTestGzip(ReadTest):
comp = "gz"
class ReadStreamTestGzip(ReadStreamTest):
comp = "gz"
class WriteTestGzip(WriteTest):
comp = "gz"
class WriteStreamTestGzip(WriteStreamTest):
comp = "gz"
if bz2:
# Bzip2 TestCases
class ReadTestBzip2(ReadTestGzip):
comp = "bz2"
class ReadStreamTestBzip2(ReadStreamTestGzip):
comp = "bz2"
class WriteTestBzip2(WriteTest):
comp = "bz2"
class WriteStreamTestBzip2(WriteStreamTestGzip):
comp = "bz2"
# If importing gzip failed, discard the Gzip TestCases.
if not gzip:
del ReadTestGzip
del ReadStreamTestGzip
del WriteTestGzip
del WriteStreamTestGzip
def test_main():
if gzip:
# create testtar.tar.gz
gzip.open(tarname("gz"), "wb").write(file(tarname(), "rb").read())
if bz2:
# create testtar.tar.bz2
bz2.BZ2File(tarname("bz2"), "wb").write(file(tarname(), "rb").read())
tests = [
ReadTest,
ReadStreamTest,
WriteTest,
WriteStreamTest
]
if gzip:
tests.extend([
ReadTestGzip, ReadStreamTestGzip,
WriteTestGzip, WriteStreamTestGzip
])
if bz2:
tests.extend([
ReadTestBzip2, ReadStreamTestBzip2,
WriteTestBzip2, WriteStreamTestBzip2
])
try:
test_support.run_unittest(*tests)
finally:
if gzip:
os.remove(tarname("gz"))
if bz2:
os.remove(tarname("bz2"))
if os.path.exists(dirname()):
shutil.rmtree(dirname())
if os.path.exists(tmpname()):
os.remove(tmpname())
if __name__ == "__main__":
test_main()
--- NEW FILE: test_tcl.py ---
#!/usr/bin/env python
import unittest
import os
from test import test_support
from Tkinter import Tcl
from _tkinter import TclError
class TclTest(unittest.TestCase):
def setUp(self):
self.interp = Tcl()
def testEval(self):
tcl = self.interp
tcl.eval('set a 1')
self.assertEqual(tcl.eval('set a'),'1')
def testEvalException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.eval,'set a')
def testEvalException2(self):
tcl = self.interp
self.assertRaises(TclError,tcl.eval,'this is wrong')
def testCall(self):
tcl = self.interp
tcl.call('set','a','1')
self.assertEqual(tcl.call('set','a'),'1')
def testCallException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.call,'set','a')
def testCallException2(self):
tcl = self.interp
self.assertRaises(TclError,tcl.call,'this','is','wrong')
def testSetVar(self):
tcl = self.interp
tcl.setvar('a','1')
self.assertEqual(tcl.eval('set a'),'1')
def testSetVarArray(self):
tcl = self.interp
tcl.setvar('a(1)','1')
self.assertEqual(tcl.eval('set a(1)'),'1')
def testGetVar(self):
tcl = self.interp
tcl.eval('set a 1')
self.assertEqual(tcl.getvar('a'),'1')
def testGetVarArray(self):
tcl = self.interp
tcl.eval('set a(1) 1')
self.assertEqual(tcl.getvar('a(1)'),'1')
def testGetVarException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.getvar,'a')
def testGetVarArrayException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.getvar,'a(1)')
def testUnsetVar(self):
tcl = self.interp
tcl.setvar('a',1)
self.assertEqual(tcl.eval('info exists a'),'1')
tcl.unsetvar('a')
self.assertEqual(tcl.eval('info exists a'),'0')
def testUnsetVarArray(self):
tcl = self.interp
tcl.setvar('a(1)',1)
tcl.setvar('a(2)',2)
self.assertEqual(tcl.eval('info exists a(1)'),'1')
self.assertEqual(tcl.eval('info exists a(2)'),'1')
tcl.unsetvar('a(1)')
self.assertEqual(tcl.eval('info exists a(1)'),'0')
self.assertEqual(tcl.eval('info exists a(2)'),'1')
def testUnsetVarException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.unsetvar,'a')
def testEvalFile(self):
tcl = self.interp
filename = "testEvalFile.tcl"
fd = open(filename,'w')
script = """set a 1
set b 2
set c [ expr $a + $b ]
"""
fd.write(script)
fd.close()
tcl.evalfile(filename)
os.remove(filename)
self.assertEqual(tcl.eval('set a'),'1')
self.assertEqual(tcl.eval('set b'),'2')
self.assertEqual(tcl.eval('set c'),'3')
def testEvalFileException(self):
tcl = self.interp
filename = "doesnotexists"
try:
os.remove(filename)
except Exception,e:
pass
self.assertRaises(TclError,tcl.evalfile,filename)
def testPackageRequireException(self):
tcl = self.interp
self.assertRaises(TclError,tcl.eval,'package require DNE')
def testLoadTk(self):
import os
if 'DISPLAY' not in os.environ:
# skipping test of clean upgradeability
return
tcl = Tcl()
self.assertRaises(TclError,tcl.winfo_geometry)
tcl.loadtk()
self.assertEqual('1x1+0+0', tcl.winfo_geometry())
def testLoadTkFailure(self):
import os
old_display = None
import sys
if sys.platform.startswith('win') or sys.platform.startswith('darwin'):
return # no failure possible on windows?
if 'DISPLAY' in os.environ:
old_display = os.environ['DISPLAY']
del os.environ['DISPLAY']
# on some platforms, deleting environment variables
# doesn't actually carry through to the process level
# because they don't support unsetenv
# If that's the case, abort.
display = os.popen('echo $DISPLAY').read().strip()
if display:
return
try:
tcl = Tcl()
self.assertRaises(TclError, tcl.winfo_geometry)
self.assertRaises(TclError, tcl.loadtk)
finally:
if old_display is not None:
os.environ['DISPLAY'] = old_display
def test_main():
test_support.run_unittest(TclTest)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_textwrap.py ---
#
# Test script for the textwrap module.
#
# Original tests written by Greg Ward <gward at python.net>.
# Converted to PyUnit by Peter Hansen <peter at engcorp.com>.
# Currently maintained by Greg Ward.
#
# $Id: test_textwrap.py,v 1.1 2004/05/01 00:54:16 tismer Exp $
#
import unittest
from test import test_support
from textwrap import TextWrapper, wrap, fill, dedent
class BaseTestCase(unittest.TestCase):
'''Parent class with utility methods for textwrap tests.'''
def show(self, textin):
if isinstance(textin, list):
result = []
for i in range(len(textin)):
result.append(" %d: %r" % (i, textin[i]))
result = '\n'.join(result)
elif isinstance(textin, basestring):
result = " %s\n" % repr(textin)
return result
def check(self, result, expect):
self.assertEquals(result, expect,
'expected:\n%s\nbut got:\n%s' % (
self.show(expect), self.show(result)))
def check_wrap(self, text, width, expect, **kwargs):
result = wrap(text, width, **kwargs)
self.check(result, expect)
def check_split(self, text, expect):
result = self.wrapper._split(text)
self.assertEquals(result, expect,
"\nexpected %r\n"
"but got %r" % (expect, result))
class WrapTestCase(BaseTestCase):
def setUp(self):
self.wrapper = TextWrapper(width=45, fix_sentence_endings=True)
def test_simple(self):
# Simple case: just words, spaces, and a bit of punctuation
text = "Hello there, how are you this fine day? I'm glad to hear it!"
self.check_wrap(text, 12,
["Hello there,",
"how are you",
"this fine",
"day? I'm",
"glad to hear",
"it!"])
self.check_wrap(text, 42,
["Hello there, how are you this fine day?",
"I'm glad to hear it!"])
self.check_wrap(text, 80, [text])
def test_whitespace(self):
# Whitespace munging and end-of-sentence detection
text = """\
This is a paragraph that already has
line breaks. But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""
expect = ["This is a paragraph that already has line",
"breaks. But some of its lines are much",
"longer than the others, so it needs to be",
"wrapped. Some lines are tabbed too. What a",
"mess!"]
result = self.wrapper.wrap(text)
self.check(result, expect)
result = self.wrapper.fill(text)
self.check(result, '\n'.join(expect))
def test_wrap_short(self):
# Wrapping to make short lines longer
text = "This is a\nshort paragraph."
self.check_wrap(text, 20, ["This is a short",
"paragraph."])
self.check_wrap(text, 40, ["This is a short paragraph."])
def test_wrap_short_1line(self):
# Test endcases
text = "This is a short line."
self.check_wrap(text, 30, ["This is a short line."])
self.check_wrap(text, 30, ["(1) This is a short line."],
initial_indent="(1) ")
def test_hyphenated(self):
# Test breaking hyphenated words
text = ("this-is-a-useful-feature-for-"
"reformatting-posts-from-tim-peters'ly")
self.check_wrap(text, 40,
["this-is-a-useful-feature-for-",
"reformatting-posts-from-tim-peters'ly"])
self.check_wrap(text, 41,
["this-is-a-useful-feature-for-",
"reformatting-posts-from-tim-peters'ly"])
self.check_wrap(text, 42,
["this-is-a-useful-feature-for-reformatting-",
"posts-from-tim-peters'ly"])
def test_em_dash(self):
# Test text with em-dashes
text = "Em-dashes should be written -- thus."
self.check_wrap(text, 25,
["Em-dashes should be",
"written -- thus."])
# Probe the boundaries of the properly written em-dash,
# ie. " -- ".
self.check_wrap(text, 29,
["Em-dashes should be written",
"-- thus."])
expect = ["Em-dashes should be written --",
"thus."]
self.check_wrap(text, 30, expect)
self.check_wrap(text, 35, expect)
self.check_wrap(text, 36,
["Em-dashes should be written -- thus."])
# The improperly written em-dash is handled too, because
# it's adjacent to non-whitespace on both sides.
text = "You can also do--this or even---this."
expect = ["You can also do",
"--this or even",
"---this."]
self.check_wrap(text, 15, expect)
self.check_wrap(text, 16, expect)
expect = ["You can also do--",
"this or even---",
"this."]
self.check_wrap(text, 17, expect)
self.check_wrap(text, 19, expect)
expect = ["You can also do--this or even",
"---this."]
self.check_wrap(text, 29, expect)
self.check_wrap(text, 31, expect)
expect = ["You can also do--this or even---",
"this."]
self.check_wrap(text, 32, expect)
self.check_wrap(text, 35, expect)
# All of the above behaviour could be deduced by probing the
# _split() method.
text = "Here's an -- em-dash and--here's another---and another!"
expect = ["Here's", " ", "an", " ", "--", " ", "em-", "dash", " ",
"and", "--", "here's", " ", "another", "---",
"and", " ", "another!"]
self.check_split(text, expect)
text = "and then--bam!--he was gone"
expect = ["and", " ", "then", "--", "bam!", "--",
"he", " ", "was", " ", "gone"]
self.check_split(text, expect)
def test_unix_options (self):
# Test that Unix-style command-line options are wrapped correctly.
# Both Optik (OptionParser) and Docutils rely on this behaviour!
text = "You should use the -n option, or --dry-run in its long form."
self.check_wrap(text, 20,
["You should use the",
"-n option, or --dry-",
"run in its long",
"form."])
self.check_wrap(text, 21,
["You should use the -n",
"option, or --dry-run",
"in its long form."])
expect = ["You should use the -n option, or",
"--dry-run in its long form."]
self.check_wrap(text, 32, expect)
self.check_wrap(text, 34, expect)
self.check_wrap(text, 35, expect)
self.check_wrap(text, 38, expect)
expect = ["You should use the -n option, or --dry-",
"run in its long form."]
self.check_wrap(text, 39, expect)
self.check_wrap(text, 41, expect)
expect = ["You should use the -n option, or --dry-run",
"in its long form."]
self.check_wrap(text, 42, expect)
# Again, all of the above can be deduced from _split().
text = "the -n option, or --dry-run or --dryrun"
expect = ["the", " ", "-n", " ", "option,", " ", "or", " ",
"--dry-", "run", " ", "or", " ", "--dryrun"]
self.check_split(text, expect)
def test_funky_hyphens (self):
# Screwy edge cases cooked up by David Goodger. All reported
# in SF bug #596434.
self.check_split("what the--hey!", ["what", " ", "the", "--", "hey!"])
self.check_split("what the--", ["what", " ", "the--"])
self.check_split("what the--.", ["what", " ", "the--."])
self.check_split("--text--.", ["--text--."])
# When I first read bug #596434, this is what I thought David
# was talking about. I was wrong; these have always worked
# fine. The real problem is tested in test_funky_parens()
# below...
self.check_split("--option", ["--option"])
self.check_split("--option-opt", ["--option-", "opt"])
self.check_split("foo --option-opt bar",
["foo", " ", "--option-", "opt", " ", "bar"])
def test_funky_parens (self):
# Second part of SF bug #596434: long option strings inside
# parentheses.
self.check_split("foo (--option) bar",
["foo", " ", "(--option)", " ", "bar"])
# Related stuff -- make sure parens work in simpler contexts.
self.check_split("foo (bar) baz",
["foo", " ", "(bar)", " ", "baz"])
self.check_split("blah (ding dong), wubba",
["blah", " ", "(ding", " ", "dong),",
" ", "wubba"])
def test_initial_whitespace(self):
# SF bug #622849 reported inconsistent handling of leading
# whitespace; let's test that a bit, shall we?
text = " This is a sentence with leading whitespace."
self.check_wrap(text, 50,
[" This is a sentence with leading whitespace."])
self.check_wrap(text, 30,
[" This is a sentence with", "leading whitespace."])
def test_unicode(self):
# *Very* simple test of wrapping Unicode strings. I'm sure
# there's more to it than this, but let's at least make
# sure textwrap doesn't crash on Unicode input!
text = u"Hello there, how are you today?"
self.check_wrap(text, 50, [u"Hello there, how are you today?"])
self.check_wrap(text, 20, [u"Hello there, how are", "you today?"])
olines = self.wrapper.wrap(text)
assert isinstance(olines, list) and isinstance(olines[0], unicode)
otext = self.wrapper.fill(text)
assert isinstance(otext, unicode)
def test_split(self):
# Ensure that the standard _split() method works as advertised
# in the comments
text = "Hello there -- you goof-ball, use the -b option!"
result = self.wrapper._split(text)
self.check(result,
["Hello", " ", "there", " ", "--", " ", "you", " ", "goof-",
"ball,", " ", "use", " ", "the", " ", "-b", " ", "option!"])
def test_bad_width(self):
# Ensure that width <= 0 is caught.
text = "Whatever, it doesn't matter."
self.assertRaises(ValueError, wrap, text, 0)
self.assertRaises(ValueError, wrap, text, -1)
class LongWordTestCase (BaseTestCase):
def setUp(self):
self.wrapper = TextWrapper()
self.text = '''\
Did you say "supercalifragilisticexpialidocious?"
How *do* you spell that odd word, anyways?
'''
def test_break_long(self):
# Wrap text with long words and lots of punctuation
self.check_wrap(self.text, 30,
['Did you say "supercalifragilis',
'ticexpialidocious?" How *do*',
'you spell that odd word,',
'anyways?'])
self.check_wrap(self.text, 50,
['Did you say "supercalifragilisticexpialidocious?"',
'How *do* you spell that odd word, anyways?'])
# SF bug 797650. Prevent an infinite loop by making sure that at
# least one character gets split off on every pass.
self.check_wrap('-'*10+'hello', 10,
['----------',
' h',
' e',
' l',
' l',
' o'],
subsequent_indent = ' '*15)
def test_nobreak_long(self):
# Test with break_long_words disabled
self.wrapper.break_long_words = 0
self.wrapper.width = 30
expect = ['Did you say',
'"supercalifragilisticexpialidocious?"',
'How *do* you spell that odd',
'word, anyways?'
]
result = self.wrapper.wrap(self.text)
self.check(result, expect)
# Same thing with kwargs passed to standalone wrap() function.
result = wrap(self.text, width=30, break_long_words=0)
self.check(result, expect)
class IndentTestCases(BaseTestCase):
# called before each test method
def setUp(self):
self.text = '''\
This paragraph will be filled, first without any indentation,
and then with some (including a hanging indent).'''
def test_fill(self):
# Test the fill() method
expect = '''\
This paragraph will be filled, first
without any indentation, and then with
some (including a hanging indent).'''
result = fill(self.text, 40)
self.check(result, expect)
def test_initial_indent(self):
# Test initial_indent parameter
expect = [" This paragraph will be filled,",
"first without any indentation, and then",
"with some (including a hanging indent)."]
result = wrap(self.text, 40, initial_indent=" ")
self.check(result, expect)
expect = "\n".join(expect)
result = fill(self.text, 40, initial_indent=" ")
self.check(result, expect)
def test_subsequent_indent(self):
# Test subsequent_indent parameter
expect = '''\
* This paragraph will be filled, first
without any indentation, and then
with some (including a hanging
indent).'''
result = fill(self.text, 40,
initial_indent=" * ", subsequent_indent=" ")
self.check(result, expect)
# Despite the similar names, DedentTestCase is *not* the inverse
# of IndentTestCase!
class DedentTestCase(unittest.TestCase):
def test_dedent_nomargin(self):
# No lines indented.
text = "Hello there.\nHow are you?\nOh good, I'm glad."
self.assertEquals(dedent(text), text)
# Similar, with a blank line.
text = "Hello there.\n\nBoo!"
self.assertEquals(dedent(text), text)
# Some lines indented, but overall margin is still zero.
text = "Hello there.\n This is indented."
self.assertEquals(dedent(text), text)
# Again, add a blank line.
text = "Hello there.\n\n Boo!\n"
self.assertEquals(dedent(text), text)
def test_dedent_even(self):
# All lines indented by two spaces.
text = " Hello there.\n How are ya?\n Oh good."
expect = "Hello there.\nHow are ya?\nOh good."
self.assertEquals(dedent(text), expect)
# Same, with blank lines.
text = " Hello there.\n\n How are ya?\n Oh good.\n"
expect = "Hello there.\n\nHow are ya?\nOh good.\n"
self.assertEquals(dedent(text), expect)
# Now indent one of the blank lines.
text = " Hello there.\n \n How are ya?\n Oh good.\n"
expect = "Hello there.\n\nHow are ya?\nOh good.\n"
self.assertEquals(dedent(text), expect)
def test_dedent_uneven(self):
# Lines indented unevenly.
text = '''\
def foo():
while 1:
return foo
'''
expect = '''\
def foo():
while 1:
return foo
'''
self.assertEquals(dedent(text), expect)
# Uneven indentation with a blank line.
text = " Foo\n Bar\n\n Baz\n"
expect = "Foo\n Bar\n\n Baz\n"
self.assertEquals(dedent(text), expect)
# Uneven indentation with a whitespace-only line.
text = " Foo\n Bar\n \n Baz\n"
expect = "Foo\n Bar\n\n Baz\n"
self.assertEquals(dedent(text), expect)
def test_main():
test_support.run_unittest(WrapTestCase,
LongWordTestCase,
IndentTestCases,
DedentTestCase)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_timeout.py ---
"""Unit tests for socket timeout feature."""
import unittest
from test import test_support
# This requires the 'network' resource as given on the regrtest command line.
skip_expected = not test_support.is_resource_enabled('network')
import time
import socket
class CreationTestCase(unittest.TestCase):
"""Test case for socket.gettimeout() and socket.settimeout()"""
def setUp(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def tearDown(self):
self.sock.close()
def testObjectCreation(self):
# Test Socket creation
self.assertEqual(self.sock.gettimeout(), None,
"timeout not disabled by default")
def testFloatReturnValue(self):
# Test return value of gettimeout()
self.sock.settimeout(7.345)
self.assertEqual(self.sock.gettimeout(), 7.345)
self.sock.settimeout(3)
self.assertEqual(self.sock.gettimeout(), 3)
self.sock.settimeout(None)
self.assertEqual(self.sock.gettimeout(), None)
def testReturnType(self):
# Test return type of gettimeout()
self.sock.settimeout(1)
self.assertEqual(type(self.sock.gettimeout()), type(1.0))
self.sock.settimeout(3.9)
self.assertEqual(type(self.sock.gettimeout()), type(1.0))
def testTypeCheck(self):
# Test type checking by settimeout()
self.sock.settimeout(0)
self.sock.settimeout(0L)
self.sock.settimeout(0.0)
self.sock.settimeout(None)
self.assertRaises(TypeError, self.sock.settimeout, "")
self.assertRaises(TypeError, self.sock.settimeout, u"")
self.assertRaises(TypeError, self.sock.settimeout, ())
self.assertRaises(TypeError, self.sock.settimeout, [])
self.assertRaises(TypeError, self.sock.settimeout, {})
self.assertRaises(TypeError, self.sock.settimeout, 0j)
def testRangeCheck(self):
# Test range checking by settimeout()
self.assertRaises(ValueError, self.sock.settimeout, -1)
self.assertRaises(ValueError, self.sock.settimeout, -1L)
self.assertRaises(ValueError, self.sock.settimeout, -1.0)
def testTimeoutThenBlocking(self):
# Test settimeout() followed by setblocking()
self.sock.settimeout(10)
self.sock.setblocking(1)
self.assertEqual(self.sock.gettimeout(), None)
self.sock.setblocking(0)
self.assertEqual(self.sock.gettimeout(), 0.0)
self.sock.settimeout(10)
self.sock.setblocking(0)
self.assertEqual(self.sock.gettimeout(), 0.0)
self.sock.setblocking(1)
self.assertEqual(self.sock.gettimeout(), None)
def testBlockingThenTimeout(self):
# Test setblocking() followed by settimeout()
self.sock.setblocking(0)
self.sock.settimeout(1)
self.assertEqual(self.sock.gettimeout(), 1)
self.sock.setblocking(1)
self.sock.settimeout(1)
self.assertEqual(self.sock.gettimeout(), 1)
class TimeoutTestCase(unittest.TestCase):
"""Test case for socket.socket() timeout functions"""
# There are a number of tests here trying to make sure that an operation
# doesn't take too much longer than expected. But competing machine
# activity makes it inevitable that such tests will fail at times.
# When fuzz was at 1.0, I (tim) routinely saw bogus failures on Win2K
# and Win98SE. Boosting it to 2.0 helped a lot, but isn't a real
# solution.
fuzz = 2.0
def setUp(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addr_remote = ('www.google.com', 80)
self.addr_local = ('127.0.0.1', 25339)
def tearDown(self):
self.sock.close()
def testConnectTimeout(self):
# Test connect() timeout
_timeout = 0.001
self.sock.settimeout(_timeout)
_t1 = time.time()
self.failUnlessRaises(socket.error, self.sock.connect,
self.addr_remote)
_t2 = time.time()
_delta = abs(_t1 - _t2)
self.assert_(_delta < _timeout + self.fuzz,
"timeout (%g) is %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
def testRecvTimeout(self):
# Test recv() timeout
_timeout = 0.02
self.sock.connect(self.addr_remote)
self.sock.settimeout(_timeout)
_t1 = time.time()
self.failUnlessRaises(socket.error, self.sock.recv, 1024)
_t2 = time.time()
_delta = abs(_t1 - _t2)
self.assert_(_delta < _timeout + self.fuzz,
"timeout (%g) is %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
def testAcceptTimeout(self):
# Test accept() timeout
_timeout = 2
self.sock.settimeout(_timeout)
self.sock.bind(self.addr_local)
self.sock.listen(5)
_t1 = time.time()
self.failUnlessRaises(socket.error, self.sock.accept)
_t2 = time.time()
_delta = abs(_t1 - _t2)
self.assert_(_delta < _timeout + self.fuzz,
"timeout (%g) is %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
def testRecvfromTimeout(self):
# Test recvfrom() timeout
_timeout = 2
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(_timeout)
self.sock.bind(self.addr_local)
_t1 = time.time()
self.failUnlessRaises(socket.error, self.sock.recvfrom, 8192)
_t2 = time.time()
_delta = abs(_t1 - _t2)
self.assert_(_delta < _timeout + self.fuzz,
"timeout (%g) is %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
def testSend(self):
# Test send() timeout
# couldn't figure out how to test it
pass
def testSendto(self):
# Test sendto() timeout
# couldn't figure out how to test it
pass
def testSendall(self):
# Test sendall() timeout
# couldn't figure out how to test it
pass
def test_main():
test_support.requires('network')
test_support.run_unittest(CreationTestCase, TimeoutTestCase)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_tuple.py ---
import unittest
from test import test_support, seq_tests
class TupleTest(seq_tests.CommonTest):
type2test = tuple
def test_constructors(self):
super(TupleTest, self).test_len()
# calling built-in types without argument must return empty
self.assertEqual(tuple(), ())
def test_truth(self):
super(TupleTest, self).test_truth()
self.assert_(not ())
self.assert_((42, ))
def test_len(self):
super(TupleTest, self).test_len()
self.assertEqual(len(()), 0)
self.assertEqual(len((0,)), 1)
self.assertEqual(len((0, 1, 2)), 3)
def test_iadd(self):
super(TupleTest, self).test_iadd()
u = (0, 1)
u2 = u
u += (2, 3)
self.assert_(u is not u2)
def test_imul(self):
super(TupleTest, self).test_imul()
u = (0, 1)
u2 = u
u *= 3
self.assert_(u is not u2)
def test_tupleresizebug(self):
# Check that a specific bug in _PyTuple_Resize() is squashed.
def f():
for i in range(1000):
yield i
self.assertEqual(list(tuple(f())), range(1000))
def test_main():
test_support.run_unittest(TupleTest)
if __name__=="__main__":
test_main()
--- NEW FILE: test_univnewlines.py ---
# Tests universal newline support for both reading and parsing files.
import unittest
import os
import sys
from test import test_support
if not hasattr(sys.stdin, 'newlines'):
raise test_support.TestSkipped, \
"This Python does not have universal newline support"
FATX = 'x' * (2**14)
DATA_TEMPLATE = [
"line1=1",
"line2='this is a very long line designed to go past the magic " +
"hundred character limit that is inside fileobject.c and which " +
"is meant to speed up the common case, but we also want to test " +
"the uncommon case, naturally.'",
"def line3():pass",
"line4 = '%s'" % FATX,
]
DATA_LF = "\n".join(DATA_TEMPLATE) + "\n"
DATA_CR = "\r".join(DATA_TEMPLATE) + "\r"
DATA_CRLF = "\r\n".join(DATA_TEMPLATE) + "\r\n"
# Note that DATA_MIXED also tests the ability to recognize a lone \r
# before end-of-file.
DATA_MIXED = "\n".join(DATA_TEMPLATE) + "\r"
DATA_SPLIT = [x + "\n" for x in DATA_TEMPLATE]
del x
class TestGenericUnivNewlines(unittest.TestCase):
# use a class variable DATA to define the data to write to the file
# and a class variable NEWLINE to set the expected newlines value
READMODE = 'U'
WRITEMODE = 'wb'
def setUp(self):
fp = open(test_support.TESTFN, self.WRITEMODE)
fp.write(self.DATA)
fp.close()
def tearDown(self):
try:
os.unlink(test_support.TESTFN)
except:
pass
def test_read(self):
fp = open(test_support.TESTFN, self.READMODE)
data = fp.read()
self.assertEqual(data, DATA_LF)
self.assertEqual(repr(fp.newlines), repr(self.NEWLINE))
def test_readlines(self):
fp = open(test_support.TESTFN, self.READMODE)
data = fp.readlines()
self.assertEqual(data, DATA_SPLIT)
self.assertEqual(repr(fp.newlines), repr(self.NEWLINE))
def test_readline(self):
fp = open(test_support.TESTFN, self.READMODE)
data = []
d = fp.readline()
while d:
data.append(d)
d = fp.readline()
self.assertEqual(data, DATA_SPLIT)
self.assertEqual(repr(fp.newlines), repr(self.NEWLINE))
def test_seek(self):
fp = open(test_support.TESTFN, self.READMODE)
fp.readline()
pos = fp.tell()
data = fp.readlines()
self.assertEqual(data, DATA_SPLIT[1:])
fp.seek(pos)
data = fp.readlines()
self.assertEqual(data, DATA_SPLIT[1:])
def test_execfile(self):
namespace = {}
execfile(test_support.TESTFN, namespace)
func = namespace['line3']
self.assertEqual(func.func_code.co_firstlineno, 3)
self.assertEqual(namespace['line4'], FATX)
class TestNativeNewlines(TestGenericUnivNewlines):
NEWLINE = None
DATA = DATA_LF
READMODE = 'r'
WRITEMODE = 'w'
class TestCRNewlines(TestGenericUnivNewlines):
NEWLINE = '\r'
DATA = DATA_CR
class TestLFNewlines(TestGenericUnivNewlines):
NEWLINE = '\n'
DATA = DATA_LF
class TestCRLFNewlines(TestGenericUnivNewlines):
NEWLINE = '\r\n'
DATA = DATA_CRLF
class TestMixedNewlines(TestGenericUnivNewlines):
NEWLINE = ('\r', '\n')
DATA = DATA_MIXED
def test_main():
test_support.run_unittest(
TestNativeNewlines,
TestCRNewlines,
TestLFNewlines,
TestCRLFNewlines,
TestMixedNewlines
)
if __name__ == '__main__':
test_main()
--- NEW FILE: test_urllibnet.py ---
#!/usr/bin/env python
import unittest
from test import test_support
import socket
import urllib
import sys
import os
import mimetools
class URLTimeoutTest(unittest.TestCase):
TIMEOUT = 10.0
def setUp(self):
socket.setdefaulttimeout(self.TIMEOUT)
def tearDown(self):
socket.setdefaulttimeout(None)
def testURLread(self):
f = urllib.urlopen("http://www.python.org/")
x = f.read()
class urlopenNetworkTests(unittest.TestCase):
"""Tests urllib.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
tests exercising the optional 'data' and 'proxies' arguments. No tests
for transparent redirection have been written.
setUp is not used for always constructing a connection to
http://www.python.org/ since there a few tests that don't use that address
and making a connection is expensive enough to warrant minimizing unneeded
connections.
"""
def test_basic(self):
# Simple test expected to pass.
open_url = urllib.urlopen("http://www.python.org/")
for attr in ("read", "readline", "readlines", "fileno", "close",
"info", "geturl"):
self.assert_(hasattr(open_url, attr), "object returned from "
"urlopen lacks the %s attribute" % attr)
try:
self.assert_(open_url.read(), "calling 'read' failed")
finally:
open_url.close()
def test_readlines(self):
# Test both readline and readlines.
open_url = urllib.urlopen("http://www.python.org/")
try:
self.assert_(isinstance(open_url.readline(), basestring),
"readline did not return a string")
self.assert_(isinstance(open_url.readlines(), list),
"readlines did not return a list")
finally:
open_url.close()
def test_info(self):
# Test 'info'.
open_url = urllib.urlopen("http://www.python.org/")
try:
info_obj = open_url.info()
finally:
open_url.close()
self.assert_(isinstance(info_obj, mimetools.Message),
"object returned by 'info' is not an instance of "
"mimetools.Message")
self.assertEqual(info_obj.getsubtype(), "html")
def test_geturl(self):
# Make sure same URL as opened is returned by geturl.
URL = "http://www.python.org/"
open_url = urllib.urlopen(URL)
try:
gotten_url = open_url.geturl()
finally:
open_url.close()
self.assertEqual(gotten_url, URL)
def test_fileno(self):
if (sys.platform in ('win32',) or
not hasattr(os, 'fdopen')):
# On Windows, socket handles are not file descriptors; this
# test can't pass on Windows.
return
# Make sure fd returned by fileno is valid.
open_url = urllib.urlopen("http://www.python.org/")
fd = open_url.fileno()
FILE = os.fdopen(fd)
try:
self.assert_(FILE.read(), "reading from file created using fd "
"returned by fileno failed")
finally:
FILE.close()
def test_bad_address(self):
# Make sure proper exception is raised when connecting to a bogus
# address.
self.assertRaises(IOError,
# SF patch 809915: In Sep 2003, VeriSign started
# highjacking invalid .com and .net addresses to
# boost traffic to their own site. This test
# started failing then. One hopes the .invalid
# domain will be spared to serve its defined
# purpose.
# urllib.urlopen, "http://www.sadflkjsasadf.com/")
urllib.urlopen, "http://www.python.invalid/")
class urlretrieveNetworkTests(unittest.TestCase):
"""Tests urllib.urlretrieve using the network."""
def test_basic(self):
# Test basic functionality.
file_location,info = urllib.urlretrieve("http://www.python.org/")
self.assert_(os.path.exists(file_location), "file location returned by"
" urlretrieve is not a valid path")
FILE = file(file_location)
try:
self.assert_(FILE.read(), "reading from the file location returned"
" by urlretrieve failed")
finally:
FILE.close()
os.unlink(file_location)
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)
self.assertEqual(file_location, test_support.TESTFN)
self.assert_(os.path.exists(file_location))
FILE = file(file_location)
try:
self.assert_(FILE.read(), "reading from temporary file failed")
finally:
FILE.close()
os.unlink(file_location)
def test_header(self):
# Make sure header returned as 2nd value from urlretrieve is good.
file_location, header = urllib.urlretrieve("http://www.python.org/")
os.unlink(file_location)
self.assert_(isinstance(header, mimetools.Message),
"header is not an instance of mimetools.Message")
def test_main():
test_support.requires('network')
test_support.run_unittest(URLTimeoutTest,
urlopenNetworkTests,
urlretrieveNetworkTests)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_warnings.py ---
import warnings
import os
import unittest
from test import test_support
# The warnings module isn't easily tested, because it relies on module
# globals to store configuration information. setUp() and tearDown()
# preserve the current settings to avoid bashing them while running tests.
# To capture the warning messages, a replacement for showwarning() is
# used to save warning information in a global variable.
class WarningMessage:
"Holds results of latest showwarning() call"
pass
def showwarning(message, category, filename, lineno, file=None):
msg.message = str(message)
msg.category = category.__name__
msg.filename = os.path.basename(filename)
msg.lineno = lineno
class TestModule(unittest.TestCase):
def setUp(self):
global msg
msg = WarningMessage()
self._filters = warnings.filters[:]
self._showwarning = warnings.showwarning
warnings.showwarning = showwarning
self.ignored = [w[2].__name__ for w in self._filters
if w[0]=='ignore' and w[1] is None and w[3] is None]
def tearDown(self):
warnings.filters = self._filters[:]
warnings.showwarning = self._showwarning
def test_warn_default_category(self):
for i in range(4):
text = 'multi %d' %i # Different text on each call
warnings.warn(text)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, 'UserWarning')
def test_warn_specific_category(self):
text = 'None'
for category in [DeprecationWarning, FutureWarning, OverflowWarning,
PendingDeprecationWarning, RuntimeWarning,
SyntaxWarning, UserWarning, Warning]:
if category.__name__ in self.ignored:
text = 'filtered out' + category.__name__
warnings.warn(text, category)
self.assertNotEqual(msg.message, text)
else:
text = 'unfiltered %s' % category.__name__
warnings.warn(text, category)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, category.__name__)
def test_filtering(self):
warnings.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, warnings.warn, 'convert to error')
warnings.resetwarnings()
text = 'handle normally'
warnings.warn(text)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, 'UserWarning')
warnings.filterwarnings("ignore", "", Warning, "", 0)
text = 'filtered out'
warnings.warn(text)
self.assertNotEqual(msg.message, text)
warnings.resetwarnings()
warnings.filterwarnings("error", "hex*", Warning, "", 0)
self.assertRaises(UserWarning, warnings.warn, 'hex/oct')
text = 'nonmatching text'
warnings.warn(text)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, 'UserWarning')
def test_main(verbose=None):
test_support.run_unittest(TestModule)
if __name__ == "__main__":
test_main(verbose=True)
--- NEW FILE: test_whichdb.py ---
#! /usr/bin/env python
"""Test script for the whichdb module
based on test_anydbm.py
"""
import os
import test.test_support
import unittest
import whichdb
import anydbm
import tempfile
import glob
_fname = test.test_support.TESTFN
def _delete_files():
# we don't know the precise name the underlying database uses
# so we use glob to locate all names
for f in glob.glob(_fname + "*"):
try:
os.unlink(f)
except OSError:
pass
class WhichDBTestCase(unittest.TestCase):
# Actual test methods are added to namespace
# after class definition.
def __init__(self, *args):
unittest.TestCase.__init__(self, *args)
def tearDown(self):
_delete_files()
def setUp(self):
_delete_files()
for name in anydbm._names:
# we define a new test method for each
# candidate database module.
try:
mod = __import__(name)
except ImportError:
continue
def test_whichdb_name(self, name=name, mod=mod):
# Check whether whichdb correctly guesses module name
# for databases opened with module mod.
# Try with empty files first
f = mod.open(_fname, 'c')
f.close()
self.assertEqual(name, whichdb.whichdb(_fname))
# Now add a key
f = mod.open(_fname, 'w')
f["1"] = "1"
f.close()
self.assertEqual(name, whichdb.whichdb(_fname))
setattr(WhichDBTestCase,"test_whichdb_%s" % name, test_whichdb_name)
def test_main():
try:
test.test_support.run_unittest(WhichDBTestCase)
finally:
_delete_files()
if __name__ == "__main__":
test_main()
--- NEW FILE: test_xpickle.py ---
# test_pickle dumps and loads pickles via pickle.py.
# test_cpickle does the same, but via the cPickle module.
# This test covers the other two cases, making pickles with one module and
# loading them via the other.
import pickle
import cPickle
import unittest
from test import test_support
from test.pickletester import AbstractPickleTests
class DumpCPickle_LoadPickle(AbstractPickleTests):
error = KeyError
def dumps(self, arg, proto=0, fast=0):
# Ignore fast
return cPickle.dumps(arg, proto)
def loads(self, buf):
# Ignore fast
return pickle.loads(buf)
class DumpPickle_LoadCPickle(AbstractPickleTests):
error = cPickle.BadPickleGet
def dumps(self, arg, proto=0, fast=0):
# Ignore fast
return pickle.dumps(arg, proto)
def loads(self, buf):
# Ignore fast
return cPickle.loads(buf)
def test_main():
test_support.run_unittest(
DumpCPickle_LoadPickle,
DumpPickle_LoadCPickle
)
if __name__ == "__main__":
test_main()
--- NEW FILE: test_zipimport.py ---
import sys
import os
import marshal
import imp
import struct
import time
import zlib # implied prerequisite
from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
from test import test_support
from test.test_importhooks import ImportHooksBaseTestCase, test_src, test_co
import zipimport
def make_pyc(co, mtime):
data = marshal.dumps(co)
if type(mtime) is type(0.0):
# Mac mtimes need a bit of special casing
if mtime < 0x7fffffff:
mtime = int(mtime)
else:
mtime = int(-0x100000000L + long(mtime))
pyc = imp.get_magic() + struct.pack("<i", int(mtime)) + data
return pyc
NOW = time.time()
test_pyc = make_pyc(test_co, NOW)
if __debug__:
pyc_ext = ".pyc"
else:
pyc_ext = ".pyo"
TESTMOD = "ziptestmodule"
TESTPACK = "ziptestpackage"
TESTPACK2 = "ziptestpackage2"
TEMP_ZIP = os.path.abspath("junk95142" + os.extsep + "zip")
class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
compression = ZIP_STORED
def setUp(self):
# We're reusing the zip archive path, so we must clear the
# cached directory info.
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
def doTest(self, expected_ext, files, *modules, **kw):
z = ZipFile(TEMP_ZIP, "w")
try:
for name, (mtime, data) in files.items():
zinfo = ZipInfo(name, time.localtime(mtime))
zinfo.compress_type = self.compression
z.writestr(zinfo, data)
z.close()
stuff = kw.get("stuff", None)
if stuff is not None:
# Prepend 'stuff' to the start of the zipfile
f = open(TEMP_ZIP, "rb")
data = f.read()
f.close()
f = open(TEMP_ZIP, "wb")
f.write(stuff)
f.write(data)
f.close()
sys.path.insert(0, TEMP_ZIP)
mod = __import__(".".join(modules), globals(), locals(),
["__dummy__"])
if expected_ext:
file = mod.get_file()
self.assertEquals(file, os.path.join(TEMP_ZIP,
*modules) + expected_ext)
finally:
z.close()
os.remove(TEMP_ZIP)
def testAFakeZlib(self):
#
# This could cause a stack overflow before: importing zlib.py
# from a compressed archive would cause zlib to be imported
# which would find zlib.py in the archive, which would... etc.
#
# This test *must* be executed first: it must be the first one
# to trigger zipimport to import zlib (zipimport caches the
# zlib.decompress function object, after which the problem being
# tested here wouldn't be a problem anymore...
# (Hence the 'A' in the test method name: to make it the first
# item in a list sorted by name, like unittest.makeSuite() does.)
#
# This test fails on platforms on which the zlib module is
# statically linked, but the problem it tests for can't
# occur in that case (builtin modules are always found first),
# so we'll simply skip it then. Bug #765456.
#
if "zlib" in sys.builtin_module_names:
return
if "zlib" in sys.modules:
del sys.modules["zlib"]
files = {"zlib.py": (NOW, test_src)}
try:
self.doTest(".py", files, "zlib")
except ImportError:
if self.compression != ZIP_DEFLATED:
self.fail("expected test to not raise ImportError")
else:
if self.compression != ZIP_STORED:
self.fail("expected test to raise ImportError")
def testPy(self):
files = {TESTMOD + ".py": (NOW, test_src)}
self.doTest(".py", files, TESTMOD)
def testPyc(self):
files = {TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTMOD)
def testBoth(self):
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTMOD)
def testEmptyPy(self):
files = {TESTMOD + ".py": (NOW, "")}
self.doTest(None, files, TESTMOD)
def testBadMagic(self):
# make pyc magic word invalid, forcing loading from .py
m0 = ord(test_pyc[0])
m0 ^= 0x04 # flip an arbitrary bit
badmagic_pyc = chr(m0) + test_pyc[1:]
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
self.doTest(".py", files, TESTMOD)
def testBadMagic2(self):
# make pyc magic word invalid, causing an ImportError
m0 = ord(test_pyc[0])
m0 ^= 0x04 # flip an arbitrary bit
badmagic_pyc = chr(m0) + test_pyc[1:]
files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
try:
self.doTest(".py", files, TESTMOD)
except ImportError:
pass
else:
self.fail("expected ImportError; import from bad pyc")
def testBadMTime(self):
t3 = ord(test_pyc[7])
t3 ^= 0x02 # flip the second bit -- not the first as that one
# isn't stored in the .py's mtime in the zip archive.
badtime_pyc = test_pyc[:7] + chr(t3) + test_pyc[8:]
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, badtime_pyc)}
self.doTest(".py", files, TESTMOD)
def testPackage(self):
packdir = TESTPACK + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
packdir + TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTPACK, TESTMOD)
def testDeepPackage(self):
packdir = TESTPACK + os.sep
packdir2 = packdir + TESTPACK2 + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
def testGetData(self):
z = ZipFile(TEMP_ZIP, "w")
z.compression = self.compression
try:
name = "testdata.dat"
data = "".join([chr(x) for x in range(256)]) * 500
z.writestr(name, data)
z.close()
zi = zipimport.zipimporter(TEMP_ZIP)
self.assertEquals(data, zi.get_data(name))
finally:
z.close()
os.remove(TEMP_ZIP)
def testImporterAttr(self):
src = """if 1: # indent hack
def get_file():
return __file__
if __loader__.get_data("some.data") != "some data":
raise AssertionError, "bad data"\n"""
pyc = make_pyc(compile(src, "<???>", "exec"), NOW)
files = {TESTMOD + pyc_ext: (NOW, pyc),
"some.data": (NOW, "some data")}
self.doTest(pyc_ext, files, TESTMOD)
def testImport_WithStuff(self):
# try importing from a zipfile which contains additional
# stuff at the beginning of the file
files = {TESTMOD + ".py": (NOW, test_src)}
self.doTest(".py", files, TESTMOD,
stuff="Some Stuff"*31)
class CompressedZipImportTestCase(UncompressedZipImportTestCase):
compression = ZIP_DEFLATED
def test_main():
test_support.run_unittest(
UncompressedZipImportTestCase,
CompressedZipImportTestCase
)
if __name__ == "__main__":
test_main()
--- NEW FILE: testtar.tar ---
0-REGTYPE
@Ñh±ÏÙÚÛ®
n¢0àÉDåÜîïµÅyEçÅSâhØ``}[Â[È>&â
QhRU
#$õ«Y³8(KbØ;4ìØ
SAUUY¥Ôt
;aðÃþîPÌøð]
õBÆkªh&b ¥Ôa@§#vJ
hxj«#ªªp«©¨Þ²vÖ!¹ÎÒ®Èj¢§þ&«(¦<Z¥ªÂR ËçW9ëm¹^°+äÒáWek.´hæ.Æà)hæbn&>IDj#ë5°¡ÀV"üx¿*ÕH@}ÃÄt8`±xj|±½àÈ0ÐÝ©hÖ!rµ1r?,Á
T&,M5;iÏà4u¶
y=3ºïÀkÁ«æв&¼S`YôýÒè)öpÃÿ>pú_ªp×!
añZªö1Î~Ì
p'ÏhÈ6Lrf?4Nj0iÄ5 iTj¾6³t
,:
*üÂÀðü-\ Àóø@FöèWcùã¤É
)2¼\_fÖQ_¹&sËüÄ0}@öÐ&upãÌèv7º§§]e0úåtd¥ÑÄ9
Ha´û>qÆLZCôù:gfÚEã¼£ÚÅ\,æÈf&ªÂ
¤±D4ªU×tÊÈ1µ««2
yLué:ä
®jÕ©è¨øt@F
@,[)¨Ï
¸ðxÑ ë
kÀ× Ð5á!8 ÆÄn e£l&T@pm`U"ãZ1N ÒÕ~ÇE9<RN& únK¬
¼ê¨ÖPmúÄùÙ8Ñ¥
Ñjþ W¼XãÕ#
¹;l Ð ¬!¤èwÃk©v¯¹ÀB at x¬·½ë*Cí¶È²ªÃÒÄÎ2ðªýÊhZ?ùÝD+Õ¥ü!3
Á
ÑÀHÈhñ¿Â¬e W(ôÒÔKùg
¦´äÁ<AÒùR
88§-÷M1Xx8pÈxv¦W¨S*7¢ýÑo0ì»_lA9è :só°*kÁJ/£/©W$ù2G#6à÷
àRâ⧯àTZþ áÞáÆÂÕ±* *äLÜõ_¶ñþZÃËYyEJæÃþ¡ÏoY."\ë>à-,mé'áhÌv˯
>v
g(ã EsRéq
R¥^Ý5ztSg°
]6ov8mèPh
ÕP&Ð]³1cÄ4£&üñ>&BÙ)Ù×~ù¦âVreyÓ¢|8]ùjb1 nå&IpϦ(Û︢9gþf%m7`¤¹¬y±ÀÚ?WÙ´Y[Rê`Ôv;o¢iN½ùc½à9dbtó Fy ïS PÉ1)Â
O°Áá
®aJ@æ®
Title: Index of Python Enhancement Proposals (PEPs)
Version: $Revision: 1.1 $
Last-Modified: $Date: 2004/05/01 00:54:16 $
Author: Barry A. Warsaw <barry at zope.com>
Status: Active
Type: Informational
Created: 13-Jul-2000
Post-History:
Introduction
The PEP contains the index of all Python Enhancement Proposals,
known as PEPs. PEP numbers are assigned by the PEP Editor, and
once assigned are never changed. The CVS history[1] of the PEP
texts represent their historical record.
The BDFL maintains his own Pronouncements page[2] at
http://www.python.org/doc/essays/pepparade.html which contains his
musings on the various outstanding PEPs.
Index by Category
num title owner
--- ----- -----
Meta-PEPs (PEPs about PEPs or Process)
I 0 Index of Python Enhancement Proposals Warsaw
I 1 PEP Guidelines Warsaw, Hylton
I 2 Procedure for Adding New Modules Faassen
I 3 Guidelines for Handling Bug Reports Hylton
I 4 Deprecation of Standard Modules von Loewis
I 5 Guidelines for Language Evolution Prescod
I 6 Bug Fix Releases Aahz
I 7 Style Guide for C Code van Rossum
I 8 Style Guide for Python Code van Rossum, Warsaw
I 9 Sample Plaintext PEP Template Warsaw
I 10 Voting Guidelines Warsaw
I 11 Removing support for little used platforms von Loewis
I 12 Sample reStructuredText PEP Template Goodger, Warsaw
Other Informational PEPs
I 101 Doing Python Releases 101 Warsaw, van Rossum
I 102 Doing Python Micro Releases Baxter, Warsaw, van Rossum
IF 247 API for Cryptographic Hash Functions Kuchling
IF 248 Python Database API Specification v1.0 Lemburg
IF 249 Python Database API Specification v2.0 Lemburg
I 257 Docstring Conventions Goodger, van Rossum
IF 272 API for Block Encryption Algorithms v1.0 Kuchling
I 290 Code Migration and Modernization Hettinger
Accepted PEPs (accepted; may not be implemented yet)
S 252 Making Types Look More Like Classes van Rossum
S 253 Subtyping Built-in Types van Rossum
Open PEPs (under consideration)
I 42 Small Feature Requests Hylton
I 206 2.0 Batteries Included Zadka
S 209 Adding Multidimensional Arrays Barrett, Oliphant
S 215 String Interpolation Yee
S 218 Adding a Built-In Set Object Type Wilson
S 228 Reworking Python's Numeric Model Zadka, van Rossum
S 237 Unifying Long Integers and Integers Zadka, van Rossum
S 239 Adding a Rational Type to Python Zadka
S 240 Adding a Rational Literal to Python Zadka
S 242 Numeric Kinds Dubois
S 243 Module Repository Upload Mechanism Reifschneider
S 245 Python Interface Syntax Pelletier
S 246 Object Adaptation Evans
S 254 Making Classes Look More Like Types van Rossum
S 256 Docstring Processing System Framework Goodger
S 258 Docutils Design Specification Goodger
S 262 Database of Installed Python Packages Kuchling
S 265 Sorting Dictionaries by Value Griffin
S 266 Optimizing Global Variable/Attribute Access Montanaro
S 267 Optimized Access to Module Namespaces Hylton
S 268 Extended HTTP functionality and WebDAV Stein
S 269 Pgen Module for Python Riehl
S 270 uniq method for list objects Petrone
S 273 Import Modules from Zip Archives Ahlstrom
S 274 Dict Comprehensions Warsaw
S 275 Switching on Multiple Values Lemburg
S 276 Simple Iterator for ints Althoff
S 277 Unicode file name support for Windows NT Hodgson
S 278 Universal Newline Support Jansen
S 280 Optimizing access to globals van Rossum
S 281 Loop Counter Iteration with range and xrange Hetland
S 282 A Logging System Sajip, Mick
I 283 Python 2.3 Release Schedule van Rossum
S 284 Integer for-loops Eppstein, Ewing
S 286 Enhanced Argument Tuples von Loewis
I 287 reStructuredText Docstring Format Goodger
I 291 Backward Compatibility for Standard Library Norwitz
S 292 Simpler String Substitutions Warsaw
S 294 Type Names in the types Module Tirosh
S 296 Adding a bytes Object Type Gilbert
S 297 Support for System Upgrades Lemburg
S 298 The Locked Buffer Interface Heller
S 299 Special __main__() function in modules Epler
Finished PEPs (done, implemented in CVS)
SF 100 Python Unicode Integration Lemburg
IF 160 Python 1.6 Release Schedule Drake
IF 200 Python 2.0 Release Schedule Hylton
SF 201 Lockstep Iteration Warsaw
SF 202 List Comprehensions Warsaw
SF 203 Augmented Assignments Wouters
S 205 Weak References Drake
SF 207 Rich Comparisons van Rossum, Ascher
SF 208 Reworking the Coercion Model Schemenauer, Lemburg
SF 214 Extended Print Statement Warsaw
SF 217 Display Hook for Interactive Use Zadka
SF 221 Import As Wouters
SF 223 Change the Meaning of \x Escapes Peters
I 226 Python 2.1 Release Schedule Hylton
S 227 Statically Nested Scopes Hylton
SF 229 Using Distutils to Build Python Kuchling
SF 230 Warning Framework van Rossum
SF 232 Function Attributes Warsaw
SF 234 Iterators Yee, van Rossum
SF 235 Import on Case-Insensitive Platforms Peters
SF 236 Back to the __future__ Peters
SF 238 Changing the Division Operator Zadka, van Rossum
SF 241 Metadata for Python Software Packages Kuchling
SF 250 Using site-packages on Windows Moore
IF 251 Python 2.2 Release Schedule Warsaw, van Rossum
SF 255 Simple Generators Schemenauer, et al
SF 260 Simplify xrange() van Rossum
S 261 Support for "wide" Unicode characters Prescod
SF 263 Defining Python Source Code Encodings Lemburg
SF 264 Future statements in simulated shells Hudson
SF 279 The enumerate() built-in function Hettinger
SF 285 Adding a bool type van Rossum
SF 293 Codec Error Handling Callbacks Dörwald
Empty PEPs (or containing only an abstract)
SD 210 Decoupling the Interpreter Loop Ascher
ID 220 Coroutines, Generators, Continuations McMillan
Deferred, Abandoned, Withdrawn, and Rejected PEPs
SR 204 Range Literals Wouters
SD 211 Adding A New Outer Product Operator Wilson
SD 212 Loop Counter Iteration Schneider-Kamp
SD 213 Attribute Access Handlers Prescod
IR 216 Docstring Format Zadka
SD 219 Stackless Python McMillan
SD 222 Web Library Enhancements Kuchling
SR 224 Attribute Docstrings Lemburg
SD 225 Elementwise/Objectwise Operators Zhu, Lielens
SR 231 __findattr__() Warsaw
SD 233 Python Online Help Prescod
SR 244 The `directive' Statement von Loewis
SR 259 Omit printing newline after newline van Rossum
SR 271 Prefixing sys.path by command line option Giacometti
SD 288 Generators Attributes and Exceptions Hettinger
SR 289 Generator Comprehensions Hettinger
SR 295 Interpretation of multiline string constants Koltsov
SR 666 Reject Foolish Indentation Creighton
Numerical Index
num title owner
--- ----- -----
I 0 Index of Python Enhancement Proposals Warsaw
I 1 PEP Guidelines Warsaw, Hylton
I 2 Procedure for Adding New Modules Faassen
I 3 Guidelines for Handling Bug Reports Hylton
I 4 Deprecation of Standard Modules von Loewis
I 5 Guidelines for Language Evolution Prescod
I 6 Bug Fix Releases Aahz
I 7 Style Guide for C Code van Rossum
I 8 Style Guide for Python Code van Rossum, Warsaw
I 9 Sample Plaintext PEP Template Warsaw
I 10 Voting Guidelines Warsaw
I 11 Removing support for little used platforms von Loewis
I 12 Sample reStructuredText PEP Template Goodger, Warsaw
I 42 Small Feature Requests Hylton
SF 100 Python Unicode Integration Lemburg
I 101 Doing Python Releases 101 Warsaw, van Rossum
I 102 Doing Python Micro Releases Baxter, Warsaw, van Rossum
IF 160 Python 1.6 Release Schedule Drake
IF 200 Python 2.0 Release Schedule Hylton
SF 201 Lockstep Iteration Warsaw
SF 202 List Comprehensions Warsaw
SF 203 Augmented Assignments Wouters
SR 204 Range Literals Wouters
S 205 Weak References Drake
I 206 2.0 Batteries Included Zadka
SF 207 Rich Comparisons van Rossum, Ascher
SF 208 Reworking the Coercion Model Schemenauer, Lemburg
S 209 Adding Multidimensional Arrays Barrett, Oliphant
SD 210 Decoupling the Interpreter Loop Ascher
SD 211 Adding A New Outer Product Operator Wilson
SD 212 Loop Counter Iteration Schneider-Kamp
SD 213 Attribute Access Handlers Prescod
SF 214 Extended Print Statement Warsaw
SD 215 String Interpolation Yee
IR 216 Docstring Format Zadka
SF 217 Display Hook for Interactive Use Zadka
S 218 Adding a Built-In Set Object Type Wilson
SD 219 Stackless Python McMillan
ID 220 Coroutines, Generators, Continuations McMillan
SF 221 Import As Wouters
SD 222 Web Library Enhancements Kuchling
SF 223 Change the Meaning of \x Escapes Peters
SR 224 Attribute Docstrings Lemburg
SD 225 Elementwise/Objectwise Operators Zhu, Lielens
I 226 Python 2.1 Release Schedule Hylton
S 227 Statically Nested Scopes Hylton
S 228 Reworking Python's Numeric Model Zadka, van Rossum
SF 229 Using Distutils to Build Python Kuchling
SF 230 Warning Framework van Rossum
SR 231 __findattr__() Warsaw
SF 232 Function Attributes Warsaw
SD 233 Python Online Help Prescod
SF 234 Iterators Yee, van Rossum
SF 235 Import on Case-Insensitive Platforms Peters
SF 236 Back to the __future__ Peters
S 237 Unifying Long Integers and Integers Zadka, van Rossum
SF 238 Changing the Division Operator Zadka, van Rossum
S 239 Adding a Rational Type to Python Zadka
S 240 Adding a Rational Literal to Python Zadka
SF 241 Metadata for Python Software Packages Kuchling
S 242 Numeric Kinds Dubois
S 243 Module Repository Upload Mechanism Reifschneider
SR 244 The `directive' Statement von Loewis
S 245 Python Interface Syntax Pelletier
S 246 Object Adaptation Evans
IF 247 API for Cryptographic Hash Functions Kuchling
IF 248 Python Database API Specification v1.0 Lemburg
IF 249 Python Database API Specification v2.0 Lemburg
SF 250 Using site-packages on Windows Moore
IF 251 Python 2.2 Release Schedule Warsaw, van Rossum
S 252 Making Types Look More Like Classes van Rossum
S 253 Subtyping Built-in Types van Rossum
S 254 Making Classes Look More Like Types van Rossum
SF 255 Simple Generators Schemenauer, et al
S 256 Docstring Processing System Framework Goodger
I 257 Docstring Conventions Goodger, van Rossum
S 258 Docutils Design Specification Goodger
SR 259 Omit printing newline after newline van Rossum
SF 260 Simplify xrange() van Rossum
S 261 Support for "wide" Unicode characters Prescod
S 262 Database of Installed Python Packages Kuchling
SF 263 Defining Python Source Code Encodings Lemburg
SF 264 Future statements in simulated shells Hudson
S 265 Sorting Dictionaries by Value Griffin
S 266 Optimizing Global Variable/Attribute Access Montanaro
S 267 Optimized Access to Module Namespaces Hylton
S 268 Extended HTTP functionality and WebDAV Stein
S 269 Pgen Module for Python Riehl
S 270 uniq method for list objects Petrone
SR 271 Prefixing sys.path by command line option Giacometti
IF 272 API for Block Encryption Algorithms v1.0 Kuchling
S 273 Import Modules from Zip Archives Ahlstrom
S 274 Dict Comprehensions Warsaw
S 275 Switching on Multiple Values Lemburg
S 276 Simple Iterator for ints Althoff
S 277 Unicode file name support for Windows NT Hodgson
S 278 Universal Newline Support Jansen
SF 279 The enumerate() built-in function Hettinger
S 280 Optimizing access to globals van Rossum
S 281 Loop Counter Iteration with range and xrange Hetland
S 282 A Logging System Sajip, Mick
I 283 Python 2.3 Release Schedule van Rossum
S 284 Integer for-loops Eppstein, Ewing
SF 285 Adding a bool type van Rossum
S 286 Enhanced Argument Tuples von Loewis
I 287 reStructuredText Docstring Format Goodger
SD 288 Generators Attributes and Exceptions Hettinger
SR 289 Generator Comprehensions Hettinger
I 290 Code Migration and Modernization Hettinger
I 291 Backward Compatibility for Standard Library Norwitz
S 292 Simpler String Substitutions Warsaw
SF 293 Codec Error Handling Callbacks Dörwald
S 294 Type Names in the types Module Tirosh
SR 295 Interpretation of multiline string constants Koltsov
S 296 Adding a bytes Object Type Gilbert
S 297 Support for System Upgrades Lemburg
S 298 The Locked Buffer Interface Heller
S 299 Special __main__() function in modules Epler
SR 666 Reject Foolish Indentation Creighton
Key
I - Informational PEP
S - Standards Track PEP
A - Accepted proposal
R - Rejected proposal
D - Deferred proposal
F - Final proposal
Owners
name email address
---------------- -------------
Aahz aahz at pobox.com
Ahlstrom, James C. jim at interet.com
Althoff, Jim james_althoff at i2.com
Ascher, David davida at activestate.com
Barrett, Paul barrett at stsci.edu
Baxter, Anthony anthony at interlink.com.au
Creighton, Laura lac at strakt.com
Dörwald, Walter
Drake, Fred fdrake at acm.org
Dubois, Paul F. paul at pfdubois.com
Epler, Jeff jepler at unpythonic.net
Eppstein, David eppstein at ics.uci.edu
Evans, Clark C. cce at clarkevans.com
Ewing, Greg greg at cosc.canterbury.ac.nz
Faassen, Martijn faassen at infrae.com
Giacometti, Frédéric B. fred at arakne.com
Gilbert, Scott xscottg at yahoo.com
Goodger, David goodger at users.sourceforge.net
Griffin, Grant g2 at iowegian.com
Heller, Thomas theller at python.net
Hetland, Magnus Lie magnus at hetland.org
Hettinger, Raymond D. python at rcn.com
Hodgson, Neil neilh at scintilla.org
Hudson, Michael mwh at python.net
Hylton, Jeremy jeremy at zope.com
Jansen, Jack jack at cwi.nl
Koltsov, Stepan yozh at mx1.ru
Kuchling, Andrew akuchlin at mems-exchange.org
Lemburg, Marc-Andre mal at lemburg.com
Lielens, Gregory gregory.lielens at fft.be
von Loewis, Martin loewis at informatik.hu-berlin.de
Martelli, Alex aleax at aleax.it
McMillan, Gordon gmcm at hypernet.com
Mick, Trent trentm at activestate.com
Montanaro, Skip skip at pobox.com
Moore, Paul gustav at morpheus.demon.co.uk
Norwitz, Neal neal at metaslash.com
Oliphant, Travis oliphant at ee.byu.edu
Pelletier, Michel michel at digicool.com
Peters, Tim tim at digicool.com
Petrone, Jason jp at demonseed.net
Prescod, Paul paul at prescod.net
Reifschneider, Sean jafo-pep at tummy.com
Riehl, Jonathan jriehl at spaceship.com
van Rossum, Guido guido at python.org
Sajip, Vinay vinay_sajip at red-dove.com
Schemenauer, Neil nas at arctrix.com
Schneider-Kamp, Peter nowonder at nowonder.de
Stein, Greg gstein at lyra.org
Tirosh, Oren oren at hishome.net
Warsaw, Barry barry at zope.com
Wilson, Greg gvwilson at ddj.com
Wouters, Thomas thomas at xs4all.net
Yee, Ka-Ping ping at lfw.org
Zadka, Moshe moshez at zadka.site.co.il
Zhu, Huaiyu hzhu at users.sourceforge.net
References
[1] View PEP history online
http://cvs.sf.net/cgi-bin/viewcvs.cgi/python/python/nondist/peps/
[2] The Benevolent Dictator For Life's Parade of PEPs
http://www.python.org/doc/essays/pepparade.html
Local Variables:
mode: indented-text
indent-tabs-mode: nil
sentence-end-double-space: t
fill-column: 70
End:
@Ñh±ÏÙÚÛ®
n¢0àÉDåÜîïµÅyEçÅSâhØ``}[Â[È>&â
QhRU
#$õ«Y³8(KbØ;4ìØ
SAUUY¥Ôt
;aðÃþîPÌøð]
õBÆkªh&b ¥Ôa@§#vJ
hxj«#ªªp«©¨Þ²vÖ!¹ÎÒ®Èj¢§þ&«(¦<Z¥ªÂR ËçW9ëm¹^°+äÒáWek.´hæ.Æà)hæbn&>IDj#ë5°¡ÀV"üx¿*ÕH@}ÃÄt8`±xj|±½àÈ0ÐÝ©hÖ!rµ1r?,Á
T&,M5;iÏà4u¶
y=3ºïÀkÁ«æв&¼S`YôýÒè)öpÃÿ>pú_ªp×!
añZªö1Î~Ì
p'ÏhÈ6Lrf?4Nj0iÄ5 iTj¾6³t
,:
*üÂÀðü-\ Àóø@FöèWcùã¤É
)2¼\_fÖQ_¹&sËüÄ0}@öÐ&upãÌèv7º§§]e0úåtd¥ÑÄ9
Ha´û>qÆLZCôù:gfÚEã¼£ÚÅ\,æÈf&ªÂ
¤±D4ªU×tÊÈ1µ««2
yLué:ä
®jÕ©è¨øt@F
@,[)¨Ï
¸ðxÑ ë
kÀ× Ð5á!8 ÆÄn e£l&T@pm`U"ãZ1N ÒÕ~ÇE9<RN& únK¬
¼ê¨ÖPmúÄùÙ8Ñ¥
Ñjþ W¼XãÕ#
¹;l Ð ¬!¤èwÃk©v¯¹ÀB at x¬·½ë*Cí¶È²ªÃÒÄÎ2ðªýÊhZ?ùÝD+Õ¥ü!3
Á
ÑÀHÈhñ¿Â¬e W(ôÒÔKùg
¦´äÁ<AÒùR
88§-÷M1Xx8pÈxv¦W¨S*7¢ýÑo0ì»_lA9è :só°*kÁJ/£/©W$ù2G#6à÷
àRâ⧯àTZþ áÞáÆÂÕ±* *äLÜõ_¶ñþZÃËYyEJæÃþ¡ÏoY."\ë>à-,mé'áhÌv˯
>v
g(ã EsRéq
R¥^Ý5ztSg°
]6ov8mèPh
ÕP&Ð]³1cÄ4£&üñ>&BÙ)Ù×~ù¦âVreyÓ¢|8]ùjb1 nå&IpϦ(Û︢9gþf%m7`¤¹¬y±ÀÚ?WÙ´Y[Rê`Ôv;o¢iN½ùc½à9dbtó Fy ïS PÉ1)Â
O°Áá
®aJ@æ®
56789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEFS-SPARSE-WITH-NULLS
123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF
--- NEW FILE: tf_inherit_check.py ---
# Helper script for test_tempfile.py. argv[2] is the number of a file
# descriptor which should _not_ be open. Check this by attempting to
# write to it -- if we succeed, something is wrong.
import sys
import os
verbose = (sys.argv[1] == 'v')
try:
fd = int(sys.argv[2])
try:
os.write(fd, "blat")
except os.error:
# Success -- could not write to fd.
sys.exit(0)
else:
if verbose:
sys.stderr.write("fd %d is open in child" % fd)
sys.exit(1)
except StandardError:
if verbose:
raise
sys.exit(1)
--- NEW FILE: tokenize_tests.txt ---
# Tests for the 'tokenize' module.
# Large bits stolen from test_grammar.py.
# Comments
"#"
#'
#"
#\
#
# abc
'''#
#'''
x = 1 #
# Balancing continuation
a = (3, 4,
5, 6)
y = [3, 4,
5]
z = {'a':5,
'b':6}
x = (len(`y`) + 5*x - a[
3 ]
- x + len({
}
)
)
# Backslash means line continuation:
x = 1 \
+ 1
# Backslash does not means continuation in comments :\
x = 0
# Ordinary integers
0xff <> 255
0377 <> 255
2147483647 != 017777777777
-2147483647-1 != 020000000000
037777777777 != -1
0xffffffff != -1
# Long integers
x = 0L
x = 0l
x = 0xffffffffffffffffL
x = 0xffffffffffffffffl
x = 077777777777777777L
x = 077777777777777777l
x = 123456789012345678901234567890L
x = 123456789012345678901234567890l
# Floating-point numbers
x = 3.14
x = 314.
x = 0.314
# XXX x = 000.314
x = .314
x = 3e14
x = 3E14
x = 3e-14
x = 3e+14
x = 3.e14
x = .3e14
x = 3.1e4
# String literals
x = ''; y = "";
x = '\''; y = "'";
x = '"'; y = "\"";
x = "doesn't \"shrink\" does it"
y = 'doesn\'t "shrink" does it'
x = "does \"shrink\" doesn't it"
y = 'does "shrink" doesn\'t it'
x = """
The "quick"
brown fox
jumps over
the 'lazy' dog.
"""
y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
y = '''
The "quick"
brown fox
jumps over
the 'lazy' dog.
''';
y = "\n\
The \"quick\"\n\
brown fox\n\
jumps over\n\
the 'lazy' dog.\n\
";
y = '\n\
The \"quick\"\n\
brown fox\n\
jumps over\n\
the \'lazy\' dog.\n\
';
x = r'\\' + R'\\'
x = r'\'' + ''
y = r'''
foo bar \\
baz''' + R'''
foo'''
y = r"""foo
bar \\ baz
""" + R'''spam
'''
x = u'abc' + U'ABC'
y = u"abc" + U"ABC"
x = ur'abc' + Ur'ABC' + uR'ABC' + UR'ABC'
y = ur"abc" + Ur"ABC" + uR"ABC" + UR"ABC"
x = ur'\\' + UR'\\'
x = ur'\'' + ''
y = ur'''
foo bar \\
baz''' + UR'''
foo'''
y = Ur"""foo
bar \\ baz
""" + uR'''spam
'''
# Indentation
if 1:
x = 2
if 1:
x = 2
if 1:
while 0:
if 0:
x = 2
x = 2
if 0:
if 2:
while 0:
if 1:
x = 2
# Operators
def d22(a, b, c=1, d=2): pass
def d01v(a=1, *restt, **restd): pass
(x, y) <> ({'a':1}, {'b':2})
# comparison
if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
# binary
x = 1 & 1
x = 1 ^ 1
x = 1 | 1
# shift
x = 1 << 1 >> 1
# additive
x = 1 - 1 + 1 - 1 + 1
# multiplicative
x = 1 / 1 * 1 % 1
# unary
x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
x = -1*1/1 + 1*1 - ---1*1
# selector
import sys, time
x = sys.modules['time'].time()
--- NEW FILE: xmltests.py ---
# Convenience test module to run all of the XML-related tests in the
# standard library.
import sys
import test.test_support
test.test_support.verbose = 0
def runtest(name):
__import__(name)
module = sys.modules[name]
if hasattr(module, "test_main"):
module.test_main()
runtest("test.test_minidom")
runtest("test.test_pyexpat")
runtest("test.test_sax")
runtest("test.test_xmllib")
runtest("test.test_xmlrpc")
_______________________________________________
Stackless-checkins mailing list
Stackless-checkins at stackless.com
http://www.stackless.com/mailman/listinfo/stackless-checkins
- Previous message: [Stackless-checkins] CVS: slpdev/src/2.2/src/Lib/test/output test_logging, NONE, 1.1 test_ossaudiodev, NONE, 1.1 test_pep277, NONE, 1.1 test_popen, NONE, 1.1 test_resource, NONE, 1.1 xmltests, NONE, 1.1
- Next message: [Stackless-checkins] CVS: slpdev/src/2.2/src/Lib/xml/dom NodeFilter.py, NONE, 1.1 expatbuilder.py, NONE, 1.1 minicompat.py, NONE, 1.1 xmlbuilder.py, NONE, 1.1
- Messages sorted by:
[ date ]
[ thread ]
[ subject ]
[ author ]
More information about the Stackless-checkins
mailing list