Test for Python 2 BytesKeyDict and UnicodeKeyDict behavior.

This commit is contained in:
Itamar Turner-Trauring 2020-11-05 10:15:38 -05:00
parent a49ef086b6
commit cd01d4dafa

View File

@ -8,9 +8,10 @@ from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future.utils import PY2
from future.utils import PY2, PY3
if PY2:
from builtins import filter, map, zip, ascii, chr, hex, input, next, oct, open, pow, round, super, bytes, dict, list, object, range, str, max, min # noqa: F401
# dict omitted to match dictutil.py.
from future.builtins import filter, map, zip, ascii, chr, hex, input, next, oct, open, pow, round, super, bytes, list, object, range, str, max, min # noqa: F401
from unittest import skipIf
@ -124,7 +125,7 @@ class TypedKeyDict(unittest.TestCase):
self.assertEqual(d[b"456"], 300)
def test_unicode(self):
"""UnicodeKeyDict is limited to just byte keys."""
"""UnicodeKeyDict is limited to just unicode keys."""
self.assertRaises(TypeError, dictutil.UnicodeKeyDict, {b"hello": 123})
d = dictutil.UnicodeKeyDict({u"123": 200})
with self.assertRaises(TypeError):
@ -146,3 +147,24 @@ class TypedKeyDict(unittest.TestCase):
self.assertEqual(d.get(u"456", 50), 50)
self.assertEqual(d.setdefault(u"456", 300), 300)
self.assertEqual(d[u"456"], 300)
class TypedKeyDictPython2(unittest.TestCase):
"""Tests for dictionaries that limit keys on Python 2."""
@skipIf(PY3, "Testing Python 2 behavior.")
def test_python2(self):
"""
On Python2, BytesKeyDict and UnicodeKeyDict are unnecessary, because
dicts can mix both without problem so you don't get confusing behavior
if you get the type wrong.
Eventually in a Python 3-only world mixing bytes and unicode will be
bad, thus the existence of these classes, but as we port there will be
situations where it's mixed on Python 2, which again is fine.
"""
self.assertIs(dictutil.UnicodeKeyDict, dict)
self.assertIs(dictutil.BytesKeyDict, dict)
# Demonstration of how bytes and unicode can be mixed:
d = {u"abc": 1}
self.assertEqual(d[b"abc"], 1)