A non-persistent example database, implemented in terms of an in-memory dictionary. This can be useful if you call a test function several times in a single session, or for testing other database implementations, but because it does not persist between runs we do not recommend it fo
| 366 | |
| 367 | |
| 368 | class InMemoryExampleDatabase(ExampleDatabase): |
| 369 | """A non-persistent example database, implemented in terms of an in-memory |
| 370 | dictionary. |
| 371 | |
| 372 | This can be useful if you call a test function several times in a single |
| 373 | session, or for testing other database implementations, but because it |
| 374 | does not persist between runs we do not recommend it for general use. |
| 375 | """ |
| 376 | |
| 377 | def __init__(self) -> None: |
| 378 | super().__init__() |
| 379 | self.data: dict[bytes, set[bytes]] = {} |
| 380 | |
| 381 | def __repr__(self) -> str: |
| 382 | return f"InMemoryExampleDatabase({self.data!r})" |
| 383 | |
| 384 | def __eq__(self, other: object) -> bool: |
| 385 | return isinstance(other, InMemoryExampleDatabase) and self.data is other.data |
| 386 | |
| 387 | def fetch(self, key: bytes) -> Iterable[bytes]: |
| 388 | yield from self.data.get(key, ()) |
| 389 | |
| 390 | def save(self, key: bytes, value: bytes) -> None: |
| 391 | value = bytes(value) |
| 392 | values = self.data.setdefault(key, set()) |
| 393 | changed = value not in values |
| 394 | values.add(value) |
| 395 | |
| 396 | if changed: |
| 397 | self._broadcast_change(("save", (key, value))) |
| 398 | |
| 399 | def delete(self, key: bytes, value: bytes) -> None: |
| 400 | value = bytes(value) |
| 401 | values = self.data.get(key, set()) |
| 402 | changed = value in values |
| 403 | values.discard(value) |
| 404 | |
| 405 | if changed: |
| 406 | self._broadcast_change(("delete", (key, value))) |
| 407 | |
| 408 | def _start_listening(self) -> None: |
| 409 | # declare compatibility with the listener api, but do the actual |
| 410 | # implementation in .delete and .save, since we know we are the only |
| 411 | # writer to .data. |
| 412 | pass |
| 413 | |
| 414 | def _stop_listening(self) -> None: |
| 415 | pass |
| 416 | |
| 417 | |
| 418 | def _hash(key: bytes) -> str: |
no outgoing calls