Add ImmutableDict

This commit is contained in:
Florian Bruhin 2014-05-05 18:48:38 +02:00
parent c561931699
commit 938fbd5608
2 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,44 @@
# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
# pylint: disable=missing-docstring
"""Tests for the FakeDict class."""
import unittest
from unittest import TestCase
from qutebrowser.utils.usertypes import ImmutableDict
class ImmutableDictTests(TestCase):
"""Test the ImmutableDict usertype."""
def setUp(self):
self.d = ImmutableDict()
def test_setitem(self):
self.d['foo'] = 'bar'
self.assertEqual(self.d['foo'], 'bar')
with self.assertRaises(ValueError):
self.d['foo'] = 'baz'
self.assertEqual(self.d['foo'], 'bar')
if __name__ == '__main__':
unittest.main()

View File

@ -182,3 +182,13 @@ class FakeDict:
def __getitem__(self, _key): def __getitem__(self, _key):
return self._val return self._val
class ImmutableDict(dict):
"""Dict where items only can be set once."""
def __setitem__(self, key, value):
if key in self:
raise ValueError("Key {} already has been set.".format(key))
super().__setitem__(key, value)