Debian Codegraph @

pypy/module/__builtin__/test/test_functional.py

raw symbols SCIP
1 import pytest
2
3 class AppTestMap:
4 def test_trivial_map_one_seq(self):
5 assert list(map(lambda x: x+2, [1, 2, 3, 4])) == [3, 4, 5, 6]
6
7 def test_trivial_map_one_seq_2(self):
8 assert list(map(str, [1, 2, 3, 4])) == ['1', '2', '3', '4']
9
10 def test_trivial_map_two_seq(self):
11 assert list(map(lambda x,y: x+y,
12 [1, 2, 3, 4],[1, 2, 3, 4])) == (
13 [2, 4, 6, 8])
14
15 def test_trivial_map_sizes_dont_match(self):
16 assert list(map(lambda x,y: x+y, [1, 2, 3, 4], [1, 2, 3])) == (
17 [2, 4, 6])
18
19 def test_trivial_map_no_arguments(self):
20 raises(TypeError, map)
21
22 def test_trivial_map_no_function_no_seq(self):
23 raises(TypeError, map, None)
24
25 def test_trivial_map_no_fuction(self):
26 m = map(None, [1, 2, 3]) # Don't crash here...
27 raises(TypeError, next, m) # ...but only on first item.
28
29 def test_map_identity1(self):
30 a = ['1', 2, 3, 'b', None]
31 b = a[:]
32 assert list(map(lambda x: x, a)) == a
33 assert a == b
34
35 def test_map_badoperation(self):
36 a = ['1', 2, 3, 'b', None]
37 raises(TypeError, list, map, lambda x: x+1, a)
38
39 def test_map_add(self):
40 a = [1, 2, 3, 4]
41 b = [0, 1, 1, 1]
42 assert list(map(lambda x, y: x+y, a, b)) == [1, 3, 4, 5]
43
44 def test_map_first_item(self):
45 a = [1, 2, 3, 4, 5]
46 b = [6, 7, 8, 9, 10]
47 assert list(map(lambda x, y: x, a, b)) == a
48
49 def test_map_second_item(self):
50 a = []
51 b = [1, 2, 3, 4, 5]
52 assert list(map(lambda x, y: y, a, b)) == a
53
54 def test_map_iterables(self):
55 class A(object):
56 def __init__(self, n):
57 self.n = n
58 def __iter__(self):
59 return B(self.n)
60 class B(object):
61 def __init__(self, n):
62 self.n = n
63 def __next__(self):
64 self.n -= 1
65 if self.n == 0: raise StopIteration
66 return self.n
67 result = map(lambda *x:x, A(3), A(8))
68 # this also checks that B.next() is not called any more after it
69 # raised StopIteration once
70 assert list(result) == [(2, 7), (1, 6)]
71
72 def test_repr(self):
73 assert repr(map(1, [2])).startswith('<map object ')
74
75 def test_subclass_kwarg(self):
76 class subclass_with_new(map):
77 def __new__(cls, f, v, newarg=None):
78 self = super().__new__(cls, f, v)
79 self.newarg = newarg
80 return self
81 u = subclass_with_new(int, ['1', '2'], newarg=3)
82 assert u.newarg == 3
83 assert list(u) == [1, 2]
84
85 class subclass_with_init(map):
86 def __init__(self, f, v, newarg=None):
87 self.newarg = newarg
88 u = subclass_with_init(int, ['1', '2'], newarg=3)
89 assert u.newarg == 3
90 assert list(u) == [1, 2]
91
92 with raises(TypeError) as e:
93 u = map()
94 assert str(e.value) == "map() must have at least two arguments"
95
96 with raises(TypeError) as e:
97 u = map(int, [1, 2], newargs=3)
98 assert str(e.value) == "map() takes no keyword arguments"
99
100 class subclass(map):
101 pass
102 with raises(TypeError) as e:
103 subclass(str, [1, 2], newarg=3)
104
105 class AppTestMap2:
106
107 def test_map(self):
108 obj_list = [object(), object(), object()]
109 it = map(lambda *x:x, obj_list)
110 for x in obj_list:
111 assert next(it) == (x, )
112 raises(StopIteration, next, it)
113
114 it = map(lambda *x:x, [1, 2, 3], [4], [5, 6])
115 assert next(it) == (1, 4, 5)
116 raises(StopIteration, next, it)
117
118 it = map(lambda *x:x, [], [], [1], [])
119 raises(StopIteration, next, it)
120
121 it = map(str, [0, 1, 0, 1])
122 for x in ['0', '1', '0', '1']:
123 assert next(it) == x
124 raises(StopIteration, next, it)
125
126 import operator
127 it = map(operator.add, [1, 2, 3], [4, 5, 6])
128 for x in [5, 7, 9]:
129 assert next(it) == x
130 raises(StopIteration, next, it)
131
132 def test_map_wrongargs(self):
133 # Duplicate python 2.4 behaviour for invalid arguments
134 it = map(0, [])
135 raises(StopIteration, next, it)
136 it = map(0, [0])
137 raises(TypeError, next, it)
138 raises(TypeError, map, None, 0)
139
140 raises(TypeError, map, None)
141 raises(TypeError, map, bool)
142 raises(TypeError, map, 42)
143
144
145 class AppTestZip:
146 def test_one_list(self):
147 assert list(zip([1,2,3])) == [(1,), (2,), (3,)]
148
149 def test_three_lists(self):
150 assert list(zip([1,2,3], [1,2], [1,2,3])) == [(1,1,1), (2,2,2)]
151
152 def test_strict_same_length(self):
153 assert list(zip(strict=True)) == []
154 assert list(zip([1,2,3], strict=True)) == [(1,), (2,), (3,)]
155 assert list(zip([1,2,3], [1,2,3], strict=True)) == [(1,1), (2,2), (3,3)]
156 assert list(zip([1,2,3], [1,2,3], strict=True)) == [(1,1), (2,2), (3,3)]
157 assert list(zip([1,2,3], [1,2,3], [1,2,3], strict=True)) == [(1,1,1), (2,2,2), (3,3,3)]
158
159
160 def test_strict_different_length_shorter_singular(self):
161 with raises(ValueError) as exinfo:
162 l = list()
163 l.extend(zip([1,2,3], [1,2], strict=True))
164 assert "zip() argument 2 is shorter than argument 1" in str(exinfo.value)
165 assert l == [(1,1), (2,2)]
166
167 def test_strict_different_length_shorter_plural(self):
168 with raises(ValueError) as exinfo:
169 l = list()
170 l.extend(zip([1,2,3], [1,2,3], [1,2], strict=True))
171 assert "zip() argument 3 is shorter than arguments 1-2" in str(exinfo.value)
172 assert l == [(1,1,1), (2,2,2)]
173
174 def test_strict_different_length_longer_singular(self):
175 with raises(ValueError) as exinfo:
176 l = list()
177 l.extend(zip([1,2], [1,2,3], strict=True))
178 assert "zip() argument 2 is longer than argument 1" in str(exinfo.value)
179 assert l == [(1,1), (2,2)]
180
181 def test_strict_different_length_longer_plural(self):
182 with raises(ValueError) as exinfo:
183 l = list()
184 l.extend(zip([1,2], [1,2], [1,2,3], strict=True))
185 assert "zip() argument 3 is longer than arguments 1-2" in str(exinfo.value)
186 assert l == [(1,1,1), (2,2,2)]
187
188 def test_zip_strict_reduce(self):
189 l1 = [1, 2, 3]
190 l2 = [2, 3, 4, 5]
191 res = zip(l1, l2, strict=True).__reduce__()
192 assert len(res) == 3 and res[2] is True
193
194 def test_bad_length_hint(self):
195 class Foo(object):
196 def __length_hint__(self):
197 return NotImplemented
198 def __iter__(self):
199 if False:
200 yield None
201 assert list(zip(Foo())) == []
202
203 def test_repr(self):
204 assert repr(zip([1,2,3], [1,2], [1,2,3])).startswith('<zip object ')
205
206 def test_zip_setstate(self):
207 l1 = [1, 2, 3]
208 l2 = [2, 3, 4, 5]
209 z = zip(l1, l2, strict=False)
210 z.__setstate__(True)
211 with raises(ValueError):
212 t = []
213 for v1, v2 in z:
214 t.append((v1, v2))
215 assert t == [(1, 2), (2, 3), (3, 4)]
216
217
218
219
220
221 class AppTestFilter:
222 def test_None(self):
223 assert list(filter(None, ['a', 'b', 1, 0, None])) == ['a', 'b', 1]
224
225 def test_return_type(self):
226 txt = "This is a test text"
227 assert list(filter(None, txt)) == list(txt)
228 tup = ("a", None, 0, [], 1)
229 assert list(filter(None, tup)) == ["a", 1]
230
231 def test_function(self):
232 assert list(filter(lambda x: x != "a", "a small text")) == list(" smll text")
233 assert list(filter(lambda x: x < 20, [3, 33, 5, 55])) == [3, 5]
234
235 def test_filter_reduce(self):
236 it = iter([1, 2, 3, 4, 5])
237 f = filter(None, it)
238 assert f.__reduce__() == (filter, (None, it))
239 f = filter(bool, it)
240 assert f.__reduce__() == (filter, (bool, it))
241
242 def test_subclass_kwarg(self):
243 class subclass_with_new(filter):
244 def __new__(cls, f, v, newarg=None):
245 self = super().__new__(cls, f, v)
246 self.newarg = newarg
247 return self
248 u = subclass_with_new(None, [1, 2], newarg=3)
249 assert u.newarg == 3
250 assert list(u) == [1, 2]
251
252 class subclass_with_init(filter):
253 def __init__(self, f, v, newarg=None):
254 self.newarg = newarg
255 u = subclass_with_init(None, [1, 2], newarg=3)
256 assert u.newarg == 3
257 assert list(u) == [1, 2]
258
259 with raises(TypeError) as e:
260 u = filter()
261 assert str(e.value) == "filter() expected 2 arguments got 0"
262
263 with raises(TypeError) as e:
264 u = filter(None, [1, 2], newargs=3)
265 assert str(e.value) == "filter() takes no keyword arguments"
266
267 class subclass(filter):
268 pass
269 with raises(TypeError) as e:
270 subclass(None, [1, 2], newarg=3)
271
272
273 class AppTestFilter2:
274 def test_filter(self):
275 it = filter(None, [])
276 raises(StopIteration, next, it)
277
278 it = filter(None, [1, 0, 2, 3, 0])
279 for x in [1, 2, 3]:
280 assert next(it) == x
281 raises(StopIteration, next, it)
282
283 def is_odd(arg):
284 return (arg % 2 == 1)
285
286 it = filter(is_odd, [1, 2, 3, 4, 5, 6])
287 for x in [1, 3, 5]:
288 assert next(it) == x
289 raises(StopIteration, next, it)
290
291 def test_filter_wrongargs(self):
292 it = filter(0, [1])
293 raises(TypeError, next, it)
294
295 raises(TypeError, filter, bool, None)
296
297
298 class AppTestRange:
299 def test_range(self):
300 x = range(2, 9, 3)
301 assert x[1] == 5
302 assert len(x) == 3
303 assert list(x) == [2, 5, 8]
304 # test again, to make sure that range() is not its own iterator
305 assert list(x) == [2, 5, 8]
306
307 def test_range_toofew(self):
308 raises(TypeError, range)
309
310 def test_range_toomany(self):
311 raises(TypeError, range, 1, 2, 3, 4)
312
313 def test_range_one(self):
314 assert list(range(1)) == [0]
315
316 def test_range_posstartisstop(self):
317 assert list(range(1, 1)) == []
318
319 def test_range_negstartisstop(self):
320 assert list(range(-1, -1)) == []
321
322 def test_range_zero(self):
323 assert list(range(0)) == []
324
325 def test_range_twoargs(self):
326 assert list(range(1, 2)) == [1]
327
328 def test_range_decreasingtwoargs(self):
329 assert list(range(3, 1)) == []
330
331 def test_range_negatives(self):
332 assert list(range(-3)) == []
333
334 def test_range_decreasing_negativestep(self):
335 assert list(range(5, -2, -1)) == [5, 4, 3, 2, 1, 0 , -1]
336
337 def test_range_posfencepost1(self):
338 assert list(range(1, 10, 3)) == [1, 4, 7]
339
340 def test_range_posfencepost2(self):
341 assert list(range(1, 11, 3)) == [1, 4, 7, 10]
342
343 def test_range_posfencepost3(self):
344 assert list(range(1, 12, 3)) == [1, 4, 7, 10]
345
346 def test_range_negfencepost1(self):
347 assert list(range(-1, -10, -3)) == [-1, -4, -7]
348
349 def test_range_negfencepost2(self):
350 assert list(range(-1, -11, -3)) == [-1, -4, -7, -10]
351
352 def test_range_negfencepost3(self):
353 assert list(range(-1, -12, -3)) == [-1, -4, -7, -10]
354
355 def test_range_decreasing_negativelargestep(self):
356 assert list(range(5, -2, -3)) == [5, 2, -1]
357
358 def test_range_increasing_positivelargestep(self):
359 assert list(range(-5, 2, 3)) == [-5, -2, 1]
360
361 def test_range_zerostep(self):
362 raises(ValueError, range, 1, 5, 0)
363
364 def test_range_wrong_type(self):
365 raises(TypeError, range, "42")
366
367 def test_range_iter(self):
368 x = range(2, 9, 3)
369 it = iter(x)
370 assert iter(it) is it
371 assert it.__next__() == 2
372 assert it.__next__() == 5
373 assert it.__next__() == 8
374 raises(StopIteration, it.__next__)
375 # test again, to make sure that range() is not its own iterator
376 assert iter(x).__next__() == 2
377
378 def test_range_object_with___index__(self):
379 class A(object):
380 def __index__(self):
381 return 5
382
383 assert list(range(A())) == [0, 1, 2, 3, 4]
384 assert list(range(0, A())) == [0, 1, 2, 3, 4]
385 assert list(range(0, 10, A())) == [0, 5]
386
387 class A2(object):
388 def __index__(self):
389 return 'quux'
390 raises(TypeError, range, A2())
391
392 def test_range_float(self):
393 raises(TypeError, range, 0.1)
394 raises(TypeError, range, 0.1, 0)
395 raises(TypeError, range, 0, 0.1)
396 raises(TypeError, range, 0.1, 0, 0)
397 raises(TypeError, range, 0, 0.1, 0)
398 raises(TypeError, range, 0, 0, 0.1)
399 raises(TypeError, range, 0.1, 2.0, 1.1)
400
401 def test_range_long(self):
402 import sys
403 assert list(range(-2**100)) == []
404 assert list(range(0, -2**100)) == []
405 assert list(range(0, 2**100, -1)) == []
406 assert list(range(0, 2**100, -1)) == []
407
408 a = 10 * sys.maxsize
409 assert range(a)[-1] == a-1
410 assert range(0, a)[-1] == a-1
411 assert range(0, 1, a)[-1] == 0
412 assert list(range(a, a+2)) == [a, a+1]
413 assert list(range(a+2, a, -1)) == [a+2, a+1]
414 assert list(range(a+4, a, -2)) == [a+4, a+2]
415 assert list(range(a, a*5, a)) == [a, 2*a, 3*a, 4*a]
416
417 def test_range_cases(self):
418 import sys
419 for start in [10, 10 * sys.maxsize]:
420 for stop in [start-4, start-1, start, start+1, start+4]:
421 for step in [1, 2, 3, 4]:
422 lst = list(range(start, stop, step))
423 expected = []
424 a = start
425 while a < stop:
426 expected.append(a)
427 a += step
428 assert lst == expected
429 for step in [-1, -2, -3, -4]:
430 lst = list(range(start, stop, step))
431 expected = []
432 a = start
433 while a > stop:
434 expected.append(a)
435 a += step
436 assert lst == expected
437
438 def test_range_contains(self):
439 assert 3 in range(5)
440 assert 3 not in range(3)
441 assert 3 not in range(4, 5)
442 assert 3 in range(1, 5, 2)
443 assert 3 not in range(0, 5, 2)
444 assert '3' not in range(5)
445
446 def test_range_count(self):
447 assert range(5).count(3) == 1
448 assert type(range(5).count(3)) is int
449 assert range(0, 5, 2).count(3) == 0
450 assert range(5).count(3.0) == 1
451 assert range(5).count('3') == 0
452
453 def test_range_getitem(self):
454 assert range(6)[3] == 3
455 assert range(6)[-1] == 5
456 raises(IndexError, range(6).__getitem__, 6)
457
458 def test_range_slice(self):
459 # range objects don't implement equality in 3.2, use the repr
460 assert repr(range(6)[2:5]) == 'range(2, 5)'
461 assert repr(range(6)[-1:-3:-2]) == 'range(5, 3, -2)'
462
463 def test_large_range(self):
464 import sys
465 def _range_len(x):
466 try:
467 length = len(x)
468 except OverflowError:
469 step = x[1] - x[0]
470 length = 1 + ((x[-1] - x[0]) // step)
471 return length
472 a = -sys.maxsize
473 b = sys.maxsize
474 expected_len = b - a
475 x = range(a, b)
476 assert a in x
477 assert b not in x
478 raises(OverflowError, len, x)
479 assert _range_len(x) == expected_len
480 assert x[0] == a
481 idx = sys.maxsize + 1
482 assert x[idx] == a + idx
483 assert a[idx:idx + 1][0] == a + idx
484 try:
485 x[-expected_len - 1]
486 except IndexError:
487 pass
488 else:
489 assert False, 'Expected IndexError'
490 try:
491 x[expected_len]
492 except IndexError:
493 pass
494 else:
495 assert False, 'Expected IndexError'
496
497 def test_range_index(self):
498 u = range(2)
499 assert u.index(0) == 0
500 assert u.index(1) == 1
501 raises(ValueError, u.index, 2)
502 raises(ValueError, u.index, object())
503 raises(TypeError, u.index)
504
505 assert range(1, 10, 3).index(4) == 1
506 assert range(1, -10, -3).index(-5) == 2
507
508 assert range(10**20).index(1) == 1
509 assert range(10**20).index(10**20 - 1) == 10**20 - 1
510
511 raises(ValueError, range(1, 2**100, 2).index, 2**87)
512 assert range(1, 2**100, 2).index(2**87+1) == 2**86
513
514 class AlwaysEqual(object):
515 def __eq__(self, other):
516 return True
517 always_equal = AlwaysEqual()
518 assert range(10).index(always_equal) == 0
519
520 def test_range_types(self):
521 assert 1.0 in range(3)
522 assert True in range(3)
523 assert 1+0j in range(3)
524
525 class C1:
526 def __eq__(self, other): return True
527 assert C1() in range(3)
528
529 # Objects are never coerced into other types for comparison.
530 class C2:
531 def __int__(self): return 1
532 def __index__(self): return 1
533 assert C2() not in range(3)
534 # ..except if explicitly told so.
535 assert int(C2()) in range(3)
536
537 # Check that the range.__contains__ optimization is only
538 # used for ints, not for instances of subclasses of int.
539 class C3(int):
540 def __eq__(self, other): return True
541 assert C3(11) in range(10)
542 assert C3(11) in list(range(10))
543
544 def test_range_reduce(self):
545 x = range(2, 9, 3)
546 callable, args = x.__reduce__()
547 y = callable(*args)
548 assert list(y) == list(x)
549
550 def test_range_iter_reduce(self):
551 x = iter(range(2, 9, 3))
552 next(x)
553 callable, args, idx = x.__reduce__()
554 y = callable(*args)
555 y.__setstate__(idx)
556 ylist = list(y)
557 xlist = list(x)
558 print(ylist)
559 print(xlist)
560 assert ylist == xlist
561
562 def test_range_iter_reduce_one(self):
563 x = iter(range(2, 9))
564 next(x)
565 callable, args, idx = x.__reduce__()
566 y = callable(*args)
567 y.__setstate__(idx)
568 assert list(y) == list(x)
569
570 def test_lib_python_range_optimization(self):
571 x = range(1)
572 assert type(reversed(x)) == type(iter(x))
573
574 def test_cpython_issue16029(self):
575 import sys
576 M = sys.maxsize
577 x = range(0, M, M - 1)
578 assert x.__reduce__() == (range, (0, M, M - 1))
579 x = range(0, -M, 1 - M)
580 assert x.__reduce__() == (range, (0, -M, 1 - M))
581
582 def test_cpython_issue16030(self):
583 import sys
584 M = sys.maxsize
585 x = range(0, M, M - 1)
586 assert repr(x) == 'range(0, %s, %s)' % (M, M - 1), repr(x)
587 x = range(0, -M, 1 - M)
588 assert repr(x) == 'range(0, %s, %s)' % (-M, 1 - M), repr(x)
589
590 def test_range_attributes(self):
591 rangeobj = range(3, 4, 5)
592 assert rangeobj.start == 3
593 assert rangeobj.stop == 4
594 assert rangeobj.step == 5
595
596 raises(AttributeError, "rangeobj.start = 0")
597 raises(AttributeError, "rangeobj.stop = 10")
598 raises(AttributeError, "rangeobj.step = 1")
599 raises(AttributeError, "del rangeobj.start")
600 raises(AttributeError, "del rangeobj.stop")
601 raises(AttributeError, "del rangeobj.step")
602
603 def test_comparison(self):
604 test_ranges = [range(0), range(0, -1), range(1, 1, 3),
605 range(1), range(5, 6), range(5, 6, 2),
606 range(5, 7, 2), range(2), range(0, 4, 2),
607 range(0, 5, 2), range(0, 6, 2)]
608 test_tuples = list(map(tuple, test_ranges))
609
610 # Check that equality of ranges matches equality of the corresponding
611 # tuples for each pair from the test lists above.
612 ranges_eq = [a == b for a in test_ranges for b in test_ranges]
613 tuples_eq = [a == b for a in test_tuples for b in test_tuples]
614 assert ranges_eq == tuples_eq
615
616 # Check that != correctly gives the logical negation of ==
617 ranges_ne = [a != b for a in test_ranges for b in test_ranges]
618 assert ranges_ne == [not x for x in ranges_eq]
619
620 # Equal ranges should have equal hashes.
621 for a in test_ranges:
622 for b in test_ranges:
623 if a == b:
624 assert hash(a) == hash(b)
625
626 # Ranges are unequal to other types (even sequence types)
627 assert (range(0) == ()) is False
628 assert (() == range(0)) is False
629 assert (range(2) == [0, 1]) is False
630
631 # Huge integers aren't a problem.
632 assert range(0, 2**100 - 1, 2) == range(0, 2**100, 2)
633 assert hash(range(0, 2**100 - 1, 2)) == hash(range(0, 2**100, 2))
634 assert range(0, 2**100, 2) != range(0, 2**100 + 1, 2)
635 assert (range(2**200, 2**201 - 2**99, 2**100) ==
636 range(2**200, 2**201, 2**100))
637 assert (hash(range(2**200, 2**201 - 2**99, 2**100)) ==
638 hash(range(2**200, 2**201, 2**100)))
639 assert (range(2**200, 2**201, 2**100) !=
640 range(2**200, 2**201 + 1, 2**100))
641
642 # Order comparisons are not implemented for ranges.
643 raises(TypeError, "range(0) < range(0)")
644 raises(TypeError, "range(0) > range(0)")
645 raises(TypeError, "range(0) <= range(0)")
646 raises(TypeError, "range(0) >= range(0)")
647
648 class AppTestReversed:
649 def test_reversed(self):
650 assert isinstance(reversed, type)
651 r = reversed("hello")
652 assert iter(r) is r
653 assert r.__next__() == "o"
654 assert r.__next__() == "l"
655 assert r.__next__() == "l"
656 assert r.__next__() == "e"
657 assert r.__next__() == "h"
658 raises(StopIteration, r.__next__)
659 assert list(reversed(list(reversed("hello")))) == ['h','e','l','l','o']
660 raises(TypeError, reversed, reversed("hello"))
661
662 def test_reversed_user_type(self):
663 class X(object):
664 def __getitem__(self, index):
665 return str(index)
666 def __len__(self):
667 return 5
668 assert list(reversed(X())) == ["4", "3", "2", "1", "0"]
669
670 def test_reversed_type_with_no_len(self):
671 class X(object):
672 def __getitem__(self, key):
673 raise ValueError
674 raises(TypeError, reversed, X())
675
676 def test_reversed_length_hint(self):
677 lst = [1, 2, 3]
678 r = reversed(lst)
679 assert r.__length_hint__() == 3
680 assert next(r) == 3
681 assert r.__length_hint__() == 2
682 lst.pop()
683 assert r.__length_hint__() == 2
684 lst.pop()
685 assert r.__length_hint__() == 0
686 raises(StopIteration, next, r)
687 #
688 r = reversed(lst)
689 assert r.__length_hint__() == 1
690 assert next(r) == 1
691 assert r.__length_hint__() == 0
692 raises(StopIteration, next, r)
693 assert r.__length_hint__() == 0
694
695 def test_reversed_setstate_crash(self):
696 reverse_iter = reversed((5,4,3,2,1))
697 assert list(reverse_iter) == [1, 2, 3, 4, 5]
698 reverse_iter.__setstate__(1) # used to segfault
699 assert list(reverse_iter) == []
700
701
702 class AppTestAllAny:
703 """
704 These are copied directly and replicated from the Python 2.5 source code.
705 """
706
707 def test_all(self):
708
709 class TestFailingBool(object):
710 def __bool__(self):
711 raise RuntimeError
712 class TestFailingIter(object):
713 def __iter__(self):
714 raise RuntimeError
715
716 assert all([2, 4, 6]) == True
717 assert all([2, None, 6]) == False
718 raises(RuntimeError, all, [2, TestFailingBool(), 6])
719 raises(RuntimeError, all, TestFailingIter())
720 raises(TypeError, all, 10) # Non-iterable
721 raises(TypeError, all) # No args
722 raises(TypeError, all, [2, 4, 6], []) # Too many args
723 assert all([]) == True # Empty iterator
724 S = [50, 60]
725 assert all([x > 42 for x in S]) == True
726 S = [50, 40, 60]
727 assert all([x > 42 for x in S]) == False
728
729 def test_any(self):
730
731 class TestFailingBool(object):
732 def __bool__(self):
733 raise RuntimeError
734 class TestFailingIter(object):
735 def __iter__(self):
736 raise RuntimeError
737
738 assert any([None, None, None]) == False
739 assert any([None, 4, None]) == True
740 raises(RuntimeError, any, [None, TestFailingBool(), 6])
741 raises(RuntimeError, all, TestFailingIter())
742 raises(TypeError, any, 10) # Non-iterable
743 raises(TypeError, any) # No args
744 raises(TypeError, any, [2, 4, 6], []) # Too many args
745 assert any([]) == False # Empty iterator
746 S = [40, 60, 30]
747 assert any([x > 42 for x in S]) == True
748 S = [10, 20, 30]
749 assert any([x > 42 for x in S]) == False
750
751
752 class AppTestMinMax:
753 def test_min(self):
754 assert min(1, 2) == 1
755 assert min(1, 2, key=lambda x: -x) == 2
756 assert min([1, 2, 3]) == 1
757 raises(TypeError, min, 1, 2, bar=2)
758 raises(TypeError, min, 1, 2, key=lambda x: x, bar=2)
759 assert type(min(1, 1.0)) is int
760 assert type(min(1.0, 1)) is float
761 assert type(min(1, 1.0, 1)) is int
762 assert type(min(1.0, 1, 1)) is float
763 assert type(min(1, 1, 1.0)) is int
764 assert min([], default=-1) == -1
765 assert min([1, 2], default=-1) == 1
766 raises(TypeError, min, 0, 1, default=-1)
767 assert min([], default=None) == None
768 raises(TypeError, min, 1, default=0)
769 raises(TypeError, min, default=1)
770 raises(ValueError, min, [])
771
772 def test_max(self):
773 assert max(1, 2) == 2
774 assert max(1, 2, key=lambda x: -x) == 1
775 assert max([1, 2, 3]) == 3
776 raises(TypeError, max, 1, 2, bar=2)
777 raises(TypeError, max, 1, 2, key=lambda x: x, bar=2)
778 assert type(max(1, 1.0)) is int
779 assert type(max(1.0, 1)) is float
780 assert type(max(1, 1.0, 1)) is int
781 assert type(max(1.0, 1, 1)) is float
782 assert type(max(1, 1, 1.0)) is int
783 assert max([], default=-1) == -1
784 assert max([1, 2], default=3) == 2
785 raises(TypeError, min, 0, 1, default=-1)
786 assert max([], default=None) == None
787 raises(TypeError, max, 1, default=0)
788 raises(TypeError, max, default=1)
789 raises(ValueError, max, [])
790
791 def test_max_list_and_key(self):
792 assert max(["100", "50", "30", "-200"], key=int) == "100"
793 assert max("100", "50", "30", "-200", key=int) == "100"
794
795 def test_max_key_is_None_works(self):
796 assert max(1, 2, key=None) == 2
797
798
799 try:
800 from hypothesis import given, strategies, example
801 except ImportError:
802 pass
803 else:
804 @given(lst=strategies.lists(strategies.integers()))
805 def test_map_hypothesis(space, lst):
806 print lst
807 w_lst = space.appexec([space.wrap(lst[:])], """(lst):
808 def change(n):
809 if n & 3 == 1:
810 lst.pop(0)
811 elif n & 3 == 2:
812 lst.append(100)
813 return n * 2
814 return list(map(change, lst))
815 """)
816 expected = []
817 i = 0
818 while i < len(lst):
819 n = lst[i]
820 if n & 3 == 1:
821 lst.pop(0)
822 elif n & 3 == 2:
823 lst.append(100)
824 expected.append(n * 2)
825 i += 1
826 assert space.unwrap(w_lst) == expected