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