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

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

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 5 years, 11 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 368 matching lines...) Expand 10 before | Expand all | Expand 10 after
575 exec, code, {'__builtins__': {}}) 577 exec, code, {'__builtins__': {}})
576 578
577 class frozendict_error(Exception): 579 class frozendict_error(Exception):
578 pass 580 pass
579 581
580 class frozendict(dict): 582 class frozendict(dict):
581 def __setitem__(self, key, value): 583 def __setitem__(self, key, value):
582 raise frozendict_error("frozendict is readonly") 584 raise frozendict_error("frozendict is readonly")
583 585
584 # read-only builtins 586 # read-only builtins
585 frozen_builtins = frozendict(__builtins__) 587 if isinstance(__builtins__, types.ModuleType):
588 frozen_builtins = frozendict(__builtins__.__dict__)
589 else:
590 frozen_builtins = frozendict(__builtins__)
586 code = compile("__builtins__['superglobal']=2; print(superglobal)", "tes t", "exec") 591 code = compile("__builtins__['superglobal']=2; print(superglobal)", "tes t", "exec")
587 self.assertRaises(frozendict_error, 592 self.assertRaises(frozendict_error,
588 exec, code, {'__builtins__': frozen_builtins}) 593 exec, code, {'__builtins__': frozen_builtins})
589 594
590 # read-only globals 595 # read-only globals
591 namespace = frozendict({}) 596 namespace = frozendict({})
592 code = compile("x=1", "test", "exec") 597 code = compile("x=1", "test", "exec")
593 self.assertRaises(frozendict_error, 598 self.assertRaises(frozendict_error,
594 exec, code, namespace) 599 exec, code, namespace)
595 600
(...skipping 239 matching lines...) Expand 10 before | Expand all | Expand 10 after
835 def test_max(self): 840 def test_max(self):
836 self.assertEqual(max('123123'), '3') 841 self.assertEqual(max('123123'), '3')
837 self.assertEqual(max(1, 2, 3), 3) 842 self.assertEqual(max(1, 2, 3), 3)
838 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) 843 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
839 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) 844 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
840 845
841 self.assertEqual(max(1, 2, 3.0), 3.0) 846 self.assertEqual(max(1, 2, 3.0), 3.0)
842 self.assertEqual(max(1, 2.0, 3), 3) 847 self.assertEqual(max(1, 2.0, 3), 3)
843 self.assertEqual(max(1.0, 2, 3), 3) 848 self.assertEqual(max(1.0, 2, 3), 3)
844 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
845 for stmt in ( 858 for stmt in (
846 "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)",
847 "max(1, key=int)", # single arg not iterable 863 "max(1, key=int)", # single arg not iterable
848 "max(1, 2, keystone=int)", # wrong keyword 864 "max(1, 2, keystone=int)", # wrong keyword
849 "max(1, 2, key=int, abc=int)", # two many keywords 865 "max(1, 2, key=int, abc=int)", # two many keywords
850 "max(1, 2, key=1)", # keyfunc is not callable 866 "max(1, 2, key=1)", # keyfunc is not callable
851 ): 867 ):
852 try: 868 try:
853 exec(stmt, globals()) 869 exec(stmt, globals())
854 except TypeError: 870 except TypeError:
855 pass 871 pass
856 else: 872 else:
857 self.fail(stmt) 873 self.fail(stmt)
858 874
859 self.assertEqual(max((1,), key=neg), 1) # one elem iterable 875 self.assertEqual(max((1,), key=neg), 1) # one elem iterable
860 self.assertEqual(max((1,2), key=neg), 1) # two elem iterable 876 self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
861 self.assertEqual(max(1, 2, key=neg), 1) # two elems 877 self.assertEqual(max(1, 2, key=neg), 1) # two elems
862 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
863 data = [random.randrange(200) for i in range(100)] 886 data = [random.randrange(200) for i in range(100)]
864 keys = dict((elem, random.randrange(50)) for elem in data) 887 keys = dict((elem, random.randrange(50)) for elem in data)
865 f = keys.__getitem__ 888 f = keys.__getitem__
866 self.assertEqual(max(data, key=f), 889 self.assertEqual(max(data, key=f),
867 sorted(reversed(data), key=f)[-1]) 890 sorted(reversed(data), key=f)[-1])
868 891
869 def test_min(self): 892 def test_min(self):
870 self.assertEqual(min('123123'), '1') 893 self.assertEqual(min('123123'), '1')
871 self.assertEqual(min(1, 2, 3), 1) 894 self.assertEqual(min(1, 2, 3), 1)
872 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) 895 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
873 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) 896 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
874 897
875 self.assertEqual(min(1, 2, 3.0), 1) 898 self.assertEqual(min(1, 2, 3.0), 1)
876 self.assertEqual(min(1, 2.0, 3), 1) 899 self.assertEqual(min(1, 2.0, 3), 1)
877 self.assertEqual(min(1.0, 2, 3), 1.0) 900 self.assertEqual(min(1.0, 2, 3), 1.0)
878 901
879 self.assertRaises(TypeError, min) 902 self.assertRaises(TypeError, min)
880 self.assertRaises(TypeError, min, 42) 903 self.assertRaises(TypeError, min, 42)
881 self.assertRaises(ValueError, min, ()) 904 self.assertRaises(ValueError, min, ())
882 class BadSeq: 905 class BadSeq:
883 def __getitem__(self, index): 906 def __getitem__(self, index):
884 raise ValueError 907 raise ValueError
885 self.assertRaises(ValueError, min, BadSeq()) 908 self.assertRaises(ValueError, min, BadSeq())
886 909
887 for stmt in ( 910 for stmt in (
888 "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)",
889 "min(1, key=int)", # single arg not iterable 915 "min(1, key=int)", # single arg not iterable
890 "min(1, 2, keystone=int)", # wrong keyword 916 "min(1, 2, keystone=int)", # wrong keyword
891 "min(1, 2, key=int, abc=int)", # two many keywords 917 "min(1, 2, key=int, abc=int)", # two many keywords
892 "min(1, 2, key=1)", # keyfunc is not callable 918 "min(1, 2, key=1)", # keyfunc is not callable
893 ): 919 ):
894 try: 920 try:
895 exec(stmt, globals()) 921 exec(stmt, globals())
896 except TypeError: 922 except TypeError:
897 pass 923 pass
898 else: 924 else:
899 self.fail(stmt) 925 self.fail(stmt)
900 926
901 self.assertEqual(min((1,), key=neg), 1) # one elem iterable 927 self.assertEqual(min((1,), key=neg), 1) # one elem iterable
902 self.assertEqual(min((1,2), key=neg), 2) # two elem iterable 928 self.assertEqual(min((1,2), key=neg), 2) # two elem iterable
903 self.assertEqual(min(1, 2, key=neg), 2) # two elems 929 self.assertEqual(min(1, 2, key=neg), 2) # two elems
904 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
905 data = [random.randrange(200) for i in range(100)] 938 data = [random.randrange(200) for i in range(100)]
906 keys = dict((elem, random.randrange(50)) for elem in data) 939 keys = dict((elem, random.randrange(50)) for elem in data)
907 f = keys.__getitem__ 940 f = keys.__getitem__
908 self.assertEqual(min(data, key=f), 941 self.assertEqual(min(data, key=f),
909 sorted(data, key=f)[0]) 942 sorted(data, key=f)[0])
910 943
911 def test_next(self): 944 def test_next(self):
912 it = iter(range(2)) 945 it = iter(range(2))
913 self.assertEqual(next(it), 0) 946 self.assertEqual(next(it), 0)
914 self.assertEqual(next(it), 1) 947 self.assertEqual(next(it), 1)
(...skipping 21 matching lines...) Expand all
936 self.assertEqual(next(it, 42), 42) 969 self.assertEqual(next(it, 42), 42)
937 970
938 def test_oct(self): 971 def test_oct(self):
939 self.assertEqual(oct(100), '0o144') 972 self.assertEqual(oct(100), '0o144')
940 self.assertEqual(oct(-100), '-0o144') 973 self.assertEqual(oct(-100), '-0o144')
941 self.assertRaises(TypeError, oct, ()) 974 self.assertRaises(TypeError, oct, ())
942 975
943 def write_testfile(self): 976 def write_testfile(self):
944 # 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
945 fp = open(TESTFN, 'w') 978 fp = open(TESTFN, 'w')
946 try: 979 self.addCleanup(unlink, TESTFN)
980 with fp:
947 fp.write('1+1\n') 981 fp.write('1+1\n')
948 fp.write('The quick brown fox jumps over the lazy dog') 982 fp.write('The quick brown fox jumps over the lazy dog')
949 fp.write('.\n') 983 fp.write('.\n')
950 fp.write('Dear John\n') 984 fp.write('Dear John\n')
951 fp.write('XXX'*100) 985 fp.write('XXX'*100)
952 fp.write('YYY'*100) 986 fp.write('YYY'*100)
953 finally:
954 fp.close()
955 987
956 def test_open(self): 988 def test_open(self):
957 self.write_testfile() 989 self.write_testfile()
958 fp = open(TESTFN, 'r') 990 fp = open(TESTFN, 'r')
959 try: 991 with fp:
960 self.assertEqual(fp.readline(4), '1+1\n') 992 self.assertEqual(fp.readline(4), '1+1\n')
961 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')
962 self.assertEqual(fp.readline(4), 'Dear') 994 self.assertEqual(fp.readline(4), 'Dear')
963 self.assertEqual(fp.readline(100), ' John\n') 995 self.assertEqual(fp.readline(100), ' John\n')
964 self.assertEqual(fp.read(300), 'XXX'*100) 996 self.assertEqual(fp.read(300), 'XXX'*100)
965 self.assertEqual(fp.read(1000), 'YYY'*100) 997 self.assertEqual(fp.read(1000), 'YYY'*100)
966 finally:
967 fp.close()
968 unlink(TESTFN)
969 998
970 def test_open_default_encoding(self): 999 def test_open_default_encoding(self):
971 old_environ = dict(os.environ) 1000 old_environ = dict(os.environ)
972 try: 1001 try:
973 # try to get a user preferred encoding different than the current 1002 # try to get a user preferred encoding different than the current
974 # locale encoding to check that open() uses the current locale 1003 # locale encoding to check that open() uses the current locale
975 # encoding and not the user preferred encoding 1004 # encoding and not the user preferred encoding
976 for key in ('LC_ALL', 'LANG', 'LC_CTYPE'): 1005 for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
977 if key in os.environ: 1006 if key in os.environ:
978 del os.environ[key] 1007 del os.environ[key]
979 1008
980 self.write_testfile() 1009 self.write_testfile()
981 current_locale_encoding = locale.getpreferredencoding(False) 1010 current_locale_encoding = locale.getpreferredencoding(False)
982 fp = open(TESTFN, 'w') 1011 fp = open(TESTFN, 'w')
983 try: 1012 with fp:
984 self.assertEqual(fp.encoding, current_locale_encoding) 1013 self.assertEqual(fp.encoding, current_locale_encoding)
985 finally:
986 fp.close()
987 unlink(TESTFN)
988 finally: 1014 finally:
989 os.environ.clear() 1015 os.environ.clear()
990 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()))
991 1022
992 def test_ord(self): 1023 def test_ord(self):
993 self.assertEqual(ord(' '), 32) 1024 self.assertEqual(ord(' '), 32)
994 self.assertEqual(ord('A'), 65) 1025 self.assertEqual(ord('A'), 65)
995 self.assertEqual(ord('a'), 97) 1026 self.assertEqual(ord('a'), 97)
996 self.assertEqual(ord('\x80'), 128) 1027 self.assertEqual(ord('\x80'), 128)
997 self.assertEqual(ord('\xff'), 255) 1028 self.assertEqual(ord('\xff'), 255)
998 1029
999 self.assertEqual(ord(b' '), 32) 1030 self.assertEqual(ord(b' '), 32)
1000 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
1092 self.assertRaises(EOFError, input) 1123 self.assertRaises(EOFError, input)
1093 1124
1094 del sys.stdout 1125 del sys.stdout
1095 self.assertRaises(RuntimeError, input, 'prompt') 1126 self.assertRaises(RuntimeError, input, 'prompt')
1096 del sys.stdin 1127 del sys.stdin
1097 self.assertRaises(RuntimeError, input, 'prompt') 1128 self.assertRaises(RuntimeError, input, 'prompt')
1098 finally: 1129 finally:
1099 sys.stdin = savestdin 1130 sys.stdin = savestdin
1100 sys.stdout = savestdout 1131 sys.stdout = savestdout
1101 fp.close() 1132 fp.close()
1102 unlink(TESTFN)
1103 1133
1104 @unittest.skipUnless(pty, "the pty and signal modules must be available") 1134 @unittest.skipUnless(pty, "the pty and signal modules must be available")
1105 def check_input_tty(self, prompt, terminal_input, stdio_encoding=None): 1135 def check_input_tty(self, prompt, terminal_input, stdio_encoding=None):
1106 if not sys.stdin.isatty() or not sys.stdout.isatty(): 1136 if not sys.stdin.isatty() or not sys.stdout.isatty():
1107 self.skipTest("stdin and stdout must be ttys") 1137 self.skipTest("stdin and stdout must be ttys")
1108 r, w = os.pipe() 1138 r, w = os.pipe()
1109 try: 1139 try:
1110 pid, fd = pty.fork() 1140 pid, fd = pty.fork()
1111 except (OSError, AttributeError) as e: 1141 except (OSError, AttributeError) as e:
1112 os.close(r) 1142 os.close(r)
(...skipping 442 matching lines...) Expand 10 before | Expand all | Expand 10 after
1555 1585
1556 s = ''.join(set(s)) # unique letters only 1586 s = ''.join(set(s)) # unique letters only
1557 types = [str, set, frozenset, list, tuple, dict.fromkeys] 1587 types = [str, set, frozenset, list, tuple, dict.fromkeys]
1558 for T in types: 1588 for T in types:
1559 self.assertEqual(sorted(s), sorted(T(s))) 1589 self.assertEqual(sorted(s), sorted(T(s)))
1560 1590
1561 def test_baddecorator(self): 1591 def test_baddecorator(self):
1562 data = 'The quick Brown fox Jumped over The lazy Dog'.split() 1592 data = 'The quick Brown fox Jumped over The lazy Dog'.split()
1563 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) 1593 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
1564 1594
1565 def test_main(verbose=None): 1595 def load_tests(loader, tests, pattern):
1566 test_classes = (BuiltinTest, TestSorted) 1596 from doctest import DocTestSuite
1567 1597 tests.addTest(DocTestSuite(builtins))
1568 run_unittest(*test_classes) 1598 return tests
1569
1570 # verify reference counting
1571 if verbose and hasattr(sys, "gettotalrefcount"):
1572 import gc
1573 counts = [None] * 5
1574 for i in range(len(counts)):
1575 run_unittest(*test_classes)
1576 gc.collect()
1577 counts[i] = sys.gettotalrefcount()
1578 print(counts)
1579
1580 1599
1581 if __name__ == "__main__": 1600 if __name__ == "__main__":
1582 test_main(verbose=True) 1601 unittest.main()
LEFTRIGHT

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