bidict/tests/test_namedbidict.txt

74 lines
2.0 KiB
Plaintext

# Copyright 2018 Joshua Bronson. All Rights Reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
Test script for :func:`bidict.namedbidict`::
>>> from bidict import namedbidict
>>> ElementMap = namedbidict('ElementMap', 'symbol', 'name')
>>> noble_gases = ElementMap(He='helium')
>>> noble_gases.name_for['He']
'helium'
>>> noble_gases.symbol_for['helium']
'He'
>>> noble_gases.name_for['Ne'] = 'neon'
>>> del noble_gases.symbol_for['helium']
>>> noble_gases
ElementMap({'Ne': 'neon'})
``.inv`` still works too::
>>> noble_gases.inv
ElementMap({'neon': 'Ne'})
>>> noble_gases.inv.name_for['Ne']
'neon'
>>> noble_gases.inv.symbol_for['neon']
'Ne'
Pickling works::
>>> from pickle import dumps, loads
>>> loads(dumps(noble_gases)) == noble_gases
True
Invalid names are rejected::
>>> invalid = namedbidict('0xabad1d3a', 'keys', 'vals')
Traceback (most recent call last):
...
ValueError: "0xabad1d3a" does not match pattern ^[a-zA-Z][a-zA-Z0-9_]*$
Comparison works as expected::
>>> from bidict import bidict
>>> noble_gases2 = ElementMap({'Ne': 'neon'})
>>> noble_gases2 == noble_gases
True
>>> noble_gases2 == bidict(noble_gases)
True
>>> noble_gases2 == dict(noble_gases)
True
>>> noble_gases2['Rn'] = 'radon'
>>> noble_gases2 == noble_gases
False
>>> noble_gases2 != noble_gases
True
>>> noble_gases2 != bidict(noble_gases)
True
>>> noble_gases2 != dict(noble_gases)
True
Test ``base_type`` keyword arg::
>>> from bidict import frozenbidict
>>> ElMap = namedbidict('ElMap', 'sym', 'el', base_type=frozenbidict)
>>> noble = ElMap(He='helium')
>>> hash(noble) is not 'an exception'
True
>>> noble['C'] = 'carbon'
Traceback (most recent call last):
...
TypeError...