Debian Codegraph @

tests/redis_config.py

raw
1 from __future__ import annotations
2
3 from collections.abc import Sequence
4 from dataclasses import dataclass
5
6 from redis import Redis
7 from redis.exceptions import RedisError
8
9
10 @dataclass(frozen=True)
11 class RedisConfig:
12 host: str
13 port: int
14 db: int
15
16
17 def _find_empty_databases(host: str, port: int, *, required: int) -> Sequence[int]:
18 """
19 Find a set of empty Redis databases that can be used for tests.
20
21 Raises RuntimeError if we cannot connect or if we cannot find the requested
22 number of empty databases. Sentinel ports are intentionally not probed.
23 """
24
25 empty_databases: list[int] = []
26
27 for db in range(16):
28 try:
29 if Redis(host=host, port=port, db=db).dbsize() == 0:
30 empty_databases.append(db)
31 if len(empty_databases) == required:
32 break
33 except RedisError as exc: # pragma: no cover - defensive guard
34 raise RuntimeError(
35 f"Refusing to run tests: unable to inspect Redis database {db} on {host}:{port}"
36 ) from exc
37
38 if len(empty_databases) < required:
39 raise RuntimeError(
40 f"Refusing to run tests: need {required} empty Redis databases on {host}:{port}, "
41 f"but only found {len(empty_databases)}."
42 )
43
44 return empty_databases
45
46
47 REDIS_HOST = 'localhost'
48 REDIS_PORT = 6379
49 databases = _find_empty_databases(REDIS_HOST, REDIS_PORT, required=3)
50
51 REDIS_CONFIG_1 = RedisConfig(
52 host=REDIS_HOST,
53 port=REDIS_PORT,
54 db=databases[0],
55 )
56 REDIS_CONFIG_2 = RedisConfig(
57 host=REDIS_HOST,
58 port=REDIS_PORT,
59 db=databases[1],
60 )
61 REDIS_CONFIG_3 = RedisConfig(
62 host=REDIS_HOST,
63 port=REDIS_PORT,
64 db=databases[2],
65 )