(self)
| 167 | self.assertEqual(s._protocol, pickle.DEFAULT_PROTOCOL) |
| 168 | |
| 169 | def test_custom_serializer_and_deserializer(self): |
| 170 | os.mkdir(self.dirname) |
| 171 | self.addCleanup(os_helper.rmtree, self.dirname) |
| 172 | |
| 173 | def serializer(obj, protocol): |
| 174 | if isinstance(obj, (bytes, bytearray, str)): |
| 175 | if protocol == 5: |
| 176 | if isinstance(obj, bytearray): |
| 177 | return bytes(obj) # DBM backends expect bytes |
| 178 | return obj |
| 179 | return type(obj).__name__ |
| 180 | elif isinstance(obj, array.array): |
| 181 | return obj.tobytes() |
| 182 | raise TypeError(f"Unsupported type for serialization: {type(obj)}") |
| 183 | |
| 184 | def deserializer(data): |
| 185 | if isinstance(data, (bytes, bytearray, str)): |
| 186 | return data.decode("utf-8") |
| 187 | elif isinstance(data, array.array): |
| 188 | return array.array("b", data) |
| 189 | raise TypeError( |
| 190 | f"Unsupported type for deserialization: {type(data)}" |
| 191 | ) |
| 192 | |
| 193 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 194 | with self.subTest(proto=proto), shelve.open( |
| 195 | self.fn, |
| 196 | protocol=proto, |
| 197 | serializer=serializer, |
| 198 | deserializer=deserializer |
| 199 | ) as s: |
| 200 | bar = "bar" |
| 201 | bytes_data = b"Hello, world!" |
| 202 | bytearray_data = bytearray(b"\x00\x01\x02\x03\x04") |
| 203 | array_data = array.array("i", [1, 2, 3, 4, 5]) |
| 204 | |
| 205 | s["foo"] = bar |
| 206 | s["bytes_data"] = bytes_data |
| 207 | s["bytearray_data"] = bytearray_data |
| 208 | s["array_data"] = array_data |
| 209 | |
| 210 | if proto == 5: |
| 211 | self.assertEqual(s["foo"], str(bar)) |
| 212 | self.assertEqual(s["bytes_data"], "Hello, world!") |
| 213 | self.assertEqual( |
| 214 | s["bytearray_data"], bytearray_data.decode() |
| 215 | ) |
| 216 | self.assertEqual( |
| 217 | s["array_data"], array_data.tobytes().decode() |
| 218 | ) |
| 219 | else: |
| 220 | self.assertEqual(s["foo"], "str") |
| 221 | self.assertEqual(s["bytes_data"], "bytes") |
| 222 | self.assertEqual(s["bytearray_data"], "bytearray") |
| 223 | self.assertEqual( |
| 224 | s["array_data"], array_data.tobytes().decode() |
| 225 | ) |
| 226 |
nothing calls this directly
no test coverage detected