Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(73476)

Delta Between Two Patch Sets: Lib/test/test_builtin.py

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 6 years, 9 months ago
Right Patch Set: Created 5 years, 6 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_buffer.py ('k') | Lib/test/test_bz2.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 # Python test set -- built-in functions 1 # Python test set -- built-in functions
2 2
3 import ast 3 import ast
4 import builtins 4 import builtins
5 import collections 5 import collections
6 import io 6 import io
7 import locale 7 import locale
8 import os 8 import os
9 import pickle 9 import pickle
10 import platform 10 import platform
(...skipping 162 matching lines...) Expand 10 before | Expand all | Expand 10 after
173 173
174 def test_all(self): 174 def test_all(self):
175 self.assertEqual(all([2, 4, 6]), True) 175 self.assertEqual(all([2, 4, 6]), True)
176 self.assertEqual(all([2, None, 6]), False) 176 self.assertEqual(all([2, None, 6]), False)
177 self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6]) 177 self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
178 self.assertRaises(RuntimeError, all, TestFailingIter()) 178 self.assertRaises(RuntimeError, all, TestFailingIter())
179 self.assertRaises(TypeError, all, 10) # Non-iterable 179 self.assertRaises(TypeError, all, 10) # Non-iterable
180 self.assertRaises(TypeError, all) # No args 180 self.assertRaises(TypeError, all) # No args
181 self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args 181 self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args
182 self.assertEqual(all([]), True) # Empty iterator 182 self.assertEqual(all([]), True) # Empty iterator
183 self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
183 S = [50, 60] 184 S = [50, 60]
184 self.assertEqual(all(x > 42 for x in S), True) 185 self.assertEqual(all(x > 42 for x in S), True)
185 S = [50, 40, 60] 186 S = [50, 40, 60]
186 self.assertEqual(all(x > 42 for x in S), False) 187 self.assertEqual(all(x > 42 for x in S), False)
187 188
188 def test_any(self): 189 def test_any(self):
189 self.assertEqual(any([None, None, None]), False) 190 self.assertEqual(any([None, None, None]), False)
190 self.assertEqual(any([None, 4, None]), True) 191 self.assertEqual(any([None, 4, None]), True)
191 self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6]) 192 self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
192 self.assertRaises(RuntimeError, all, TestFailingIter()) 193 self.assertRaises(RuntimeError, any, TestFailingIter())
193 self.assertRaises(TypeError, any, 10) # Non-iterable 194 self.assertRaises(TypeError, any, 10) # Non-iterable
194 self.assertRaises(TypeError, any) # No args 195 self.assertRaises(TypeError, any) # No args
195 self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args 196 self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args
196 self.assertEqual(any([]), False) # Empty iterator 197 self.assertEqual(any([]), False) # Empty iterator
198 self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
197 S = [40, 60, 30] 199 S = [40, 60, 30]
198 self.assertEqual(any(x > 42 for x in S), True) 200 self.assertEqual(any(x > 42 for x in S), True)
199 S = [10, 20, 30] 201 S = [10, 20, 30]
200 self.assertEqual(any(x > 42 for x in S), False) 202 self.assertEqual(any(x > 42 for x in S), False)
201 203
202 def test_ascii(self): 204 def test_ascii(self):
203 self.assertEqual(ascii(''), '\'\'') 205 self.assertEqual(ascii(''), '\'\'')
204 self.assertEqual(ascii(0), '0') 206 self.assertEqual(ascii(0), '0')
205 self.assertEqual(ascii(()), '()') 207 self.assertEqual(ascii(()), '()')
206 self.assertEqual(ascii([]), '[]') 208 self.assertEqual(ascii([]), '[]')
(...skipping 248 matching lines...) Expand 10 before | Expand all | Expand 10 after
455 self.assertEqual(eval('c', globals, locals), 300) 457 self.assertEqual(eval('c', globals, locals), 300)
456 globals = {'a': 1, 'b': 2} 458 globals = {'a': 1, 'b': 2}
457 locals = {'b': 200, 'c': 300} 459 locals = {'b': 200, 'c': 300}
458 bom = b'\xef\xbb\xbf' 460 bom = b'\xef\xbb\xbf'
459 self.assertEqual(eval(bom + b'a', globals, locals), 1) 461 self.assertEqual(eval(bom + b'a', globals, locals), 1)
460 self.assertEqual(eval('"\xe5"', globals), "\xe5") 462 self.assertEqual(eval('"\xe5"', globals), "\xe5")
461 self.assertRaises(TypeError, eval) 463 self.assertRaises(TypeError, eval)
462 self.assertRaises(TypeError, eval, ()) 464 self.assertRaises(TypeError, eval, ())
463 self.assertRaises(SyntaxError, eval, bom[:2] + b'a') 465 self.assertRaises(SyntaxError, eval, bom[:2] + b'a')
464 466
467 class X:
468 def __getitem__(self, key):
469 raise ValueError
470 self.assertRaises(ValueError, eval, "foo", {}, X())
471
465 def test_general_eval(self): 472 def test_general_eval(self):
466 # Tests that general mappings can be used for the locals argument 473 # Tests that general mappings can be used for the locals argument
467 474
468 class M: 475 class M:
469 "Test mapping interface versus possible calls from eval()." 476 "Test mapping interface versus possible calls from eval()."
470 def __getitem__(self, key): 477 def __getitem__(self, key):
471 if key == 'a': 478 if key == 'a':
472 return 12 479 return 12
473 raise KeyError 480 raise KeyError
474 def keys(self): 481 def keys(self):
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
570 exec, code, {'__builtins__': {}}) 577 exec, code, {'__builtins__': {}})
571 578
572 class frozendict_error(Exception): 579 class frozendict_error(Exception):
573 pass 580 pass
574 581
575 class frozendict(dict): 582 class frozendict(dict):
576 def __setitem__(self, key, value): 583 def __setitem__(self, key, value):
577 raise frozendict_error("frozendict is readonly") 584 raise frozendict_error("frozendict is readonly")
578 585
579 # read-only builtins 586 # read-only builtins
580 frozen_builtins = frozendict(__builtins__) 587 if isinstance(__builtins__, types.ModuleType):
588 frozen_builtins = frozendict(__builtins__.__dict__)
589 else:
590 frozen_builtins = frozendict(__builtins__)
581 code = compile("__builtins__['superglobal']=2; print(superglobal)", "tes t", "exec") 591 code = compile("__builtins__['superglobal']=2; print(superglobal)", "tes t", "exec")
582 self.assertRaises(frozendict_error, 592 self.assertRaises(frozendict_error,
583 exec, code, {'__builtins__': frozen_builtins}) 593 exec, code, {'__builtins__': frozen_builtins})
584 594
585 # read-only globals 595 # read-only globals
586 namespace = frozendict({}) 596 namespace = frozendict({})
587 code = compile("x=1", "test", "exec") 597 code = compile("x=1", "test", "exec")
588 self.assertRaises(frozendict_error, 598 self.assertRaises(frozendict_error,
589 exec, code, namespace) 599 exec, code, namespace)
590 600
(...skipping 239 matching lines...) Expand 10 before | Expand all | Expand 10 after
830 def test_max(self): 840 def test_max(self):
831 self.assertEqual(max('123123'), '3') 841 self.assertEqual(max('123123'), '3')
832 self.assertEqual(max(1, 2, 3), 3) 842 self.assertEqual(max(1, 2, 3), 3)
833 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) 843 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
834 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) 844 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
835 845
836 self.assertEqual(max(1, 2, 3.0), 3.0) 846 self.assertEqual(max(1, 2, 3.0), 3.0)
837 self.assertEqual(max(1, 2.0, 3), 3) 847 self.assertEqual(max(1, 2.0, 3), 3)
838 self.assertEqual(max(1.0, 2, 3), 3) 848 self.assertEqual(max(1.0, 2, 3), 3)
839 849
850 self.assertRaises(TypeError, max)
851 self.assertRaises(TypeError, max, 42)
852 self.assertRaises(ValueError, max, ())
853 class BadSeq:
854 def __getitem__(self, index):
855 raise ValueError
856 self.assertRaises(ValueError, max, BadSeq())
857
840 for stmt in ( 858 for stmt in (
841 "max(key=int)", # no args 859 "max(key=int)", # no args
860 "max(default=None)",
861 "max(1, 2, default=None)", # require container for default
862 "max(default=None, key=int)",
842 "max(1, key=int)", # single arg not iterable 863 "max(1, key=int)", # single arg not iterable
843 "max(1, 2, keystone=int)", # wrong keyword 864 "max(1, 2, keystone=int)", # wrong keyword
844 "max(1, 2, key=int, abc=int)", # two many keywords 865 "max(1, 2, key=int, abc=int)", # two many keywords
845 "max(1, 2, key=1)", # keyfunc is not callable 866 "max(1, 2, key=1)", # keyfunc is not callable
846 ): 867 ):
847 try: 868 try:
848 exec(stmt, globals()) 869 exec(stmt, globals())
849 except TypeError: 870 except TypeError:
850 pass 871 pass
851 else: 872 else:
852 self.fail(stmt) 873 self.fail(stmt)
853 874
854 self.assertEqual(max((1,), key=neg), 1) # one elem iterable 875 self.assertEqual(max((1,), key=neg), 1) # one elem iterable
855 self.assertEqual(max((1,2), key=neg), 1) # two elem iterable 876 self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
856 self.assertEqual(max(1, 2, key=neg), 1) # two elems 877 self.assertEqual(max(1, 2, key=neg), 1) # two elems
857 878
879 self.assertEqual(max((), default=None), None) # zero elem iterable
880 self.assertEqual(max((1,), default=None), 1) # one elem iterable
881 self.assertEqual(max((1,2), default=None), 2) # two elem iterable
882
883 self.assertEqual(max((), default=1, key=neg), 1)
884 self.assertEqual(max((1, 2), default=3, key=neg), 1)
885
858 data = [random.randrange(200) for i in range(100)] 886 data = [random.randrange(200) for i in range(100)]
859 keys = dict((elem, random.randrange(50)) for elem in data) 887 keys = dict((elem, random.randrange(50)) for elem in data)
860 f = keys.__getitem__ 888 f = keys.__getitem__
861 self.assertEqual(max(data, key=f), 889 self.assertEqual(max(data, key=f),
862 sorted(reversed(data), key=f)[-1]) 890 sorted(reversed(data), key=f)[-1])
863 891
864 def test_min(self): 892 def test_min(self):
865 self.assertEqual(min('123123'), '1') 893 self.assertEqual(min('123123'), '1')
866 self.assertEqual(min(1, 2, 3), 1) 894 self.assertEqual(min(1, 2, 3), 1)
867 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) 895 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
868 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) 896 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
869 897
870 self.assertEqual(min(1, 2, 3.0), 1) 898 self.assertEqual(min(1, 2, 3.0), 1)
871 self.assertEqual(min(1, 2.0, 3), 1) 899 self.assertEqual(min(1, 2.0, 3), 1)
872 self.assertEqual(min(1.0, 2, 3), 1.0) 900 self.assertEqual(min(1.0, 2, 3), 1.0)
873 901
874 self.assertRaises(TypeError, min) 902 self.assertRaises(TypeError, min)
875 self.assertRaises(TypeError, min, 42) 903 self.assertRaises(TypeError, min, 42)
876 self.assertRaises(ValueError, min, ()) 904 self.assertRaises(ValueError, min, ())
877 class BadSeq: 905 class BadSeq:
878 def __getitem__(self, index): 906 def __getitem__(self, index):
879 raise ValueError 907 raise ValueError
880 self.assertRaises(ValueError, min, BadSeq()) 908 self.assertRaises(ValueError, min, BadSeq())
881 909
882 for stmt in ( 910 for stmt in (
883 "min(key=int)", # no args 911 "min(key=int)", # no args
912 "min(default=None)",
913 "min(1, 2, default=None)", # require container for default
914 "min(default=None, key=int)",
884 "min(1, key=int)", # single arg not iterable 915 "min(1, key=int)", # single arg not iterable
885 "min(1, 2, keystone=int)", # wrong keyword 916 "min(1, 2, keystone=int)", # wrong keyword
886 "min(1, 2, key=int, abc=int)", # two many keywords 917 "min(1, 2, key=int, abc=int)", # two many keywords
887 "min(1, 2, key=1)", # keyfunc is not callable 918 "min(1, 2, key=1)", # keyfunc is not callable
888 ): 919 ):
889 try: 920 try:
890 exec(stmt, globals()) 921 exec(stmt, globals())
891 except TypeError: 922 except TypeError:
892 pass 923 pass
893 else: 924 else:
894 self.fail(stmt) 925 self.fail(stmt)
895 926
896 self.assertEqual(min((1,), key=neg), 1) # one elem iterable 927 self.assertEqual(min((1,), key=neg), 1) # one elem iterable
897 self.assertEqual(min((1,2), key=neg), 2) # two elem iterable 928 self.assertEqual(min((1,2), key=neg), 2) # two elem iterable
898 self.assertEqual(min(1, 2, key=neg), 2) # two elems 929 self.assertEqual(min(1, 2, key=neg), 2) # two elems
899 930
931 self.assertEqual(min((), default=None), None) # zero elem iterable
932 self.assertEqual(min((1,), default=None), 1) # one elem iterable
933 self.assertEqual(min((1,2), default=None), 1) # two elem iterable
934
935 self.assertEqual(min((), default=1, key=neg), 1)
936 self.assertEqual(min((1, 2), default=1, key=neg), 2)
937
900 data = [random.randrange(200) for i in range(100)] 938 data = [random.randrange(200) for i in range(100)]
901 keys = dict((elem, random.randrange(50)) for elem in data) 939 keys = dict((elem, random.randrange(50)) for elem in data)
902 f = keys.__getitem__ 940 f = keys.__getitem__
903 self.assertEqual(min(data, key=f), 941 self.assertEqual(min(data, key=f),
904 sorted(data, key=f)[0]) 942 sorted(data, key=f)[0])
905 943
906 def test_next(self): 944 def test_next(self):
907 it = iter(range(2)) 945 it = iter(range(2))
908 self.assertEqual(next(it), 0) 946 self.assertEqual(next(it), 0)
909 self.assertEqual(next(it), 1) 947 self.assertEqual(next(it), 1)
(...skipping 21 matching lines...) Expand all
931 self.assertEqual(next(it, 42), 42) 969 self.assertEqual(next(it, 42), 42)
932 970
933 def test_oct(self): 971 def test_oct(self):
934 self.assertEqual(oct(100), '0o144') 972 self.assertEqual(oct(100), '0o144')
935 self.assertEqual(oct(-100), '-0o144') 973 self.assertEqual(oct(-100), '-0o144')
936 self.assertRaises(TypeError, oct, ()) 974 self.assertRaises(TypeError, oct, ())
937 975
938 def write_testfile(self): 976 def write_testfile(self):
939 # NB the first 4 lines are also used to test input, below 977 # NB the first 4 lines are also used to test input, below
940 fp = open(TESTFN, 'w') 978 fp = open(TESTFN, 'w')
941 try: 979 self.addCleanup(unlink, TESTFN)
980 with fp:
942 fp.write('1+1\n') 981 fp.write('1+1\n')
943 fp.write('The quick brown fox jumps over the lazy dog') 982 fp.write('The quick brown fox jumps over the lazy dog')
944 fp.write('.\n') 983 fp.write('.\n')
945 fp.write('Dear John\n') 984 fp.write('Dear John\n')
946 fp.write('XXX'*100) 985 fp.write('XXX'*100)
947 fp.write('YYY'*100) 986 fp.write('YYY'*100)
948 finally:
949 fp.close()
950 987
951 def test_open(self): 988 def test_open(self):
952 self.write_testfile() 989 self.write_testfile()
953 fp = open(TESTFN, 'r') 990 fp = open(TESTFN, 'r')
954 try: 991 with fp:
955 self.assertEqual(fp.readline(4), '1+1\n') 992 self.assertEqual(fp.readline(4), '1+1\n')
956 self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') 993 self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
957 self.assertEqual(fp.readline(4), 'Dear') 994 self.assertEqual(fp.readline(4), 'Dear')
958 self.assertEqual(fp.readline(100), ' John\n') 995 self.assertEqual(fp.readline(100), ' John\n')
959 self.assertEqual(fp.read(300), 'XXX'*100) 996 self.assertEqual(fp.read(300), 'XXX'*100)
960 self.assertEqual(fp.read(1000), 'YYY'*100) 997 self.assertEqual(fp.read(1000), 'YYY'*100)
961 finally:
962 fp.close()
963 unlink(TESTFN)
964 998
965 def test_open_default_encoding(self): 999 def test_open_default_encoding(self):
966 old_environ = dict(os.environ) 1000 old_environ = dict(os.environ)
967 try: 1001 try:
968 # try to get a user preferred encoding different than the current 1002 # try to get a user preferred encoding different than the current
969 # locale encoding to check that open() uses the current locale 1003 # locale encoding to check that open() uses the current locale
970 # encoding and not the user preferred encoding 1004 # encoding and not the user preferred encoding
971 for key in ('LC_ALL', 'LANG', 'LC_CTYPE'): 1005 for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
972 if key in os.environ: 1006 if key in os.environ:
973 del os.environ[key] 1007 del os.environ[key]
974 1008
975 self.write_testfile() 1009 self.write_testfile()
976 current_locale_encoding = locale.getpreferredencoding(False) 1010 current_locale_encoding = locale.getpreferredencoding(False)
977 fp = open(TESTFN, 'w') 1011 fp = open(TESTFN, 'w')
978 try: 1012 with fp:
979 self.assertEqual(fp.encoding, current_locale_encoding) 1013 self.assertEqual(fp.encoding, current_locale_encoding)
980 finally:
981 fp.close()
982 unlink(TESTFN)
983 finally: 1014 finally:
984 os.environ.clear() 1015 os.environ.clear()
985 os.environ.update(old_environ) 1016 os.environ.update(old_environ)
1017
1018 def test_open_non_inheritable(self):
1019 fileobj = open(__file__)
1020 with fileobj:
1021 self.assertFalse(os.get_inheritable(fileobj.fileno()))
986 1022
987 def test_ord(self): 1023 def test_ord(self):
988 self.assertEqual(ord(' '), 32) 1024 self.assertEqual(ord(' '), 32)
989 self.assertEqual(ord('A'), 65) 1025 self.assertEqual(ord('A'), 65)
990 self.assertEqual(ord('a'), 97) 1026 self.assertEqual(ord('a'), 97)
991 self.assertEqual(ord('\x80'), 128) 1027 self.assertEqual(ord('\x80'), 128)
992 self.assertEqual(ord('\xff'), 255) 1028 self.assertEqual(ord('\xff'), 255)
993 1029
994 self.assertEqual(ord(b' '), 32) 1030 self.assertEqual(ord(b' '), 32)
995 self.assertEqual(ord(b'A'), 65) 1031 self.assertEqual(ord(b'A'), 65)
(...skipping 91 matching lines...) Expand 10 before | Expand all | Expand 10 after
1087 self.assertRaises(EOFError, input) 1123 self.assertRaises(EOFError, input)
1088 1124
1089 del sys.stdout 1125 del sys.stdout
1090 self.assertRaises(RuntimeError, input, 'prompt') 1126 self.assertRaises(RuntimeError, input, 'prompt')
1091 del sys.stdin 1127 del sys.stdin
1092 self.assertRaises(RuntimeError, input, 'prompt') 1128 self.assertRaises(RuntimeError, input, 'prompt')
1093 finally: 1129 finally:
1094 sys.stdin = savestdin 1130 sys.stdin = savestdin
1095 sys.stdout = savestdout 1131 sys.stdout = savestdout
1096 fp.close() 1132 fp.close()
1097 unlink(TESTFN)
1098 1133
1099 @unittest.skipUnless(pty, "the pty and signal modules must be available") 1134 @unittest.skipUnless(pty, "the pty and signal modules must be available")
1100 def check_input_tty(self, prompt, terminal_input, stdio_encoding=None): 1135 def check_input_tty(self, prompt, terminal_input, stdio_encoding=None):
1101 if not sys.stdin.isatty() or not sys.stdout.isatty(): 1136 if not sys.stdin.isatty() or not sys.stdout.isatty():
1102 self.skipTest("stdin and stdout must be ttys") 1137 self.skipTest("stdin and stdout must be ttys")
1103 r, w = os.pipe() 1138 r, w = os.pipe()
1104 try: 1139 try:
1105 pid, fd = pty.fork() 1140 pid, fd = pty.fork()
1106 except (OSError, AttributeError) as e: 1141 except (OSError, AttributeError) as e:
1107 os.close(r) 1142 os.close(r)
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after
1165 self.check_input_tty("prompt", b"quux") 1200 self.check_input_tty("prompt", b"quux")
1166 1201
1167 def test_input_tty_non_ascii(self): 1202 def test_input_tty_non_ascii(self):
1168 # Check stdin/stdout encoding is used when invoking GNU readline 1203 # Check stdin/stdout encoding is used when invoking GNU readline
1169 self.check_input_tty("prompté", b"quux\xe9", "utf-8") 1204 self.check_input_tty("prompté", b"quux\xe9", "utf-8")
1170 1205
1171 def test_input_tty_non_ascii_unicode_errors(self): 1206 def test_input_tty_non_ascii_unicode_errors(self):
1172 # Check stdin/stdout error handler is used when invoking GNU readline 1207 # Check stdin/stdout error handler is used when invoking GNU readline
1173 self.check_input_tty("prompté", b"quux\xe9", "ascii") 1208 self.check_input_tty("prompté", b"quux\xe9", "ascii")
1174 1209
1210 # test_int(): see test_int.py for tests of built-in function int().
1211
1175 def test_repr(self): 1212 def test_repr(self):
1176 self.assertEqual(repr(''), '\'\'') 1213 self.assertEqual(repr(''), '\'\'')
1177 self.assertEqual(repr(0), '0') 1214 self.assertEqual(repr(0), '0')
1178 self.assertEqual(repr(()), '()') 1215 self.assertEqual(repr(()), '()')
1179 self.assertEqual(repr([]), '[]') 1216 self.assertEqual(repr([]), '[]')
1180 self.assertEqual(repr({}), '{}') 1217 self.assertEqual(repr({}), '{}')
1181 a = [] 1218 a = []
1182 a.append(a) 1219 a.append(a)
1183 self.assertEqual(repr(a), '[[...]]') 1220 self.assertEqual(repr(a), '[[...]]')
1184 a = {} 1221 a = {}
(...skipping 94 matching lines...) Expand 10 before | Expand all | Expand 10 after
1279 self.assertEqual(round(5e15+1), 5e15+1) 1316 self.assertEqual(round(5e15+1), 5e15+1)
1280 self.assertEqual(round(5e15+2), 5e15+2) 1317 self.assertEqual(round(5e15+2), 5e15+2)
1281 self.assertEqual(round(5e15+3), 5e15+3) 1318 self.assertEqual(round(5e15+3), 5e15+3)
1282 1319
1283 def test_setattr(self): 1320 def test_setattr(self):
1284 setattr(sys, 'spam', 1) 1321 setattr(sys, 'spam', 1)
1285 self.assertEqual(sys.spam, 1) 1322 self.assertEqual(sys.spam, 1)
1286 self.assertRaises(TypeError, setattr, sys, 1, 'spam') 1323 self.assertRaises(TypeError, setattr, sys, 1, 'spam')
1287 self.assertRaises(TypeError, setattr) 1324 self.assertRaises(TypeError, setattr)
1288 1325
1326 # test_str(): see test_unicode.py and test_bytes.py for str() tests.
1289 1327
1290 def test_sum(self): 1328 def test_sum(self):
1291 self.assertEqual(sum([]), 0) 1329 self.assertEqual(sum([]), 0)
1292 self.assertEqual(sum(list(range(2,8))), 27) 1330 self.assertEqual(sum(list(range(2,8))), 27)
1293 self.assertEqual(sum(iter(list(range(2,8)))), 27) 1331 self.assertEqual(sum(iter(list(range(2,8)))), 27)
1294 self.assertEqual(sum(Squares(10)), 285) 1332 self.assertEqual(sum(Squares(10)), 285)
1295 self.assertEqual(sum(iter(Squares(10))), 285) 1333 self.assertEqual(sum(iter(Squares(10))), 285)
1296 self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) 1334 self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
1297 1335
1298 self.assertRaises(TypeError, sum) 1336 self.assertRaises(TypeError, sum)
(...skipping 165 matching lines...) Expand 10 before | Expand all | Expand 10 after
1464 self.assertTrue(x.startswith('<object object at')) 1502 self.assertTrue(x.startswith('<object object at'))
1465 1503
1466 # first argument to object.__format__ must be string 1504 # first argument to object.__format__ must be string
1467 self.assertRaises(TypeError, object().__format__, 3) 1505 self.assertRaises(TypeError, object().__format__, 3)
1468 self.assertRaises(TypeError, object().__format__, object()) 1506 self.assertRaises(TypeError, object().__format__, object())
1469 self.assertRaises(TypeError, object().__format__, None) 1507 self.assertRaises(TypeError, object().__format__, None)
1470 1508
1471 # -------------------------------------------------------------------- 1509 # --------------------------------------------------------------------
1472 # Issue #7994: object.__format__ with a non-empty format string is 1510 # Issue #7994: object.__format__ with a non-empty format string is
1473 # deprecated 1511 # deprecated
1474 def test_deprecated_format_string(obj, fmt_str, should_raise_warning): 1512 def test_deprecated_format_string(obj, fmt_str, should_raise):
1475 with warnings.catch_warnings(record=True) as w: 1513 if should_raise:
1476 warnings.simplefilter("always", DeprecationWarning) 1514 self.assertRaises(TypeError, format, obj, fmt_str)
1515 else:
1477 format(obj, fmt_str) 1516 format(obj, fmt_str)
1478 if should_raise_warning:
1479 self.assertEqual(len(w), 1)
1480 self.assertIsInstance(w[0].message, DeprecationWarning)
1481 self.assertIn('object.__format__ with a non-empty format '
1482 'string', str(w[0].message))
1483 else:
1484 self.assertEqual(len(w), 0)
1485 1517
1486 fmt_strs = ['', 's'] 1518 fmt_strs = ['', 's']
1487 1519
1488 class A: 1520 class A:
1489 def __format__(self, fmt_str): 1521 def __format__(self, fmt_str):
1490 return format('', fmt_str) 1522 return format('', fmt_str)
1491 1523
1492 for fmt_str in fmt_strs: 1524 for fmt_str in fmt_strs:
1493 test_deprecated_format_string(A(), fmt_str, False) 1525 test_deprecated_format_string(A(), fmt_str, False)
1494 1526
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
1553 1585
1554 s = ''.join(set(s)) # unique letters only 1586 s = ''.join(set(s)) # unique letters only
1555 types = [str, set, frozenset, list, tuple, dict.fromkeys] 1587 types = [str, set, frozenset, list, tuple, dict.fromkeys]
1556 for T in types: 1588 for T in types:
1557 self.assertEqual(sorted(s), sorted(T(s))) 1589 self.assertEqual(sorted(s), sorted(T(s)))
1558 1590
1559 def test_baddecorator(self): 1591 def test_baddecorator(self):
1560 data = 'The quick Brown fox Jumped over The lazy Dog'.split() 1592 data = 'The quick Brown fox Jumped over The lazy Dog'.split()
1561 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) 1593 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
1562 1594
1563 def test_main(verbose=None): 1595 def load_tests(loader, tests, pattern):
1564 test_classes = (BuiltinTest, TestSorted) 1596 from doctest import DocTestSuite
1565 1597 tests.addTest(DocTestSuite(builtins))
1566 run_unittest(*test_classes) 1598 return tests
1567
1568 # verify reference counting
1569 if verbose and hasattr(sys, "gettotalrefcount"):
1570 import gc
1571 counts = [None] * 5
1572 for i in range(len(counts)):
1573 run_unittest(*test_classes)
1574 gc.collect()
1575 counts[i] = sys.gettotalrefcount()
1576 print(counts)
1577
1578 1599
1579 if __name__ == "__main__": 1600 if __name__ == "__main__":
1580 test_main(verbose=True) 1601 unittest.main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+