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