diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2018-04-05 11:12:31 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-04-05 11:12:31 (GMT) |
commit | 83f564fd242c1af9dbe6d4273ad50586489000e3 (patch) | |
tree | ab6fa2b863aead26d0c48cf14fa40845d7d76dd7 | |
parent | 04eac02088f60192c7e54c7364bcaa892d7c05cf (diff) | |
download | cpython-83f564fd242c1af9dbe6d4273ad50586489000e3.zip cpython-83f564fd242c1af9dbe6d4273ad50586489000e3.tar.gz cpython-83f564fd242c1af9dbe6d4273ad50586489000e3.tar.bz2 |
Clean up and enhance frozen dataclass tests. (GH-6380)
* Add a test for frozen with unhashable field value.
* Improve a comment.
(cherry picked from commit 74940913d26d9f94b8572eca794369841fa6d9b6)
Co-authored-by: Eric V. Smith <ericvsmith@users.noreply.github.com>
-rwxr-xr-x | Lib/test/test_dataclasses.py | 65 |
1 files changed, 38 insertions, 27 deletions
diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py index 26bfc4e..2c890a2 100755 --- a/Lib/test/test_dataclasses.py +++ b/Lib/test/test_dataclasses.py @@ -2191,33 +2191,6 @@ class TestRepr(unittest.TestCase): self.assertEqual(repr(C(0)), 'x') -class TestFrozen(unittest.TestCase): - def test_overwriting_frozen(self): - # frozen uses __setattr__ and __delattr__. - with self.assertRaisesRegex(TypeError, - 'Cannot overwrite attribute __setattr__'): - @dataclass(frozen=True) - class C: - x: int - def __setattr__(self): - pass - - with self.assertRaisesRegex(TypeError, - 'Cannot overwrite attribute __delattr__'): - @dataclass(frozen=True) - class C: - x: int - def __delattr__(self): - pass - - @dataclass(frozen=False) - class C: - x: int - def __setattr__(self, name, value): - self.__dict__['x'] = value * 2 - self.assertEqual(C(10).x, 20) - - class TestEq(unittest.TestCase): def test_no_eq(self): # Test a class with no __eq__ and eq=False. @@ -2672,6 +2645,44 @@ class TestFrozen(unittest.TestCase): self.assertEqual(s.y, 10) self.assertEqual(s.cached, True) + def test_overwriting_frozen(self): + # frozen uses __setattr__ and __delattr__. + with self.assertRaisesRegex(TypeError, + 'Cannot overwrite attribute __setattr__'): + @dataclass(frozen=True) + class C: + x: int + def __setattr__(self): + pass + + with self.assertRaisesRegex(TypeError, + 'Cannot overwrite attribute __delattr__'): + @dataclass(frozen=True) + class C: + x: int + def __delattr__(self): + pass + + @dataclass(frozen=False) + class C: + x: int + def __setattr__(self, name, value): + self.__dict__['x'] = value * 2 + self.assertEqual(C(10).x, 20) + + def test_frozen_hash(self): + @dataclass(frozen=True) + class C: + x: Any + + # If x is immutable, we can compute the hash. No exception is + # raised. + hash(C(3)) + + # If x is mutable, computing the hash is an error. + with self.assertRaisesRegex(TypeError, 'unhashable type'): + hash(C({})) + class TestSlots(unittest.TestCase): def test_simple(self): |