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

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

Issue 25958: Implicit ABCs have no means of "anti-registration"
Patch Set: Created 4 years, 2 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:
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 It:
693 def __iter__(self): return iter([])
694 class ItBlocked(It):
695 __iter__ = None
696 self.assertTrue(issubclass(It, Iterable))
697 self.assertTrue(isinstance(It(), Iterable))
698 self.assertFalse(issubclass(ItBlocked, Iterable))
699 self.assertFalse(isinstance(ItBlocked(), 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))(),
Martin Panter 2016/01/09 02:34:57 I still don’t like the lambda–generator. I would b
abarnert 2016/01/18 20:28:42 It's also in `test_Iterator`, `test_Generator`, `t
Martin Panter 2016/02/02 03:10:13 Well I did figure it out, but it initially threw m
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())), [])
733 self.assertFalse(issubclass(str, R))
734 self.validate_abstract_methods(Reversible, '__reversed__', '__iter__')
735 # Check reversible non-iterable (which is not Reversible)
736 class RevNoIter:
737 def __reversed__(self): return reversed([])
738 class RevPlusIter(RevNoIter):
739 def __iter__(self): return iter([])
740 self.assertFalse(issubclass(RevNoIter, Reversible))
741 self.assertFalse(isinstance(RevNoIter(), Reversible))
742 self.assertTrue(issubclass(RevPlusIter, Reversible))
743 self.assertTrue(isinstance(RevPlusIter(), Reversible))
744 # Check None blocking
745 class Rev:
746 def __iter__(self): return iter([])
747 def __reversed__(self): return reversed([])
748 class RevItBlocked(Rev):
749 __iter__ = None
750 class RevRevBlocked(Rev):
751 __reversed__ = None
752 self.assertTrue(issubclass(Rev, Reversible))
753 self.assertTrue(isinstance(Rev(), Reversible))
754 self.assertFalse(issubclass(RevItBlocked, Reversible))
755 self.assertFalse(isinstance(RevItBlocked(), Reversible))
756 self.assertFalse(issubclass(RevRevBlocked, Reversible))
757 self.assertFalse(isinstance(RevRevBlocked(), Reversible))
691 758
692 def test_Iterator(self): 759 def test_Iterator(self):
693 non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()] 760 non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()]
694 for x in non_samples: 761 for x in non_samples:
695 self.assertNotIsInstance(x, Iterator) 762 self.assertNotIsInstance(x, Iterator)
696 self.assertFalse(issubclass(type(x), Iterator), repr(type(x))) 763 self.assertFalse(issubclass(type(x), Iterator), repr(type(x)))
697 samples = [iter(bytes()), iter(str()), 764 samples = [iter(bytes()), iter(str()),
698 iter(tuple()), iter(list()), iter(dict()), 765 iter(tuple()), iter(list()), iter(dict()),
699 iter(set()), iter(frozenset()), 766 iter(set()), iter(frozenset()),
700 iter(dict().keys()), iter(dict().items()), 767 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__', 1279 self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__l en__',
1213 '__getitem__') 1280 '__getitem__')
1214 class MyMapping(Mapping): 1281 class MyMapping(Mapping):
1215 def __len__(self): 1282 def __len__(self):
1216 return 0 1283 return 0
1217 def __getitem__(self, i): 1284 def __getitem__(self, i):
1218 raise IndexError 1285 raise IndexError
1219 def __iter__(self): 1286 def __iter__(self):
1220 return iter(()) 1287 return iter(())
1221 self.validate_comparison(MyMapping()) 1288 self.validate_comparison(MyMapping())
1289 self.assertRaises(TypeError, reversed, MyMapping())
1222 1290
1223 def test_MutableMapping(self): 1291 def test_MutableMapping(self):
1224 for sample in [dict]: 1292 for sample in [dict]:
1225 self.assertIsInstance(sample(), MutableMapping) 1293 self.assertIsInstance(sample(), MutableMapping)
1226 self.assertTrue(issubclass(sample, MutableMapping)) 1294 self.assertTrue(issubclass(sample, MutableMapping))
1227 self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__ ', '__len__', 1295 self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__ ', '__len__',
1228 '__getitem__', '__setitem__', '__delitem__') 1296 '__getitem__', '__setitem__', '__delitem__')
1229 1297
1230 def test_MutableMapping_subclass(self): 1298 def test_MutableMapping_subclass(self):
1231 # Test issue 9214 1299 # Test issue 9214
(...skipping 399 matching lines...) Expand 10 before | Expand all | Expand 10 after
1631 test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, 1699 test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs,
1632 TestCollectionABCs, TestCounter, TestChainMap, 1700 TestCollectionABCs, TestCounter, TestChainMap,
1633 TestUserObjects, 1701 TestUserObjects,
1634 ] 1702 ]
1635 support.run_unittest(*test_classes) 1703 support.run_unittest(*test_classes)
1636 support.run_doctest(collections, verbose) 1704 support.run_doctest(collections, verbose)
1637 1705
1638 1706
1639 if __name__ == "__main__": 1707 if __name__ == "__main__":
1640 test_main(verbose=True) 1708 test_main(verbose=True)
OLDNEW

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