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

Side by Side Diff: Lib/test/test_collections.py

Issue 25958: Implicit ABCs have no means of "anti-registration"
Patch Set: Created 4 years, 1 month 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:
View unified diff | Download patch
OLDNEW
1 """Unit tests for collections.py.""" 1 """Unit tests for collections.py."""
2 2
3 import collections 3 import collections
4 import copy 4 import copy
5 import doctest 5 import doctest
6 import inspect 6 import inspect
7 import keyword 7 import keyword
8 import operator 8 import operator
9 import pickle 9 import pickle
10 from random import choice, randrange 10 from random import choice, randrange
11 import re 11 import re
12 import string 12 import string
13 import sys 13 import sys
14 from test import support 14 from test import support
15 import types 15 import types
16 import unittest 16 import unittest
17 17
18 from collections import namedtuple, Counter, OrderedDict, _count_elements 18 from collections import namedtuple, Counter, OrderedDict, _count_elements
19 from collections import UserDict, UserString, UserList 19 from collections import UserDict, UserString, UserList
20 from collections import ChainMap 20 from collections import ChainMap
21 from collections import deque 21 from collections import deque
22 from collections.abc import Awaitable, Coroutine, AsyncIterator, AsyncIterable 22 from collections.abc import Awaitable, Coroutine, AsyncIterator, AsyncIterable
23 from collections.abc import Hashable, Iterable, Iterator, Generator 23 from collections.abc import Hashable, Iterable, Iterator, Generator
24 from collections.abc import Sized, Container, Callable 24 from collections.abc import Sized, Container, Reversible, Callable
25 from collections.abc import Set, MutableSet 25 from collections.abc import Set, MutableSet
26 from collections.abc import Mapping, MutableMapping, KeysView, ItemsView 26 from collections.abc import Mapping, MutableMapping, KeysView, ItemsView
27 from collections.abc import Sequence, MutableSequence 27 from collections.abc import Sequence, MutableSequence
28 from collections.abc import ByteString 28 from collections.abc import ByteString
29 29
30 30
31 class TestUserObjects(unittest.TestCase): 31 class TestUserObjects(unittest.TestCase):
32 def _superset_test(self, a, b): 32 def _superset_test(self, a, b):
33 self.assertGreaterEqual( 33 self.assertGreaterEqual(
34 set(dir(a)), 34 set(dir(a)),
(...skipping 646 matching lines...) Expand 10 before | Expand all | Expand 10 after
681 self.assertIsInstance(x, Iterable) 681 self.assertIsInstance(x, Iterable)
682 self.assertTrue(issubclass(type(x), Iterable), repr(type(x))) 682 self.assertTrue(issubclass(type(x), Iterable), repr(type(x)))
683 # Check direct subclassing 683 # Check direct subclassing
684 class I(Iterable): 684 class I(Iterable):
685 def __iter__(self): 685 def __iter__(self):
686 return super().__iter__() 686 return super().__iter__()
687 self.assertEqual(list(I()), []) 687 self.assertEqual(list(I()), [])
688 self.assertFalse(issubclass(str, I)) 688 self.assertFalse(issubclass(str, I))
689 self.validate_abstract_methods(Iterable, '__iter__') 689 self.validate_abstract_methods(Iterable, '__iter__')
690 self.validate_isinstance(Iterable, '__iter__') 690 self.validate_isinstance(Iterable, '__iter__')
691 # Check None blocking
692 class J:
storchaka 2016/01/05 21:48:04 Could you please use more descriptive names?
abarnert 2016/01/05 23:28:55 I was following the pattern established in this fi
storchaka 2016/01/06 00:04:31 I is an abbreviation of Iterable, it is good, as w
693 def __iter__(self): return iter([])
694 class K(J):
695 __iter__ = None
696 self.assertTrue(issubclass(J, Iterable))
697 self.assertTrue(isinstance(J(), Iterable))
698 self.assertFalse(issubclass(K, Iterable))
699 self.assertFalse(isinstance(K(), Iterable))
700
701 def test_Reversible(self):
702 # Check some non-iterables
703 non_iterables = [None, 42, 3.14, 1j]
704 for x in non_iterables:
705 self.assertNotIsInstance(x, Reversible)
706 self.assertFalse(issubclass(type(x), Reversible), repr(type(x)))
707 # Check some non-reversible iterables
708 non_reversibles = [set(), frozenset(), dict(), dict().keys(),
709 dict().items(), dict().values(),
710 Counter(), Counter().keys(), Counter().items(),
711 Counter().values(), (lambda: (yield))(),
712 (x for x in []), iter([]), reversed([])
713 ]
714 for x in non_reversibles:
715 self.assertNotIsInstance(x, Reversible)
716 self.assertFalse(issubclass(type(x), Reversible), repr(type(x)))
717 # Check some reversible iterables
718 samples = [bytes(), str(),
719 tuple(), list(), OrderedDict(), OrderedDict().keys(),
720 OrderedDict().items(), OrderedDict().values(),
721 ]
722 for x in samples:
723 self.assertIsInstance(x, Reversible)
724 self.assertTrue(issubclass(type(x), Reversible), repr(type(x)))
725 # Check direct subclassing
726 class R(Reversible):
727 def __iter__(self):
728 return super().__iter__()
729 def __reversed__(self):
730 return super().__reversed__()
731 self.assertEqual(list(R()), [])
732 self.assertEqual(list(reversed(R())), list(reversed([])))
733 self.assertFalse(issubclass(str, R))
734 self.validate_abstract_methods(Reversible, '__reversed__', '__iter__')
735 # Check None blocking
736 class J:
737 def __iter__(self): return iter([])
738 def __reversed__(self): return reversed([])
739 class K(J):
storchaka 2016/01/05 21:48:04 What if just not implement __iter__?
abarnert 2016/01/05 23:28:55 Then you'd inherit the base class's __iter__ and b
storchaka 2016/01/06 00:04:31 I meant that needed a test for a class that implem
740 __iter__ = None
741 class L(J):
742 __reversed__ = None
743 self.assertTrue(issubclass(J, Reversible))
744 self.assertTrue(isinstance(J(), Reversible))
745 self.assertFalse(issubclass(K, Reversible))
746 self.assertFalse(isinstance(K(), Reversible))
747 self.assertFalse(issubclass(L, Reversible))
748 self.assertFalse(isinstance(L(), Reversible))
691 749
692 def test_Iterator(self): 750 def test_Iterator(self):
693 non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()] 751 non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()]
694 for x in non_samples: 752 for x in non_samples:
695 self.assertNotIsInstance(x, Iterator) 753 self.assertNotIsInstance(x, Iterator)
696 self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) 754 self.assertFalse(issubclass(type(x), Iterator), repr(type(x)))
697 samples = [iter(bytes()), iter(str()), 755 samples = [iter(bytes()), iter(str()),
698 iter(tuple()), iter(list()), iter(dict()), 756 iter(tuple()), iter(list()), iter(dict()),
699 iter(set()), iter(frozenset()), 757 iter(set()), iter(frozenset()),
700 iter(dict().keys()), iter(dict().items()), 758 iter(dict().keys()), iter(dict().items()),
(...skipping 511 matching lines...) Expand 10 before | Expand all | Expand 10 after
1212 self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__l en__', 1270 self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__l en__',
1213 '__getitem__') 1271 '__getitem__')
1214 class MyMapping(Mapping): 1272 class MyMapping(Mapping):
1215 def __len__(self): 1273 def __len__(self):
1216 return 0 1274 return 0
1217 def __getitem__(self, i): 1275 def __getitem__(self, i):
1218 raise IndexError 1276 raise IndexError
1219 def __iter__(self): 1277 def __iter__(self):
1220 return iter(()) 1278 return iter(())
1221 self.validate_comparison(MyMapping()) 1279 self.validate_comparison(MyMapping())
1280 self.assertRaises(TypeError, reversed, MyMapping())
1222 1281
1223 def test_MutableMapping(self): 1282 def test_MutableMapping(self):
1224 for sample in [dict]: 1283 for sample in [dict]:
1225 self.assertIsInstance(sample(), MutableMapping) 1284 self.assertIsInstance(sample(), MutableMapping)
1226 self.assertTrue(issubclass(sample, MutableMapping)) 1285 self.assertTrue(issubclass(sample, MutableMapping))
1227 self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__ ', '__len__', 1286 self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__ ', '__len__',
1228 '__getitem__', '__setitem__', '__delitem__') 1287 '__getitem__', '__setitem__', '__delitem__')
1229 1288
1230 def test_MutableMapping_subclass(self): 1289 def test_MutableMapping_subclass(self):
1231 # Test issue 9214 1290 # Test issue 9214
(...skipping 399 matching lines...) Expand 10 before | Expand all | Expand 10 after
1631 test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, 1690 test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs,
1632 TestCollectionABCs, TestCounter, TestChainMap, 1691 TestCollectionABCs, TestCounter, TestChainMap,
1633 TestUserObjects, 1692 TestUserObjects,
1634 ] 1693 ]
1635 support.run_unittest(*test_classes) 1694 support.run_unittest(*test_classes)
1636 support.run_doctest(collections, verbose) 1695 support.run_doctest(collections, verbose)
1637 1696
1638 1697
1639 if __name__ == "__main__": 1698 if __name__ == "__main__":
1640 test_main(verbose=True) 1699 test_main(verbose=True)
OLDNEW

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