diff --git a/qutebrowser/test/test_immutabledict.py b/qutebrowser/test/test_immutabledict.py new file mode 100644 index 000000000..6aca6d9dd --- /dev/null +++ b/qutebrowser/test/test_immutabledict.py @@ -0,0 +1,44 @@ +# Copyright 2014 Florian Bruhin (The Compiler) +# +# 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 . + +# 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() diff --git a/qutebrowser/utils/usertypes.py b/qutebrowser/utils/usertypes.py index a67a24e49..94d0113ce 100644 --- a/qutebrowser/utils/usertypes.py +++ b/qutebrowser/utils/usertypes.py @@ -182,3 +182,13 @@ class FakeDict: def __getitem__(self, _key): 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)