Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1 | # Python test set -- built-in functions |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 2 | |
Mark Dickinson | ad731b9 | 2009-11-09 17:12:30 +0000 | [diff] [blame] | 3 | import platform |
Georg Brandl | 1b37e87 | 2010-03-14 10:45:50 +0000 | [diff] [blame] | 4 | import unittest |
Benjamin Peterson | 076e031 | 2010-08-23 21:58:59 +0000 | [diff] [blame] | 5 | import sys |
| 6 | import warnings |
| 7 | import collections |
| 8 | import io |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 9 | import ast |
Benjamin Peterson | 076e031 | 2010-08-23 21:58:59 +0000 | [diff] [blame] | 10 | import types |
| 11 | import builtins |
| 12 | import random |
Eli Bendersky | 67ebabd | 2011-02-25 10:14:17 +0000 | [diff] [blame] | 13 | from test.support import TESTFN, unlink, run_unittest, check_warnings |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 14 | from operator import neg |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 15 | |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 16 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 17 | class Squares: |
Guido van Rossum | 3bead09 | 1992-01-27 17:00:37 +0000 | [diff] [blame] | 18 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 19 | def __init__(self, max): |
| 20 | self.max = max |
| 21 | self.sofar = [] |
| 22 | |
| 23 | def __len__(self): return len(self.sofar) |
| 24 | |
| 25 | def __getitem__(self, i): |
| 26 | if not 0 <= i < self.max: raise IndexError |
| 27 | n = len(self.sofar) |
| 28 | while n <= i: |
| 29 | self.sofar.append(n*n) |
| 30 | n += 1 |
| 31 | return self.sofar[i] |
| 32 | |
| 33 | class StrSquares: |
| 34 | |
| 35 | def __init__(self, max): |
| 36 | self.max = max |
| 37 | self.sofar = [] |
| 38 | |
| 39 | def __len__(self): |
| 40 | return len(self.sofar) |
| 41 | |
| 42 | def __getitem__(self, i): |
| 43 | if not 0 <= i < self.max: |
| 44 | raise IndexError |
| 45 | n = len(self.sofar) |
| 46 | while n <= i: |
| 47 | self.sofar.append(str(n*n)) |
| 48 | n += 1 |
| 49 | return self.sofar[i] |
| 50 | |
| 51 | class BitBucket: |
| 52 | def write(self, line): |
| 53 | pass |
| 54 | |
Facundo Batista | 2336bdd | 2008-01-19 19:12:01 +0000 | [diff] [blame] | 55 | test_conv_no_sign = [ |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 56 | ('0', 0), |
| 57 | ('1', 1), |
| 58 | ('9', 9), |
| 59 | ('10', 10), |
| 60 | ('99', 99), |
| 61 | ('100', 100), |
| 62 | ('314', 314), |
| 63 | (' 314', 314), |
| 64 | ('314 ', 314), |
| 65 | (' \t\t 314 \t\t ', 314), |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 66 | (repr(sys.maxsize), sys.maxsize), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 67 | (' 1x', ValueError), |
| 68 | (' 1 ', 1), |
| 69 | (' 1\02 ', ValueError), |
| 70 | ('', ValueError), |
| 71 | (' ', ValueError), |
Walter Dörwald | 1f5947b | 2007-05-22 16:52:54 +0000 | [diff] [blame] | 72 | (' \t\t ', ValueError), |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 73 | (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), |
Guido van Rossum | 84fc66d | 2007-05-03 17:18:26 +0000 | [diff] [blame] | 74 | (chr(0x200), ValueError), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 75 | ] |
| 76 | |
Facundo Batista | 2336bdd | 2008-01-19 19:12:01 +0000 | [diff] [blame] | 77 | test_conv_sign = [ |
| 78 | ('0', 0), |
| 79 | ('1', 1), |
| 80 | ('9', 9), |
| 81 | ('10', 10), |
| 82 | ('99', 99), |
| 83 | ('100', 100), |
| 84 | ('314', 314), |
| 85 | (' 314', ValueError), |
| 86 | ('314 ', 314), |
| 87 | (' \t\t 314 \t\t ', ValueError), |
| 88 | (repr(sys.maxsize), sys.maxsize), |
| 89 | (' 1x', ValueError), |
| 90 | (' 1 ', ValueError), |
| 91 | (' 1\02 ', ValueError), |
| 92 | ('', ValueError), |
| 93 | (' ', ValueError), |
| 94 | (' \t\t ', ValueError), |
| 95 | (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), |
| 96 | (chr(0x200), ValueError), |
| 97 | ] |
| 98 | |
Raymond Hettinger | 96229b1 | 2005-03-11 06:49:40 +0000 | [diff] [blame] | 99 | class TestFailingBool: |
Jack Diederich | 4dafcc4 | 2006-11-28 19:15:13 +0000 | [diff] [blame] | 100 | def __bool__(self): |
Raymond Hettinger | 96229b1 | 2005-03-11 06:49:40 +0000 | [diff] [blame] | 101 | raise RuntimeError |
| 102 | |
| 103 | class TestFailingIter: |
| 104 | def __iter__(self): |
| 105 | raise RuntimeError |
| 106 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 107 | class BuiltinTest(unittest.TestCase): |
| 108 | |
| 109 | def test_import(self): |
| 110 | __import__('sys') |
| 111 | __import__('time') |
| 112 | __import__('string') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 113 | __import__(name='sys') |
| 114 | __import__(name='time', level=0) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 115 | self.assertRaises(ImportError, __import__, 'spamspam') |
| 116 | self.assertRaises(TypeError, __import__, 1, 2, 3, 4) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 117 | self.assertRaises(ValueError, __import__, '') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 118 | self.assertRaises(TypeError, __import__, 'sys', name='sys') |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 119 | |
| 120 | def test_abs(self): |
| 121 | # int |
| 122 | self.assertEqual(abs(0), 0) |
| 123 | self.assertEqual(abs(1234), 1234) |
| 124 | self.assertEqual(abs(-1234), 1234) |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 125 | self.assertTrue(abs(-sys.maxsize-1) > 0) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 126 | # float |
| 127 | self.assertEqual(abs(0.0), 0.0) |
| 128 | self.assertEqual(abs(3.14), 3.14) |
| 129 | self.assertEqual(abs(-3.14), 3.14) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 130 | # str |
| 131 | self.assertRaises(TypeError, abs, 'a') |
Mark Dickinson | fb3dc94 | 2010-05-25 19:06:24 +0000 | [diff] [blame] | 132 | # bool |
| 133 | self.assertEqual(abs(True), 1) |
| 134 | self.assertEqual(abs(False), 0) |
| 135 | # other |
| 136 | self.assertRaises(TypeError, abs) |
| 137 | self.assertRaises(TypeError, abs, None) |
| 138 | class AbsClass(object): |
| 139 | def __abs__(self): |
| 140 | return -5 |
| 141 | self.assertEqual(abs(AbsClass()), -5) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 142 | |
Raymond Hettinger | 96229b1 | 2005-03-11 06:49:40 +0000 | [diff] [blame] | 143 | def test_all(self): |
| 144 | self.assertEqual(all([2, 4, 6]), True) |
| 145 | self.assertEqual(all([2, None, 6]), False) |
| 146 | self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6]) |
| 147 | self.assertRaises(RuntimeError, all, TestFailingIter()) |
| 148 | self.assertRaises(TypeError, all, 10) # Non-iterable |
| 149 | self.assertRaises(TypeError, all) # No args |
| 150 | self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args |
| 151 | self.assertEqual(all([]), True) # Empty iterator |
| 152 | S = [50, 60] |
| 153 | self.assertEqual(all(x > 42 for x in S), True) |
| 154 | S = [50, 40, 60] |
| 155 | self.assertEqual(all(x > 42 for x in S), False) |
| 156 | |
| 157 | def test_any(self): |
| 158 | self.assertEqual(any([None, None, None]), False) |
| 159 | self.assertEqual(any([None, 4, None]), True) |
| 160 | self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6]) |
| 161 | self.assertRaises(RuntimeError, all, TestFailingIter()) |
| 162 | self.assertRaises(TypeError, any, 10) # Non-iterable |
| 163 | self.assertRaises(TypeError, any) # No args |
| 164 | self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args |
| 165 | self.assertEqual(any([]), False) # Empty iterator |
| 166 | S = [40, 60, 30] |
| 167 | self.assertEqual(any(x > 42 for x in S), True) |
| 168 | S = [10, 20, 30] |
| 169 | self.assertEqual(any(x > 42 for x in S), False) |
| 170 | |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 171 | def test_ascii(self): |
| 172 | self.assertEqual(ascii(''), '\'\'') |
| 173 | self.assertEqual(ascii(0), '0') |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 174 | self.assertEqual(ascii(()), '()') |
| 175 | self.assertEqual(ascii([]), '[]') |
| 176 | self.assertEqual(ascii({}), '{}') |
| 177 | a = [] |
| 178 | a.append(a) |
| 179 | self.assertEqual(ascii(a), '[[...]]') |
| 180 | a = {} |
| 181 | a[0] = a |
| 182 | self.assertEqual(ascii(a), '{0: {...}}') |
Antoine Pitrou | e4a1892 | 2010-09-09 20:30:23 +0000 | [diff] [blame] | 183 | # Advanced checks for unicode strings |
| 184 | def _check_uni(s): |
| 185 | self.assertEqual(ascii(s), repr(s)) |
| 186 | _check_uni("'") |
| 187 | _check_uni('"') |
| 188 | _check_uni('"\'') |
| 189 | _check_uni('\0') |
| 190 | _check_uni('\r\n\t .') |
| 191 | # Unprintable non-ASCII characters |
| 192 | _check_uni('\x85') |
| 193 | _check_uni('\u1fff') |
| 194 | _check_uni('\U00012fff') |
| 195 | # Lone surrogates |
| 196 | _check_uni('\ud800') |
| 197 | _check_uni('\udfff') |
| 198 | # Issue #9804: surrogates should be joined even for printable |
| 199 | # wide characters (UCS-2 builds). |
| 200 | self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'") |
| 201 | # All together |
| 202 | s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx." |
| 203 | self.assertEqual(ascii(s), |
| 204 | r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""") |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 205 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 206 | def test_neg(self): |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 207 | x = -sys.maxsize-1 |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 208 | self.assertTrue(isinstance(x, int)) |
Christian Heimes | a37d4c6 | 2007-12-04 23:02:19 +0000 | [diff] [blame] | 209 | self.assertEqual(-x, sys.maxsize+1) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 210 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 211 | def test_callable(self): |
Antoine Pitrou | e71362d | 2010-11-27 22:00:11 +0000 | [diff] [blame] | 212 | self.assertTrue(callable(len)) |
| 213 | self.assertFalse(callable("a")) |
| 214 | self.assertTrue(callable(callable)) |
| 215 | self.assertTrue(callable(lambda x, y: x + y)) |
| 216 | self.assertFalse(callable(__builtins__)) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 217 | def f(): pass |
Antoine Pitrou | e71362d | 2010-11-27 22:00:11 +0000 | [diff] [blame] | 218 | self.assertTrue(callable(f)) |
| 219 | |
| 220 | class C1: |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 221 | def meth(self): pass |
Antoine Pitrou | e71362d | 2010-11-27 22:00:11 +0000 | [diff] [blame] | 222 | self.assertTrue(callable(C1)) |
| 223 | c = C1() |
| 224 | self.assertTrue(callable(c.meth)) |
| 225 | self.assertFalse(callable(c)) |
| 226 | |
| 227 | # __call__ is looked up on the class, not the instance |
| 228 | c.__call__ = None |
| 229 | self.assertFalse(callable(c)) |
| 230 | c.__call__ = lambda self: 0 |
| 231 | self.assertFalse(callable(c)) |
| 232 | del c.__call__ |
| 233 | self.assertFalse(callable(c)) |
| 234 | |
| 235 | class C2(object): |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 236 | def __call__(self): pass |
Antoine Pitrou | e71362d | 2010-11-27 22:00:11 +0000 | [diff] [blame] | 237 | c2 = C2() |
| 238 | self.assertTrue(callable(c2)) |
| 239 | c2.__call__ = None |
| 240 | self.assertTrue(callable(c2)) |
| 241 | class C3(C2): pass |
| 242 | c3 = C3() |
| 243 | self.assertTrue(callable(c3)) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 244 | |
| 245 | def test_chr(self): |
| 246 | self.assertEqual(chr(32), ' ') |
| 247 | self.assertEqual(chr(65), 'A') |
| 248 | self.assertEqual(chr(97), 'a') |
| 249 | self.assertEqual(chr(0xff), '\xff') |
Guido van Rossum | 572dbf8 | 2007-04-27 23:53:51 +0000 | [diff] [blame] | 250 | self.assertRaises(ValueError, chr, 1<<24) |
Guido van Rossum | 8ac004e | 2007-07-15 13:00:05 +0000 | [diff] [blame] | 251 | self.assertEqual(chr(sys.maxunicode), |
| 252 | str(('\\U%08x' % (sys.maxunicode)).encode("ascii"), |
| 253 | 'unicode-escape')) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 254 | self.assertRaises(TypeError, chr) |
Guido van Rossum | 8ac004e | 2007-07-15 13:00:05 +0000 | [diff] [blame] | 255 | self.assertEqual(chr(0x0000FFFF), "\U0000FFFF") |
| 256 | self.assertEqual(chr(0x00010000), "\U00010000") |
| 257 | self.assertEqual(chr(0x00010001), "\U00010001") |
| 258 | self.assertEqual(chr(0x000FFFFE), "\U000FFFFE") |
| 259 | self.assertEqual(chr(0x000FFFFF), "\U000FFFFF") |
| 260 | self.assertEqual(chr(0x00100000), "\U00100000") |
| 261 | self.assertEqual(chr(0x00100001), "\U00100001") |
| 262 | self.assertEqual(chr(0x0010FFFE), "\U0010FFFE") |
| 263 | self.assertEqual(chr(0x0010FFFF), "\U0010FFFF") |
| 264 | self.assertRaises(ValueError, chr, -1) |
| 265 | self.assertRaises(ValueError, chr, 0x00110000) |
Amaury Forgeot d'Arc | 7888d08 | 2008-08-01 01:06:32 +0000 | [diff] [blame] | 266 | self.assertRaises((OverflowError, ValueError), chr, 2**32) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 267 | |
Guido van Rossum | 8ac004e | 2007-07-15 13:00:05 +0000 | [diff] [blame] | 268 | def test_cmp(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 269 | self.assertTrue(not hasattr(builtins, "cmp")) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 270 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 271 | def test_compile(self): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 272 | compile('print(1)\n', '', 'exec') |
Amaury Forgeot d'Arc | af59346 | 2007-11-22 20:53:01 +0000 | [diff] [blame] | 273 | bom = b'\xef\xbb\xbf' |
| 274 | compile(bom + b'print(1)\n', '', 'exec') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 275 | compile(source='pass', filename='?', mode='exec') |
| 276 | compile(dont_inherit=0, filename='tmp', source='0', mode='eval') |
| 277 | compile('pass', '?', dont_inherit=1, mode='exec') |
Benjamin Peterson | 60320cb | 2008-09-26 21:49:22 +0000 | [diff] [blame] | 278 | compile(memoryview(b"text"), "name", "exec") |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 279 | self.assertRaises(TypeError, compile) |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 280 | self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode') |
| 281 | self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff) |
Neal Norwitz | fcf4435 | 2005-11-27 20:37:43 +0000 | [diff] [blame] | 282 | self.assertRaises(TypeError, compile, chr(0), 'f', 'exec') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 283 | self.assertRaises(TypeError, compile, 'pass', '?', 'exec', |
| 284 | mode='eval', source='0', filename='tmp') |
Walter Dörwald | 1f5947b | 2007-05-22 16:52:54 +0000 | [diff] [blame] | 285 | compile('print("\xe5")\n', '', 'exec') |
| 286 | self.assertRaises(TypeError, compile, chr(0), 'f', 'exec') |
| 287 | self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 288 | |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 289 | # test the optimize argument |
| 290 | |
| 291 | codestr = '''def f(): |
| 292 | """doc""" |
| 293 | try: |
| 294 | assert False |
| 295 | except AssertionError: |
| 296 | return (True, f.__doc__) |
| 297 | else: |
| 298 | return (False, f.__doc__) |
| 299 | ''' |
| 300 | def f(): """doc""" |
| 301 | values = [(-1, __debug__, f.__doc__), |
| 302 | (0, True, 'doc'), |
| 303 | (1, False, 'doc'), |
| 304 | (2, False, None)] |
| 305 | for optval, debugval, docstring in values: |
| 306 | # test both direct compilation and compilation via AST |
| 307 | codeobjs = [] |
| 308 | codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval)) |
| 309 | tree = ast.parse(codestr) |
| 310 | codeobjs.append(compile(tree, "<test>", "exec", optimize=optval)) |
| 311 | for code in codeobjs: |
| 312 | ns = {} |
| 313 | exec(code, ns) |
| 314 | rv = ns['f']() |
| 315 | self.assertEqual(rv, (debugval, docstring)) |
| 316 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 317 | def test_delattr(self): |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 318 | sys.spam = 1 |
| 319 | delattr(sys, 'spam') |
| 320 | self.assertRaises(TypeError, delattr) |
| 321 | |
| 322 | def test_dir(self): |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 323 | # dir(wrong number of arguments) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 324 | self.assertRaises(TypeError, dir, 42, 42) |
| 325 | |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 326 | # dir() - local scope |
| 327 | local_var = 1 |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 328 | self.assertIn('local_var', dir()) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 329 | |
| 330 | # dir(module) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 331 | self.assertIn('exit', dir(sys)) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 332 | |
| 333 | # dir(module_with_invalid__dict__) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 334 | class Foo(types.ModuleType): |
| 335 | __dict__ = 8 |
| 336 | f = Foo("foo") |
| 337 | self.assertRaises(TypeError, dir, f) |
| 338 | |
| 339 | # dir(type) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 340 | self.assertIn("strip", dir(str)) |
| 341 | self.assertNotIn("__mro__", dir(str)) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 342 | |
| 343 | # dir(obj) |
| 344 | class Foo(object): |
| 345 | def __init__(self): |
| 346 | self.x = 7 |
| 347 | self.y = 8 |
| 348 | self.z = 9 |
| 349 | f = Foo() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 350 | self.assertIn("y", dir(f)) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 351 | |
| 352 | # dir(obj_no__dict__) |
| 353 | class Foo(object): |
| 354 | __slots__ = [] |
| 355 | f = Foo() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 356 | self.assertIn("__repr__", dir(f)) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 357 | |
| 358 | # dir(obj_no__class__with__dict__) |
| 359 | # (an ugly trick to cause getattr(f, "__class__") to fail) |
| 360 | class Foo(object): |
| 361 | __slots__ = ["__class__", "__dict__"] |
| 362 | def __init__(self): |
| 363 | self.bar = "wow" |
| 364 | f = Foo() |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 365 | self.assertNotIn("__repr__", dir(f)) |
| 366 | self.assertIn("bar", dir(f)) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 367 | |
| 368 | # dir(obj_using __dir__) |
| 369 | class Foo(object): |
| 370 | def __dir__(self): |
| 371 | return ["kan", "ga", "roo"] |
| 372 | f = Foo() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 373 | self.assertTrue(dir(f) == ["ga", "kan", "roo"]) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 374 | |
Benjamin Peterson | 3bbb722 | 2011-06-11 16:12:08 -0500 | [diff] [blame] | 375 | # dir(obj__dir__tuple) |
| 376 | class Foo(object): |
| 377 | def __dir__(self): |
| 378 | return ("b", "c", "a") |
| 379 | res = dir(Foo()) |
| 380 | self.assertIsInstance(res, list) |
| 381 | self.assertTrue(res == ["a", "b", "c"]) |
| 382 | |
| 383 | # dir(obj__dir__not_sequence) |
Georg Brandl | e32b422 | 2007-03-10 22:13:27 +0000 | [diff] [blame] | 384 | class Foo(object): |
| 385 | def __dir__(self): |
| 386 | return 7 |
| 387 | f = Foo() |
| 388 | self.assertRaises(TypeError, dir, f) |
| 389 | |
Collin Winter | 3eed765 | 2007-08-14 17:53:54 +0000 | [diff] [blame] | 390 | # dir(traceback) |
| 391 | try: |
| 392 | raise IndexError |
| 393 | except: |
| 394 | self.assertEqual(len(dir(sys.exc_info()[2])), 4) |
| 395 | |
Benjamin Peterson | dac9ace | 2011-05-25 09:33:37 -0500 | [diff] [blame] | 396 | # test that object has a __dir__() |
| 397 | self.assertEqual(sorted([].__dir__()), dir([])) |
Collin Winter | 3eed765 | 2007-08-14 17:53:54 +0000 | [diff] [blame] | 398 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 399 | def test_divmod(self): |
| 400 | self.assertEqual(divmod(12, 7), (1, 5)) |
| 401 | self.assertEqual(divmod(-12, 7), (-2, 2)) |
| 402 | self.assertEqual(divmod(12, -7), (-2, -2)) |
| 403 | self.assertEqual(divmod(-12, -7), (1, -5)) |
| 404 | |
Mark Dickinson | 5c2db37 | 2009-12-05 20:28:34 +0000 | [diff] [blame] | 405 | self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0)) |
Raymond Hettinger | 5ea7e31 | 2004-09-30 07:47:20 +0000 | [diff] [blame] | 406 | |
Eli Bendersky | 67ebabd | 2011-02-25 10:14:17 +0000 | [diff] [blame] | 407 | for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)), |
| 408 | (-3.25, 1.0, (-4.0, 0.75)), |
| 409 | (3.25, -1.0, (-4.0, -0.75)), |
| 410 | (-3.25, -1.0, (3.0, -0.25))]: |
| 411 | result = divmod(num, denom) |
| 412 | self.assertAlmostEqual(result[0], exp_result[0]) |
| 413 | self.assertAlmostEqual(result[1], exp_result[1]) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 414 | |
| 415 | self.assertRaises(TypeError, divmod) |
| 416 | |
| 417 | def test_eval(self): |
| 418 | self.assertEqual(eval('1+1'), 2) |
| 419 | self.assertEqual(eval(' 1+1\n'), 2) |
| 420 | globals = {'a': 1, 'b': 2} |
| 421 | locals = {'b': 200, 'c': 300} |
| 422 | self.assertEqual(eval('a', globals) , 1) |
| 423 | self.assertEqual(eval('a', globals, locals), 1) |
| 424 | self.assertEqual(eval('b', globals, locals), 200) |
| 425 | self.assertEqual(eval('c', globals, locals), 300) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 426 | globals = {'a': 1, 'b': 2} |
| 427 | locals = {'b': 200, 'c': 300} |
Amaury Forgeot d'Arc | af59346 | 2007-11-22 20:53:01 +0000 | [diff] [blame] | 428 | bom = b'\xef\xbb\xbf' |
| 429 | self.assertEqual(eval(bom + b'a', globals, locals), 1) |
Walter Dörwald | 1f5947b | 2007-05-22 16:52:54 +0000 | [diff] [blame] | 430 | self.assertEqual(eval('"\xe5"', globals), "\xe5") |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 431 | self.assertRaises(TypeError, eval) |
| 432 | self.assertRaises(TypeError, eval, ()) |
Amaury Forgeot d'Arc | af59346 | 2007-11-22 20:53:01 +0000 | [diff] [blame] | 433 | self.assertRaises(SyntaxError, eval, bom[:2] + b'a') |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 434 | |
Raymond Hettinger | 214b1c3 | 2004-07-02 06:41:07 +0000 | [diff] [blame] | 435 | def test_general_eval(self): |
| 436 | # Tests that general mappings can be used for the locals argument |
| 437 | |
| 438 | class M: |
| 439 | "Test mapping interface versus possible calls from eval()." |
| 440 | def __getitem__(self, key): |
| 441 | if key == 'a': |
| 442 | return 12 |
| 443 | raise KeyError |
Guido van Rossum | cd70eee | 2007-02-11 18:53:00 +0000 | [diff] [blame] | 444 | def keys(self): |
| 445 | return list('xyz') |
Raymond Hettinger | 214b1c3 | 2004-07-02 06:41:07 +0000 | [diff] [blame] | 446 | |
| 447 | m = M() |
| 448 | g = globals() |
| 449 | self.assertEqual(eval('a', g, m), 12) |
| 450 | self.assertRaises(NameError, eval, 'b', g, m) |
| 451 | self.assertEqual(eval('dir()', g, m), list('xyz')) |
| 452 | self.assertEqual(eval('globals()', g, m), g) |
| 453 | self.assertEqual(eval('locals()', g, m), m) |
Raymond Hettinger | 513ffe8 | 2004-07-06 13:44:41 +0000 | [diff] [blame] | 454 | self.assertRaises(TypeError, eval, 'a', m) |
Raymond Hettinger | 66bd233 | 2004-08-02 08:30:07 +0000 | [diff] [blame] | 455 | class A: |
| 456 | "Non-mapping" |
| 457 | pass |
| 458 | m = A() |
| 459 | self.assertRaises(TypeError, eval, 'a', g, m) |
Raymond Hettinger | 214b1c3 | 2004-07-02 06:41:07 +0000 | [diff] [blame] | 460 | |
| 461 | # Verify that dict subclasses work as well |
| 462 | class D(dict): |
| 463 | def __getitem__(self, key): |
| 464 | if key == 'a': |
| 465 | return 12 |
| 466 | return dict.__getitem__(self, key) |
Guido van Rossum | cd70eee | 2007-02-11 18:53:00 +0000 | [diff] [blame] | 467 | def keys(self): |
| 468 | return list('xyz') |
Raymond Hettinger | 214b1c3 | 2004-07-02 06:41:07 +0000 | [diff] [blame] | 469 | |
| 470 | d = D() |
| 471 | self.assertEqual(eval('a', g, d), 12) |
| 472 | self.assertRaises(NameError, eval, 'b', g, d) |
| 473 | self.assertEqual(eval('dir()', g, d), list('xyz')) |
| 474 | self.assertEqual(eval('globals()', g, d), g) |
| 475 | self.assertEqual(eval('locals()', g, d), d) |
| 476 | |
| 477 | # Verify locals stores (used by list comps) |
| 478 | eval('[locals() for i in (2,3)]', g, d) |
Raymond Hettinger | f80680d | 2008-02-06 00:07:11 +0000 | [diff] [blame] | 479 | eval('[locals() for i in (2,3)]', g, collections.UserDict()) |
Raymond Hettinger | 214b1c3 | 2004-07-02 06:41:07 +0000 | [diff] [blame] | 480 | |
| 481 | class SpreadSheet: |
| 482 | "Sample application showing nested, calculated lookups." |
| 483 | _cells = {} |
| 484 | def __setitem__(self, key, formula): |
| 485 | self._cells[key] = formula |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 486 | def __getitem__(self, key): |
Raymond Hettinger | 214b1c3 | 2004-07-02 06:41:07 +0000 | [diff] [blame] | 487 | return eval(self._cells[key], globals(), self) |
| 488 | |
| 489 | ss = SpreadSheet() |
| 490 | ss['a1'] = '5' |
| 491 | ss['a2'] = 'a1*6' |
| 492 | ss['a3'] = 'a2*7' |
| 493 | self.assertEqual(ss['a3'], 210) |
| 494 | |
Raymond Hettinger | 2a7dede | 2004-08-07 04:55:30 +0000 | [diff] [blame] | 495 | # Verify that dir() catches a non-list returned by eval |
| 496 | # SF bug #1004669 |
| 497 | class C: |
| 498 | def __getitem__(self, item): |
| 499 | raise KeyError(item) |
Guido van Rossum | cd70eee | 2007-02-11 18:53:00 +0000 | [diff] [blame] | 500 | def keys(self): |
| 501 | return 1 # used to be 'a' but that's no longer an error |
Raymond Hettinger | 2a7dede | 2004-08-07 04:55:30 +0000 | [diff] [blame] | 502 | self.assertRaises(TypeError, eval, 'dir()', globals(), C()) |
| 503 | |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 504 | def test_exec(self): |
| 505 | g = {} |
| 506 | exec('z = 1', g) |
| 507 | if '__builtins__' in g: |
| 508 | del g['__builtins__'] |
| 509 | self.assertEqual(g, {'z': 1}) |
| 510 | |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 511 | exec('z = 1+1', g) |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 512 | if '__builtins__' in g: |
| 513 | del g['__builtins__'] |
| 514 | self.assertEqual(g, {'z': 2}) |
| 515 | g = {} |
| 516 | l = {} |
| 517 | |
Brett Cannon | 7762899 | 2010-03-20 20:59:33 +0000 | [diff] [blame] | 518 | with check_warnings(): |
| 519 | warnings.filterwarnings("ignore", "global statement", |
| 520 | module="<string>") |
| 521 | exec('global a; a = 1; b = 2', g, l) |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 522 | if '__builtins__' in g: |
| 523 | del g['__builtins__'] |
| 524 | if '__builtins__' in l: |
| 525 | del l['__builtins__'] |
| 526 | self.assertEqual((g, l), ({'a': 1}, {'b': 2})) |
| 527 | |
Amaury Forgeot d'Arc | 9ed7735 | 2008-04-04 23:25:27 +0000 | [diff] [blame] | 528 | def test_exec_redirected(self): |
| 529 | savestdout = sys.stdout |
| 530 | sys.stdout = None # Whatever that cannot flush() |
| 531 | try: |
| 532 | # Used to raise SystemError('error return without exception set') |
| 533 | exec('a') |
| 534 | except NameError: |
| 535 | pass |
| 536 | finally: |
| 537 | sys.stdout = savestdout |
| 538 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 539 | def test_filter(self): |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 540 | self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) |
| 541 | self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) |
| 542 | self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) |
| 543 | self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81]) |
| 544 | self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81]) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 545 | def identity(item): |
| 546 | return 1 |
| 547 | filter(identity, Squares(5)) |
| 548 | self.assertRaises(TypeError, filter) |
| 549 | class BadSeq(object): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 550 | def __getitem__(self, index): |
| 551 | if index<4: |
| 552 | return 42 |
| 553 | raise ValueError |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 554 | self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq())) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 555 | def badfunc(): |
| 556 | pass |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 557 | self.assertRaises(TypeError, list, filter(badfunc, range(5))) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 558 | |
Walter Dörwald | bf51707 | 2003-01-27 15:57:14 +0000 | [diff] [blame] | 559 | # test bltinmodule.c::filtertuple() |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 560 | self.assertEqual(list(filter(None, (1, 2))), [1, 2]) |
| 561 | self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) |
| 562 | self.assertRaises(TypeError, list, filter(42, (1, 2))) |
Walter Dörwald | c3da83f | 2003-02-04 20:24:45 +0000 | [diff] [blame] | 563 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 564 | def test_getattr(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 565 | self.assertTrue(getattr(sys, 'stdout') is sys.stdout) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 566 | self.assertRaises(TypeError, getattr, sys, 1) |
| 567 | self.assertRaises(TypeError, getattr, sys, 1, "foo") |
| 568 | self.assertRaises(TypeError, getattr) |
Guido van Rossum | f15a29f | 2007-05-04 00:41:39 +0000 | [diff] [blame] | 569 | self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode)) |
Victor Stinner | 624dbf6 | 2010-03-12 17:17:58 +0000 | [diff] [blame] | 570 | # unicode surrogates are not encodable to the default encoding (utf8) |
| 571 | self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E") |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 572 | |
| 573 | def test_hasattr(self): |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 574 | self.assertTrue(hasattr(sys, 'stdout')) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 575 | self.assertRaises(TypeError, hasattr, sys, 1) |
| 576 | self.assertRaises(TypeError, hasattr) |
Guido van Rossum | f15a29f | 2007-05-04 00:41:39 +0000 | [diff] [blame] | 577 | self.assertEqual(False, hasattr(sys, chr(sys.maxunicode))) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 578 | |
Benjamin Peterson | 1768999 | 2010-08-24 03:26:23 +0000 | [diff] [blame] | 579 | # Check that hasattr propagates all exceptions outside of |
| 580 | # AttributeError. |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 581 | class A: |
| 582 | def __getattr__(self, what): |
Benjamin Peterson | 1768999 | 2010-08-24 03:26:23 +0000 | [diff] [blame] | 583 | raise SystemExit |
| 584 | self.assertRaises(SystemExit, hasattr, A(), "b") |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 585 | class B: |
| 586 | def __getattr__(self, what): |
Benjamin Peterson | 1768999 | 2010-08-24 03:26:23 +0000 | [diff] [blame] | 587 | raise ValueError |
| 588 | self.assertRaises(ValueError, hasattr, B(), "b") |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 589 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 590 | def test_hash(self): |
| 591 | hash(None) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 592 | self.assertEqual(hash(1), hash(1)) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 593 | self.assertEqual(hash(1), hash(1.0)) |
| 594 | hash('spam') |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 595 | self.assertEqual(hash('spam'), hash(b'spam')) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 596 | hash((0,1,2,3)) |
| 597 | def f(): pass |
| 598 | self.assertRaises(TypeError, hash, []) |
| 599 | self.assertRaises(TypeError, hash, {}) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 600 | # Bug 1536021: Allow hash to return long objects |
| 601 | class X: |
| 602 | def __hash__(self): |
| 603 | return 2**100 |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 604 | self.assertEqual(type(hash(X())), int) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 605 | class Z(int): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 606 | def __hash__(self): |
| 607 | return self |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 608 | self.assertEqual(hash(Z(42)), hash(42)) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 609 | |
| 610 | def test_hex(self): |
| 611 | self.assertEqual(hex(16), '0x10') |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 612 | self.assertEqual(hex(-16), '-0x10') |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 613 | self.assertRaises(TypeError, hex, {}) |
| 614 | |
| 615 | def test_id(self): |
| 616 | id(None) |
| 617 | id(1) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 618 | id(1.0) |
| 619 | id('spam') |
| 620 | id((0,1,2,3)) |
| 621 | id([0,1,2,3]) |
| 622 | id({'spam': 1, 'eggs': 2, 'ham': 3}) |
| 623 | |
Guido van Rossum | a88a033 | 2007-02-26 16:59:55 +0000 | [diff] [blame] | 624 | # Test input() later, alphabetized as if it were raw_input |
| 625 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 626 | def test_iter(self): |
| 627 | self.assertRaises(TypeError, iter) |
| 628 | self.assertRaises(TypeError, iter, 42, 42) |
| 629 | lists = [("1", "2"), ["1", "2"], "12"] |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 630 | for l in lists: |
| 631 | i = iter(l) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 632 | self.assertEqual(next(i), '1') |
| 633 | self.assertEqual(next(i), '2') |
| 634 | self.assertRaises(StopIteration, next, i) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 635 | |
| 636 | def test_isinstance(self): |
| 637 | class C: |
| 638 | pass |
| 639 | class D(C): |
| 640 | pass |
| 641 | class E: |
| 642 | pass |
| 643 | c = C() |
| 644 | d = D() |
| 645 | e = E() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 646 | self.assertTrue(isinstance(c, C)) |
| 647 | self.assertTrue(isinstance(d, C)) |
| 648 | self.assertTrue(not isinstance(e, C)) |
| 649 | self.assertTrue(not isinstance(c, D)) |
| 650 | self.assertTrue(not isinstance('foo', E)) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 651 | self.assertRaises(TypeError, isinstance, E, 'foo') |
| 652 | self.assertRaises(TypeError, isinstance) |
| 653 | |
| 654 | def test_issubclass(self): |
| 655 | class C: |
| 656 | pass |
| 657 | class D(C): |
| 658 | pass |
| 659 | class E: |
| 660 | pass |
| 661 | c = C() |
| 662 | d = D() |
| 663 | e = E() |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 664 | self.assertTrue(issubclass(D, C)) |
| 665 | self.assertTrue(issubclass(C, C)) |
| 666 | self.assertTrue(not issubclass(C, D)) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 667 | self.assertRaises(TypeError, issubclass, 'foo', E) |
| 668 | self.assertRaises(TypeError, issubclass, E, 'foo') |
| 669 | self.assertRaises(TypeError, issubclass) |
| 670 | |
| 671 | def test_len(self): |
| 672 | self.assertEqual(len('123'), 3) |
| 673 | self.assertEqual(len(()), 0) |
| 674 | self.assertEqual(len((1, 2, 3, 4)), 4) |
| 675 | self.assertEqual(len([1, 2, 3, 4]), 4) |
| 676 | self.assertEqual(len({}), 0) |
| 677 | self.assertEqual(len({'a':1, 'b': 2}), 2) |
| 678 | class BadSeq: |
| 679 | def __len__(self): |
| 680 | raise ValueError |
| 681 | self.assertRaises(ValueError, len, BadSeq()) |
Benjamin Peterson | ee1ae7c | 2009-02-08 21:07:20 +0000 | [diff] [blame] | 682 | class InvalidLen: |
| 683 | def __len__(self): |
| 684 | return None |
| 685 | self.assertRaises(TypeError, len, InvalidLen()) |
| 686 | class FloatLen: |
| 687 | def __len__(self): |
| 688 | return 4.5 |
| 689 | self.assertRaises(TypeError, len, FloatLen()) |
| 690 | class HugeLen: |
| 691 | def __len__(self): |
| 692 | return sys.maxsize + 1 |
| 693 | self.assertRaises(OverflowError, len, HugeLen()) |
Mark Dickinson | fb3dc94 | 2010-05-25 19:06:24 +0000 | [diff] [blame] | 694 | class NoLenMethod(object): pass |
| 695 | self.assertRaises(TypeError, len, NoLenMethod()) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 696 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 697 | def test_map(self): |
| 698 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 699 | list(map(lambda x: x*x, range(1,4))), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 700 | [1, 4, 9] |
| 701 | ) |
| 702 | try: |
| 703 | from math import sqrt |
| 704 | except ImportError: |
| 705 | def sqrt(x): |
| 706 | return pow(x, 0.5) |
| 707 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 708 | list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 709 | [[4.0, 2.0], [9.0, 3.0]] |
| 710 | ) |
| 711 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 712 | list(map(lambda x, y: x+y, [1,3,2], [9,1,4])), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 713 | [10, 4, 6] |
| 714 | ) |
| 715 | |
| 716 | def plus(*v): |
| 717 | accu = 0 |
| 718 | for i in v: accu = accu + i |
| 719 | return accu |
| 720 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 721 | list(map(plus, [1, 3, 7])), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 722 | [1, 3, 7] |
| 723 | ) |
| 724 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 725 | list(map(plus, [1, 3, 7], [4, 9, 2])), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 726 | [1+4, 3+9, 7+2] |
| 727 | ) |
| 728 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 729 | list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 730 | [1+4+1, 3+9+1, 7+2+0] |
| 731 | ) |
| 732 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 733 | list(map(int, Squares(10))), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 734 | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
| 735 | ) |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 736 | def Max(a, b): |
| 737 | if a is None: |
| 738 | return b |
| 739 | if b is None: |
| 740 | return a |
| 741 | return max(a, b) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 742 | self.assertEqual( |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 743 | list(map(Max, Squares(3), Squares(2))), |
| 744 | [0, 1] |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 745 | ) |
| 746 | self.assertRaises(TypeError, map) |
| 747 | self.assertRaises(TypeError, map, lambda x: x, 42) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 748 | class BadSeq: |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 749 | def __iter__(self): |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 750 | raise ValueError |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 751 | yield None |
| 752 | self.assertRaises(ValueError, list, map(lambda x: x, BadSeq())) |
Neal Norwitz | fcf4435 | 2005-11-27 20:37:43 +0000 | [diff] [blame] | 753 | def badfunc(x): |
| 754 | raise RuntimeError |
Guido van Rossum | c1f779c | 2007-07-03 08:25:58 +0000 | [diff] [blame] | 755 | self.assertRaises(RuntimeError, list, map(badfunc, range(5))) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 756 | |
| 757 | def test_max(self): |
| 758 | self.assertEqual(max('123123'), '3') |
| 759 | self.assertEqual(max(1, 2, 3), 3) |
| 760 | self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) |
| 761 | self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) |
| 762 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 763 | self.assertEqual(max(1, 2, 3.0), 3.0) |
| 764 | self.assertEqual(max(1, 2.0, 3), 3) |
| 765 | self.assertEqual(max(1.0, 2, 3), 3) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 766 | |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 767 | for stmt in ( |
| 768 | "max(key=int)", # no args |
| 769 | "max(1, key=int)", # single arg not iterable |
| 770 | "max(1, 2, keystone=int)", # wrong keyword |
| 771 | "max(1, 2, key=int, abc=int)", # two many keywords |
| 772 | "max(1, 2, key=1)", # keyfunc is not callable |
| 773 | ): |
Tim Peters | 7f06187 | 2004-12-07 21:17:46 +0000 | [diff] [blame] | 774 | try: |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 775 | exec(stmt, globals()) |
Tim Peters | 7f06187 | 2004-12-07 21:17:46 +0000 | [diff] [blame] | 776 | except TypeError: |
| 777 | pass |
| 778 | else: |
| 779 | self.fail(stmt) |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 780 | |
| 781 | self.assertEqual(max((1,), key=neg), 1) # one elem iterable |
| 782 | self.assertEqual(max((1,2), key=neg), 1) # two elem iterable |
| 783 | self.assertEqual(max(1, 2, key=neg), 1) # two elems |
| 784 | |
| 785 | data = [random.randrange(200) for i in range(100)] |
| 786 | keys = dict((elem, random.randrange(50)) for elem in data) |
| 787 | f = keys.__getitem__ |
| 788 | self.assertEqual(max(data, key=f), |
| 789 | sorted(reversed(data), key=f)[-1]) |
| 790 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 791 | def test_min(self): |
| 792 | self.assertEqual(min('123123'), '1') |
| 793 | self.assertEqual(min(1, 2, 3), 1) |
| 794 | self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) |
| 795 | self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) |
| 796 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 797 | self.assertEqual(min(1, 2, 3.0), 1) |
| 798 | self.assertEqual(min(1, 2.0, 3), 1) |
| 799 | self.assertEqual(min(1.0, 2, 3), 1.0) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 800 | |
| 801 | self.assertRaises(TypeError, min) |
| 802 | self.assertRaises(TypeError, min, 42) |
| 803 | self.assertRaises(ValueError, min, ()) |
| 804 | class BadSeq: |
| 805 | def __getitem__(self, index): |
| 806 | raise ValueError |
| 807 | self.assertRaises(ValueError, min, BadSeq()) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 808 | |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 809 | for stmt in ( |
| 810 | "min(key=int)", # no args |
| 811 | "min(1, key=int)", # single arg not iterable |
| 812 | "min(1, 2, keystone=int)", # wrong keyword |
| 813 | "min(1, 2, key=int, abc=int)", # two many keywords |
| 814 | "min(1, 2, key=1)", # keyfunc is not callable |
| 815 | ): |
Tim Peters | 7f06187 | 2004-12-07 21:17:46 +0000 | [diff] [blame] | 816 | try: |
Georg Brandl | 7cae87c | 2006-09-06 06:51:57 +0000 | [diff] [blame] | 817 | exec(stmt, globals()) |
Tim Peters | 7f06187 | 2004-12-07 21:17:46 +0000 | [diff] [blame] | 818 | except TypeError: |
| 819 | pass |
| 820 | else: |
| 821 | self.fail(stmt) |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 822 | |
| 823 | self.assertEqual(min((1,), key=neg), 1) # one elem iterable |
| 824 | self.assertEqual(min((1,2), key=neg), 2) # two elem iterable |
| 825 | self.assertEqual(min(1, 2, key=neg), 2) # two elems |
| 826 | |
| 827 | data = [random.randrange(200) for i in range(100)] |
| 828 | keys = dict((elem, random.randrange(50)) for elem in data) |
| 829 | f = keys.__getitem__ |
| 830 | self.assertEqual(min(data, key=f), |
| 831 | sorted(data, key=f)[0]) |
| 832 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 833 | def test_next(self): |
| 834 | it = iter(range(2)) |
| 835 | self.assertEqual(next(it), 0) |
| 836 | self.assertEqual(next(it), 1) |
| 837 | self.assertRaises(StopIteration, next, it) |
| 838 | self.assertRaises(StopIteration, next, it) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 839 | self.assertEqual(next(it, 42), 42) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 840 | |
| 841 | class Iter(object): |
| 842 | def __iter__(self): |
| 843 | return self |
| 844 | def __next__(self): |
| 845 | raise StopIteration |
| 846 | |
| 847 | it = iter(Iter()) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 848 | self.assertEqual(next(it, 42), 42) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 849 | self.assertRaises(StopIteration, next, it) |
| 850 | |
| 851 | def gen(): |
| 852 | yield 1 |
| 853 | return |
| 854 | |
| 855 | it = gen() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 856 | self.assertEqual(next(it), 1) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 857 | self.assertRaises(StopIteration, next, it) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 858 | self.assertEqual(next(it, 42), 42) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 859 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 860 | def test_oct(self): |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 861 | self.assertEqual(oct(100), '0o144') |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 862 | self.assertEqual(oct(-100), '-0o144') |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 863 | self.assertRaises(TypeError, oct, ()) |
| 864 | |
| 865 | def write_testfile(self): |
Guido van Rossum | a88a033 | 2007-02-26 16:59:55 +0000 | [diff] [blame] | 866 | # NB the first 4 lines are also used to test input, below |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 867 | fp = open(TESTFN, 'w') |
| 868 | try: |
| 869 | fp.write('1+1\n') |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 870 | fp.write('The quick brown fox jumps over the lazy dog') |
| 871 | fp.write('.\n') |
| 872 | fp.write('Dear John\n') |
| 873 | fp.write('XXX'*100) |
| 874 | fp.write('YYY'*100) |
| 875 | finally: |
| 876 | fp.close() |
| 877 | |
| 878 | def test_open(self): |
| 879 | self.write_testfile() |
| 880 | fp = open(TESTFN, 'r') |
| 881 | try: |
| 882 | self.assertEqual(fp.readline(4), '1+1\n') |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 883 | self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') |
| 884 | self.assertEqual(fp.readline(4), 'Dear') |
| 885 | self.assertEqual(fp.readline(100), ' John\n') |
| 886 | self.assertEqual(fp.read(300), 'XXX'*100) |
| 887 | self.assertEqual(fp.read(1000), 'YYY'*100) |
| 888 | finally: |
| 889 | fp.close() |
| 890 | unlink(TESTFN) |
| 891 | |
| 892 | def test_ord(self): |
| 893 | self.assertEqual(ord(' '), 32) |
| 894 | self.assertEqual(ord('A'), 65) |
| 895 | self.assertEqual(ord('a'), 97) |
Guido van Rossum | f9e91c9 | 2007-05-08 21:05:48 +0000 | [diff] [blame] | 896 | self.assertEqual(ord('\x80'), 128) |
| 897 | self.assertEqual(ord('\xff'), 255) |
| 898 | |
| 899 | self.assertEqual(ord(b' '), 32) |
| 900 | self.assertEqual(ord(b'A'), 65) |
| 901 | self.assertEqual(ord(b'a'), 97) |
| 902 | self.assertEqual(ord(b'\x80'), 128) |
| 903 | self.assertEqual(ord(b'\xff'), 255) |
| 904 | |
Walter Dörwald | 1f5947b | 2007-05-22 16:52:54 +0000 | [diff] [blame] | 905 | self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 906 | self.assertRaises(TypeError, ord, 42) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 907 | |
Guido van Rossum | 8ac004e | 2007-07-15 13:00:05 +0000 | [diff] [blame] | 908 | self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF) |
| 909 | self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF) |
| 910 | self.assertEqual(ord("\U00010000"), 0x00010000) |
| 911 | self.assertEqual(ord("\U00010001"), 0x00010001) |
| 912 | self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE) |
| 913 | self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF) |
| 914 | self.assertEqual(ord("\U00100000"), 0x00100000) |
| 915 | self.assertEqual(ord("\U00100001"), 0x00100001) |
| 916 | self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE) |
| 917 | self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF) |
| 918 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 919 | def test_pow(self): |
| 920 | self.assertEqual(pow(0,0), 1) |
| 921 | self.assertEqual(pow(0,1), 0) |
| 922 | self.assertEqual(pow(1,0), 1) |
| 923 | self.assertEqual(pow(1,1), 1) |
| 924 | |
| 925 | self.assertEqual(pow(2,0), 1) |
| 926 | self.assertEqual(pow(2,10), 1024) |
| 927 | self.assertEqual(pow(2,20), 1024*1024) |
| 928 | self.assertEqual(pow(2,30), 1024*1024*1024) |
| 929 | |
| 930 | self.assertEqual(pow(-2,0), 1) |
| 931 | self.assertEqual(pow(-2,1), -2) |
| 932 | self.assertEqual(pow(-2,2), 4) |
| 933 | self.assertEqual(pow(-2,3), -8) |
| 934 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 935 | self.assertAlmostEqual(pow(0.,0), 1.) |
| 936 | self.assertAlmostEqual(pow(0.,1), 0.) |
| 937 | self.assertAlmostEqual(pow(1.,0), 1.) |
| 938 | self.assertAlmostEqual(pow(1.,1), 1.) |
| 939 | |
| 940 | self.assertAlmostEqual(pow(2.,0), 1.) |
| 941 | self.assertAlmostEqual(pow(2.,10), 1024.) |
| 942 | self.assertAlmostEqual(pow(2.,20), 1024.*1024.) |
| 943 | self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) |
| 944 | |
| 945 | self.assertAlmostEqual(pow(-2.,0), 1.) |
| 946 | self.assertAlmostEqual(pow(-2.,1), -2.) |
| 947 | self.assertAlmostEqual(pow(-2.,2), 4.) |
| 948 | self.assertAlmostEqual(pow(-2.,3), -8.) |
| 949 | |
Mark Dickinson | 5c2db37 | 2009-12-05 20:28:34 +0000 | [diff] [blame] | 950 | for x in 2, 2.0: |
| 951 | for y in 10, 10.0: |
| 952 | for z in 1000, 1000.0: |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 953 | if isinstance(x, float) or \ |
| 954 | isinstance(y, float) or \ |
| 955 | isinstance(z, float): |
| 956 | self.assertRaises(TypeError, pow, x, y, z) |
| 957 | else: |
| 958 | self.assertAlmostEqual(pow(x, y, z), 24.0) |
| 959 | |
Jeffrey Yasskin | 3404b3c | 2007-09-07 15:15:49 +0000 | [diff] [blame] | 960 | self.assertAlmostEqual(pow(-1, 0.5), 1j) |
| 961 | self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j) |
| 962 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 963 | self.assertRaises(TypeError, pow, -1, -2, 3) |
| 964 | self.assertRaises(ValueError, pow, 1, 2, 0) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 965 | |
| 966 | self.assertRaises(TypeError, pow) |
| 967 | |
Guido van Rossum | a88a033 | 2007-02-26 16:59:55 +0000 | [diff] [blame] | 968 | def test_input(self): |
| 969 | self.write_testfile() |
| 970 | fp = open(TESTFN, 'r') |
| 971 | savestdin = sys.stdin |
| 972 | savestdout = sys.stdout # Eats the echo |
| 973 | try: |
| 974 | sys.stdin = fp |
| 975 | sys.stdout = BitBucket() |
| 976 | self.assertEqual(input(), "1+1") |
Guido van Rossum | a88a033 | 2007-02-26 16:59:55 +0000 | [diff] [blame] | 977 | self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.') |
| 978 | self.assertEqual(input('testing\n'), 'Dear John') |
| 979 | |
| 980 | # SF 1535165: don't segfault on closed stdin |
| 981 | # sys.stdout must be a regular file for triggering |
| 982 | sys.stdout = savestdout |
| 983 | sys.stdin.close() |
| 984 | self.assertRaises(ValueError, input) |
| 985 | |
| 986 | sys.stdout = BitBucket() |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 987 | sys.stdin = io.StringIO("NULL\0") |
Guido van Rossum | a88a033 | 2007-02-26 16:59:55 +0000 | [diff] [blame] | 988 | self.assertRaises(TypeError, input, 42, 42) |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 989 | sys.stdin = io.StringIO(" 'whitespace'") |
Guido van Rossum | a88a033 | 2007-02-26 16:59:55 +0000 | [diff] [blame] | 990 | self.assertEqual(input(), " 'whitespace'") |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 991 | sys.stdin = io.StringIO() |
Guido van Rossum | a88a033 | 2007-02-26 16:59:55 +0000 | [diff] [blame] | 992 | self.assertRaises(EOFError, input) |
| 993 | |
| 994 | del sys.stdout |
| 995 | self.assertRaises(RuntimeError, input, 'prompt') |
| 996 | del sys.stdin |
| 997 | self.assertRaises(RuntimeError, input, 'prompt') |
| 998 | finally: |
| 999 | sys.stdin = savestdin |
| 1000 | sys.stdout = savestdout |
| 1001 | fp.close() |
| 1002 | unlink(TESTFN) |
| 1003 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1004 | def test_repr(self): |
| 1005 | self.assertEqual(repr(''), '\'\'') |
| 1006 | self.assertEqual(repr(0), '0') |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1007 | self.assertEqual(repr(()), '()') |
| 1008 | self.assertEqual(repr([]), '[]') |
| 1009 | self.assertEqual(repr({}), '{}') |
| 1010 | a = [] |
| 1011 | a.append(a) |
| 1012 | self.assertEqual(repr(a), '[[...]]') |
| 1013 | a = {} |
| 1014 | a[0] = a |
| 1015 | self.assertEqual(repr(a), '{0: {...}}') |
| 1016 | |
| 1017 | def test_round(self): |
| 1018 | self.assertEqual(round(0.0), 0.0) |
Guido van Rossum | 2fa33db | 2007-08-23 22:07:24 +0000 | [diff] [blame] | 1019 | self.assertEqual(type(round(0.0)), int) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1020 | self.assertEqual(round(1.0), 1.0) |
| 1021 | self.assertEqual(round(10.0), 10.0) |
| 1022 | self.assertEqual(round(1000000000.0), 1000000000.0) |
| 1023 | self.assertEqual(round(1e20), 1e20) |
| 1024 | |
| 1025 | self.assertEqual(round(-1.0), -1.0) |
| 1026 | self.assertEqual(round(-10.0), -10.0) |
| 1027 | self.assertEqual(round(-1000000000.0), -1000000000.0) |
| 1028 | self.assertEqual(round(-1e20), -1e20) |
| 1029 | |
| 1030 | self.assertEqual(round(0.1), 0.0) |
| 1031 | self.assertEqual(round(1.1), 1.0) |
| 1032 | self.assertEqual(round(10.1), 10.0) |
| 1033 | self.assertEqual(round(1000000000.1), 1000000000.0) |
| 1034 | |
| 1035 | self.assertEqual(round(-1.1), -1.0) |
| 1036 | self.assertEqual(round(-10.1), -10.0) |
| 1037 | self.assertEqual(round(-1000000000.1), -1000000000.0) |
| 1038 | |
| 1039 | self.assertEqual(round(0.9), 1.0) |
| 1040 | self.assertEqual(round(9.9), 10.0) |
| 1041 | self.assertEqual(round(999999999.9), 1000000000.0) |
| 1042 | |
| 1043 | self.assertEqual(round(-0.9), -1.0) |
| 1044 | self.assertEqual(round(-9.9), -10.0) |
| 1045 | self.assertEqual(round(-999999999.9), -1000000000.0) |
| 1046 | |
| 1047 | self.assertEqual(round(-8.0, -1), -10.0) |
Guido van Rossum | 2fa33db | 2007-08-23 22:07:24 +0000 | [diff] [blame] | 1048 | self.assertEqual(type(round(-8.0, -1)), float) |
| 1049 | |
| 1050 | self.assertEqual(type(round(-8.0, 0)), float) |
| 1051 | self.assertEqual(type(round(-8.0, 1)), float) |
| 1052 | |
| 1053 | # Check even / odd rounding behaviour |
| 1054 | self.assertEqual(round(5.5), 6) |
| 1055 | self.assertEqual(round(6.5), 6) |
| 1056 | self.assertEqual(round(-5.5), -6) |
| 1057 | self.assertEqual(round(-6.5), -6) |
| 1058 | |
| 1059 | # Check behavior on ints |
| 1060 | self.assertEqual(round(0), 0) |
| 1061 | self.assertEqual(round(8), 8) |
| 1062 | self.assertEqual(round(-8), -8) |
| 1063 | self.assertEqual(type(round(0)), int) |
Mark Dickinson | 1124e71 | 2009-01-28 21:25:58 +0000 | [diff] [blame] | 1064 | self.assertEqual(type(round(-8, -1)), int) |
| 1065 | self.assertEqual(type(round(-8, 0)), int) |
| 1066 | self.assertEqual(type(round(-8, 1)), int) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1067 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 1068 | # test new kwargs |
| 1069 | self.assertEqual(round(number=-8.0, ndigits=-1), -10.0) |
| 1070 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1071 | self.assertRaises(TypeError, round) |
| 1072 | |
Alex Martelli | ae211f9 | 2007-08-22 23:21:33 +0000 | [diff] [blame] | 1073 | # test generic rounding delegation for reals |
| 1074 | class TestRound: |
| 1075 | def __round__(self): |
| 1076 | return 23 |
| 1077 | |
| 1078 | class TestNoRound: |
| 1079 | pass |
| 1080 | |
| 1081 | self.assertEqual(round(TestRound()), 23) |
| 1082 | |
| 1083 | self.assertRaises(TypeError, round, 1, 2, 3) |
| 1084 | self.assertRaises(TypeError, round, TestNoRound()) |
| 1085 | |
Guido van Rossum | 2fa33db | 2007-08-23 22:07:24 +0000 | [diff] [blame] | 1086 | t = TestNoRound() |
| 1087 | t.__round__ = lambda *args: args |
| 1088 | self.assertRaises(TypeError, round, t) |
| 1089 | self.assertRaises(TypeError, round, t, 0) |
| 1090 | |
Mark Dickinson | ad731b9 | 2009-11-09 17:12:30 +0000 | [diff] [blame] | 1091 | # Some versions of glibc for alpha have a bug that affects |
| 1092 | # float -> integer rounding (floor, ceil, rint, round) for |
| 1093 | # values in the range [2**52, 2**53). See: |
| 1094 | # |
| 1095 | # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350 |
| 1096 | # |
| 1097 | # We skip this test on Linux/alpha if it would fail. |
| 1098 | linux_alpha = (platform.system().startswith('Linux') and |
| 1099 | platform.machine().startswith('alpha')) |
| 1100 | system_round_bug = round(5e15+1) != 5e15+1 |
| 1101 | @unittest.skipIf(linux_alpha and system_round_bug, |
| 1102 | "test will fail; failure is probably due to a " |
| 1103 | "buggy system round function") |
| 1104 | def test_round_large(self): |
| 1105 | # Issue #1869: integral floats should remain unchanged |
| 1106 | self.assertEqual(round(5e15-1), 5e15-1) |
| 1107 | self.assertEqual(round(5e15), 5e15) |
| 1108 | self.assertEqual(round(5e15+1), 5e15+1) |
| 1109 | self.assertEqual(round(5e15+2), 5e15+2) |
| 1110 | self.assertEqual(round(5e15+3), 5e15+3) |
| 1111 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1112 | def test_setattr(self): |
Tim Peters | f2715e0 | 2003-02-19 02:35:07 +0000 | [diff] [blame] | 1113 | setattr(sys, 'spam', 1) |
| 1114 | self.assertEqual(sys.spam, 1) |
| 1115 | self.assertRaises(TypeError, setattr, sys, 1, 'spam') |
| 1116 | self.assertRaises(TypeError, setattr) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1117 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1118 | |
Alex Martelli | a70b191 | 2003-04-22 08:12:33 +0000 | [diff] [blame] | 1119 | def test_sum(self): |
| 1120 | self.assertEqual(sum([]), 0) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1121 | self.assertEqual(sum(list(range(2,8))), 27) |
| 1122 | self.assertEqual(sum(iter(list(range(2,8)))), 27) |
Alex Martelli | a70b191 | 2003-04-22 08:12:33 +0000 | [diff] [blame] | 1123 | self.assertEqual(sum(Squares(10)), 285) |
| 1124 | self.assertEqual(sum(iter(Squares(10))), 285) |
| 1125 | self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) |
| 1126 | |
| 1127 | self.assertRaises(TypeError, sum) |
| 1128 | self.assertRaises(TypeError, sum, 42) |
| 1129 | self.assertRaises(TypeError, sum, ['a', 'b', 'c']) |
| 1130 | self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '') |
| 1131 | self.assertRaises(TypeError, sum, [[1], [2], [3]]) |
| 1132 | self.assertRaises(TypeError, sum, [{2:3}]) |
| 1133 | self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3}) |
| 1134 | |
| 1135 | class BadSeq: |
| 1136 | def __getitem__(self, index): |
| 1137 | raise ValueError |
| 1138 | self.assertRaises(ValueError, sum, BadSeq()) |
| 1139 | |
Mark Dickinson | 3a22b47 | 2009-10-17 21:48:16 +0000 | [diff] [blame] | 1140 | empty = [] |
| 1141 | sum(([x] for x in range(10)), empty) |
| 1142 | self.assertEqual(empty, []) |
| 1143 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1144 | def test_type(self): |
| 1145 | self.assertEqual(type(''), type('123')) |
| 1146 | self.assertNotEqual(type(''), type(())) |
| 1147 | |
Guido van Rossum | fee7b93 | 2005-01-16 00:21:28 +0000 | [diff] [blame] | 1148 | # We don't want self in vars(), so these are static methods |
| 1149 | |
| 1150 | @staticmethod |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1151 | def get_vars_f0(): |
| 1152 | return vars() |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1153 | |
Guido van Rossum | fee7b93 | 2005-01-16 00:21:28 +0000 | [diff] [blame] | 1154 | @staticmethod |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1155 | def get_vars_f2(): |
| 1156 | BuiltinTest.get_vars_f0() |
| 1157 | a = 1 |
| 1158 | b = 2 |
| 1159 | return vars() |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1160 | |
Mark Dickinson | fb3dc94 | 2010-05-25 19:06:24 +0000 | [diff] [blame] | 1161 | class C_get_vars(object): |
| 1162 | def getDict(self): |
| 1163 | return {'a':2} |
| 1164 | __dict__ = property(fget=getDict) |
| 1165 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1166 | def test_vars(self): |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 1167 | self.assertEqual(set(vars()), set(dir())) |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 1168 | self.assertEqual(set(vars(sys)), set(dir(sys))) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1169 | self.assertEqual(self.get_vars_f0(), {}) |
| 1170 | self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) |
| 1171 | self.assertRaises(TypeError, vars, 42, 42) |
| 1172 | self.assertRaises(TypeError, vars, 42) |
Mark Dickinson | fb3dc94 | 2010-05-25 19:06:24 +0000 | [diff] [blame] | 1173 | self.assertEqual(vars(self.C_get_vars()), {'a':2}) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1174 | |
| 1175 | def test_zip(self): |
| 1176 | a = (1, 2, 3) |
| 1177 | b = (4, 5, 6) |
| 1178 | t = [(1, 4), (2, 5), (3, 6)] |
Guido van Rossum | 801f0d7 | 2006-08-24 19:48:10 +0000 | [diff] [blame] | 1179 | self.assertEqual(list(zip(a, b)), t) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1180 | b = [4, 5, 6] |
Guido van Rossum | 801f0d7 | 2006-08-24 19:48:10 +0000 | [diff] [blame] | 1181 | self.assertEqual(list(zip(a, b)), t) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1182 | b = (4, 5, 6, 7) |
Guido van Rossum | 801f0d7 | 2006-08-24 19:48:10 +0000 | [diff] [blame] | 1183 | self.assertEqual(list(zip(a, b)), t) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1184 | class I: |
| 1185 | def __getitem__(self, i): |
| 1186 | if i < 0 or i > 2: raise IndexError |
| 1187 | return i + 4 |
Guido van Rossum | 801f0d7 | 2006-08-24 19:48:10 +0000 | [diff] [blame] | 1188 | self.assertEqual(list(zip(a, I())), t) |
| 1189 | self.assertEqual(list(zip()), []) |
| 1190 | self.assertEqual(list(zip(*[])), []) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1191 | self.assertRaises(TypeError, zip, None) |
| 1192 | class G: |
| 1193 | pass |
| 1194 | self.assertRaises(TypeError, zip, a, G()) |
Alexander Belopolsky | e29e6bf | 2010-08-16 18:55:46 +0000 | [diff] [blame] | 1195 | self.assertRaises(RuntimeError, zip, a, TestFailingIter()) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1196 | |
| 1197 | # Make sure zip doesn't try to allocate a billion elements for the |
| 1198 | # result list when one of its arguments doesn't say how long it is. |
| 1199 | # A MemoryError is the most likely failure mode. |
| 1200 | class SequenceWithoutALength: |
| 1201 | def __getitem__(self, i): |
| 1202 | if i == 5: |
| 1203 | raise IndexError |
| 1204 | else: |
| 1205 | return i |
| 1206 | self.assertEqual( |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1207 | list(zip(SequenceWithoutALength(), range(2**30))), |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1208 | list(enumerate(range(5))) |
| 1209 | ) |
| 1210 | |
| 1211 | class BadSeq: |
| 1212 | def __getitem__(self, i): |
| 1213 | if i == 5: |
| 1214 | raise ValueError |
| 1215 | else: |
| 1216 | return i |
Guido van Rossum | 801f0d7 | 2006-08-24 19:48:10 +0000 | [diff] [blame] | 1217 | self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq())) |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1218 | |
Eric Smith | e4d6317 | 2010-09-13 20:48:43 +0000 | [diff] [blame] | 1219 | def test_format(self): |
| 1220 | # Test the basic machinery of the format() builtin. Don't test |
| 1221 | # the specifics of the various formatters |
| 1222 | self.assertEqual(format(3, ''), '3') |
| 1223 | |
| 1224 | # Returns some classes to use for various tests. There's |
| 1225 | # an old-style version, and a new-style version |
| 1226 | def classes_new(): |
| 1227 | class A(object): |
| 1228 | def __init__(self, x): |
| 1229 | self.x = x |
| 1230 | def __format__(self, format_spec): |
| 1231 | return str(self.x) + format_spec |
| 1232 | class DerivedFromA(A): |
| 1233 | pass |
| 1234 | |
| 1235 | class Simple(object): pass |
| 1236 | class DerivedFromSimple(Simple): |
| 1237 | def __init__(self, x): |
| 1238 | self.x = x |
| 1239 | def __format__(self, format_spec): |
| 1240 | return str(self.x) + format_spec |
| 1241 | class DerivedFromSimple2(DerivedFromSimple): pass |
| 1242 | return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2 |
| 1243 | |
| 1244 | def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2): |
| 1245 | self.assertEqual(format(A(3), 'spec'), '3spec') |
| 1246 | self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec') |
| 1247 | self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc') |
| 1248 | self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'), |
| 1249 | '10abcdef') |
| 1250 | |
| 1251 | class_test(*classes_new()) |
| 1252 | |
| 1253 | def empty_format_spec(value): |
| 1254 | # test that: |
| 1255 | # format(x, '') == str(x) |
| 1256 | # format(x) == str(x) |
| 1257 | self.assertEqual(format(value, ""), str(value)) |
| 1258 | self.assertEqual(format(value), str(value)) |
| 1259 | |
| 1260 | # for builtin types, format(x, "") == str(x) |
| 1261 | empty_format_spec(17**13) |
| 1262 | empty_format_spec(1.0) |
| 1263 | empty_format_spec(3.1415e104) |
| 1264 | empty_format_spec(-3.1415e104) |
| 1265 | empty_format_spec(3.1415e-104) |
| 1266 | empty_format_spec(-3.1415e-104) |
| 1267 | empty_format_spec(object) |
| 1268 | empty_format_spec(None) |
| 1269 | |
| 1270 | # TypeError because self.__format__ returns the wrong type |
| 1271 | class BadFormatResult: |
| 1272 | def __format__(self, format_spec): |
| 1273 | return 1.0 |
| 1274 | self.assertRaises(TypeError, format, BadFormatResult(), "") |
| 1275 | |
| 1276 | # TypeError because format_spec is not unicode or str |
| 1277 | self.assertRaises(TypeError, format, object(), 4) |
| 1278 | self.assertRaises(TypeError, format, object(), object()) |
| 1279 | |
| 1280 | # tests for object.__format__ really belong elsewhere, but |
| 1281 | # there's no good place to put them |
| 1282 | x = object().__format__('') |
| 1283 | self.assertTrue(x.startswith('<object object at')) |
| 1284 | |
| 1285 | # first argument to object.__format__ must be string |
| 1286 | self.assertRaises(TypeError, object().__format__, 3) |
| 1287 | self.assertRaises(TypeError, object().__format__, object()) |
| 1288 | self.assertRaises(TypeError, object().__format__, None) |
| 1289 | |
| 1290 | # -------------------------------------------------------------------- |
| 1291 | # Issue #7994: object.__format__ with a non-empty format string is |
Eric V. Smith | b9cd353 | 2011-03-12 10:08:48 -0500 | [diff] [blame] | 1292 | # deprecated |
Eric Smith | e4d6317 | 2010-09-13 20:48:43 +0000 | [diff] [blame] | 1293 | def test_deprecated_format_string(obj, fmt_str, should_raise_warning): |
| 1294 | with warnings.catch_warnings(record=True) as w: |
Eric V. Smith | b9cd353 | 2011-03-12 10:08:48 -0500 | [diff] [blame] | 1295 | warnings.simplefilter("always", DeprecationWarning) |
Eric Smith | e4d6317 | 2010-09-13 20:48:43 +0000 | [diff] [blame] | 1296 | format(obj, fmt_str) |
| 1297 | if should_raise_warning: |
| 1298 | self.assertEqual(len(w), 1) |
Eric V. Smith | b9cd353 | 2011-03-12 10:08:48 -0500 | [diff] [blame] | 1299 | self.assertIsInstance(w[0].message, DeprecationWarning) |
Eric Smith | e4d6317 | 2010-09-13 20:48:43 +0000 | [diff] [blame] | 1300 | self.assertIn('object.__format__ with a non-empty format ' |
| 1301 | 'string', str(w[0].message)) |
| 1302 | else: |
| 1303 | self.assertEqual(len(w), 0) |
| 1304 | |
| 1305 | fmt_strs = ['', 's'] |
| 1306 | |
| 1307 | class A: |
| 1308 | def __format__(self, fmt_str): |
| 1309 | return format('', fmt_str) |
| 1310 | |
| 1311 | for fmt_str in fmt_strs: |
| 1312 | test_deprecated_format_string(A(), fmt_str, False) |
| 1313 | |
| 1314 | class B: |
| 1315 | pass |
| 1316 | |
| 1317 | class C(object): |
| 1318 | pass |
| 1319 | |
| 1320 | for cls in [object, B, C]: |
| 1321 | for fmt_str in fmt_strs: |
| 1322 | test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0) |
| 1323 | # -------------------------------------------------------------------- |
| 1324 | |
| 1325 | # make sure we can take a subclass of str as a format spec |
| 1326 | class DerivedFromStr(str): pass |
| 1327 | self.assertEqual(format(0, DerivedFromStr('10')), ' 0') |
| 1328 | |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 1329 | def test_bin(self): |
| 1330 | self.assertEqual(bin(0), '0b0') |
| 1331 | self.assertEqual(bin(1), '0b1') |
| 1332 | self.assertEqual(bin(-1), '-0b1') |
| 1333 | self.assertEqual(bin(2**65), '0b1' + '0' * 65) |
| 1334 | self.assertEqual(bin(2**65-1), '0b' + '1' * 65) |
| 1335 | self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65) |
| 1336 | self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65) |
| 1337 | |
Georg Brandl | 953152f | 2009-07-22 12:03:59 +0000 | [diff] [blame] | 1338 | def test_bytearray_translate(self): |
| 1339 | x = bytearray(b"abc") |
| 1340 | self.assertRaises(ValueError, x.translate, b"1", 1) |
| 1341 | self.assertRaises(TypeError, x.translate, b"1"*256, 1) |
| 1342 | |
Raymond Hettinger | 64958a1 | 2003-12-17 20:43:33 +0000 | [diff] [blame] | 1343 | class TestSorted(unittest.TestCase): |
| 1344 | |
| 1345 | def test_basic(self): |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1346 | data = list(range(100)) |
Raymond Hettinger | 64958a1 | 2003-12-17 20:43:33 +0000 | [diff] [blame] | 1347 | copy = data[:] |
| 1348 | random.shuffle(copy) |
| 1349 | self.assertEqual(data, sorted(copy)) |
| 1350 | self.assertNotEqual(data, copy) |
| 1351 | |
| 1352 | data.reverse() |
| 1353 | random.shuffle(copy) |
Raymond Hettinger | 64958a1 | 2003-12-17 20:43:33 +0000 | [diff] [blame] | 1354 | self.assertEqual(data, sorted(copy, key=lambda x: -x)) |
| 1355 | self.assertNotEqual(data, copy) |
| 1356 | random.shuffle(copy) |
| 1357 | self.assertEqual(data, sorted(copy, reverse=1)) |
| 1358 | self.assertNotEqual(data, copy) |
| 1359 | |
| 1360 | def test_inputtypes(self): |
| 1361 | s = 'abracadabra' |
Walter Dörwald | 1f5947b | 2007-05-22 16:52:54 +0000 | [diff] [blame] | 1362 | types = [list, tuple, str] |
Walter Dörwald | 4e41a4b | 2005-08-03 17:09:04 +0000 | [diff] [blame] | 1363 | for T in types: |
Raymond Hettinger | 64958a1 | 2003-12-17 20:43:33 +0000 | [diff] [blame] | 1364 | self.assertEqual(sorted(s), sorted(T(s))) |
| 1365 | |
Walter Dörwald | 1f5947b | 2007-05-22 16:52:54 +0000 | [diff] [blame] | 1366 | s = ''.join(set(s)) # unique letters only |
| 1367 | types = [str, set, frozenset, list, tuple, dict.fromkeys] |
Walter Dörwald | 4e41a4b | 2005-08-03 17:09:04 +0000 | [diff] [blame] | 1368 | for T in types: |
Raymond Hettinger | 64958a1 | 2003-12-17 20:43:33 +0000 | [diff] [blame] | 1369 | self.assertEqual(sorted(s), sorted(T(s))) |
| 1370 | |
| 1371 | def test_baddecorator(self): |
| 1372 | data = 'The quick Brown fox Jumped over The lazy Dog'.split() |
| 1373 | self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) |
| 1374 | |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 1375 | def test_main(verbose=None): |
| 1376 | test_classes = (BuiltinTest, TestSorted) |
| 1377 | |
| 1378 | run_unittest(*test_classes) |
| 1379 | |
| 1380 | # verify reference counting |
| 1381 | if verbose and hasattr(sys, "gettotalrefcount"): |
| 1382 | import gc |
| 1383 | counts = [None] * 5 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1384 | for i in range(len(counts)): |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 1385 | run_unittest(*test_classes) |
| 1386 | gc.collect() |
| 1387 | counts[i] = sys.gettotalrefcount() |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1388 | print(counts) |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 1389 | |
Walter Dörwald | 919497e | 2003-01-19 16:23:59 +0000 | [diff] [blame] | 1390 | |
| 1391 | if __name__ == "__main__": |
Raymond Hettinger | 3b0c7c2 | 2004-12-03 08:30:39 +0000 | [diff] [blame] | 1392 | test_main(verbose=True) |