skipcheck-tm1-testcontainers 0.1.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ """Testcontainers for IBM Planning Analytics (TM1): TM1 Server, the Admin Server, TM1 Web,
2
+ Planning Analytics Workspace, Cognos Analytics and Keycloak in Docker, for tests. The Python port
3
+ of the Java ``tm1-testcontainers`` module, on testcontainers-python.
4
+
5
+ No IBM software is included: a source (:class:`Tm1Source` and the others) supplies it.
6
+ """
7
+
8
+ from ._container import GenericContainer, Network, docker_available, reuse_enabled
9
+ from .cognos import CognosContainer, KeycloakContainer, Namespace, User
10
+ from .environment import PlanningAnalyticsEnvironment
11
+ from .paw import PawContainer, PawSession
12
+ from .requires import RequiresCognos, RequiresPaw, RequiresTm1, RequiresTm1Web
13
+ from .sources import CognosSource, PawSource, Tm1Source, Tm1WebSource
14
+ from .tm1 import Tm1AdminServerContainer, Tm1Seed, Tm1ServerContainer
15
+ from .web import Tm1WebContainer
16
+
17
+ __all__ = [
18
+ "CognosContainer",
19
+ "CognosSource",
20
+ "GenericContainer",
21
+ "KeycloakContainer",
22
+ "Namespace",
23
+ "Network",
24
+ "PawContainer",
25
+ "PawSession",
26
+ "PawSource",
27
+ "PlanningAnalyticsEnvironment",
28
+ "RequiresCognos",
29
+ "RequiresPaw",
30
+ "RequiresTm1",
31
+ "RequiresTm1Web",
32
+ "Tm1AdminServerContainer",
33
+ "Tm1Seed",
34
+ "Tm1ServerContainer",
35
+ "Tm1Source",
36
+ "Tm1WebContainer",
37
+ "Tm1WebSource",
38
+ "User",
39
+ "docker_available",
40
+ "reuse_enabled",
41
+ ]
@@ -0,0 +1,392 @@
1
+ """What Testcontainers for Java's ``GenericContainer`` gives the Java classes and
2
+ testcontainers-python's ``DockerContainer`` lacks: configuring without Docker (a container is
3
+ set up before it connects, so wiring can be tested anywhere), dependencies started first,
4
+ Java's ``configure`` and ``containerIsStarted`` hooks, reuse, extra hosts, and a lazily created
5
+ network.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import io
12
+ import json
13
+ import logging
14
+ import os
15
+ import shlex
16
+ import tarfile
17
+ import threading
18
+ import uuid
19
+ from collections.abc import Callable
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from testcontainers.core.config import testcontainers_config as tc_config
24
+ from testcontainers.core.container import DockerContainer, Reaper
25
+ from testcontainers.core.docker_client import DockerClient, get_docker_host
26
+ from testcontainers.core.labels import LABEL_SESSION_ID, create_labels
27
+ from testcontainers.core.network import Network as _TcNetwork
28
+ from testcontainers.core.transferable import Transferable, build_transfer_tar
29
+ from testcontainers.core.wait_strategies import HttpWaitStrategy
30
+ from typing_extensions import Self
31
+
32
+ __all__ = ["GenericContainer", "Network", "docker_available", "reuse_enabled"]
33
+
34
+ REUSE_HASH_LABEL = "io.skipcheck.tm1.testcontainers.hash"
35
+
36
+
37
+ class Network(_TcNetwork):
38
+ """A Docker network, created when a container first starts on it, as Java's
39
+ ``Network.newNetwork()``; testcontainers-python's own :class:`~testcontainers.core.network.Network`
40
+ works too."""
41
+
42
+ def __init__(self, docker_client_kw: dict[str, Any] | None = None, docker_network_kw: dict[str, Any] | None = None) -> None:
43
+ # testcontainers-python's connects to Docker here; Java's waits until it's used
44
+ self.name = str(uuid.uuid4())
45
+ self._docker_client_kw = docker_client_kw or {}
46
+ self._lazy_docker: DockerClient | None = None
47
+ self._docker_network_kw = docker_network_kw or {}
48
+ self._network = None
49
+
50
+ @property # type: ignore[override]
51
+ def _docker(self) -> DockerClient:
52
+ if self._lazy_docker is None:
53
+ self._lazy_docker = DockerClient(**self._docker_client_kw)
54
+ return self._lazy_docker
55
+
56
+ @staticmethod
57
+ def new_network() -> Network:
58
+ return Network()
59
+
60
+ def close(self) -> None:
61
+ """Removes the network, if it was created."""
62
+ if self._network is not None:
63
+ try:
64
+ self.remove()
65
+ finally:
66
+ self._network = None
67
+
68
+
69
+ def _ensure_created(network: _TcNetwork) -> None:
70
+ if getattr(network, "_network", None) is None:
71
+ network.create()
72
+
73
+
74
+ def reuse_enabled() -> bool:
75
+ """Whether reusable containers are reused, as in Java: ``testcontainers.reuse.enable=true``
76
+ in ``~/.testcontainers.properties``, or ``TESTCONTAINERS_REUSE_ENABLE=true``."""
77
+ value = os.environ.get("TESTCONTAINERS_REUSE_ENABLE") or tc_config.tc_properties.get("testcontainers.reuse.enable", "")
78
+ return value.strip().lower() == "true"
79
+
80
+
81
+ def docker_available() -> bool:
82
+ """Whether Docker answers, as Java's ``DockerClientFactory.isDockerAvailable()``."""
83
+ try:
84
+ client = DockerClient()
85
+ try:
86
+ return bool(client.client.ping())
87
+ finally:
88
+ client.client.close()
89
+ except Exception: # noqa: BLE001 - no Docker, however it shows
90
+ return False
91
+
92
+
93
+ class _HttpWait(HttpWaitStrategy):
94
+ """Java's ``Wait.forHttp``: and, unlike testcontainers-python's, it stops waiting when the
95
+ container has exited."""
96
+
97
+ def __init__(self, port: int, path: str) -> None:
98
+ super().__init__(port, path)
99
+ self._container: Any = None
100
+
101
+ def wait_until_ready(self, container: Any) -> None:
102
+ self._container = container
103
+ super().wait_until_ready(container)
104
+
105
+ def _try_http_request(self, url: str, headers: dict[str, str], ssl_context: Any) -> bool:
106
+ if self._container is not None:
107
+ self._container.reload()
108
+ if self._container.status in ("exited", "dead"):
109
+ out, err = self._container.get_logs()
110
+ raise RuntimeError(f"The container stopped while starting:\n{(out + err).decode(errors='replace')[-4000:]}")
111
+ return super()._try_http_request(url, headers, ssl_context)
112
+
113
+
114
+ def wait_for_http(path: str, port: int, *codes: int, timeout: float, accept: Callable[[int], bool] | None = None) -> HttpWaitStrategy:
115
+ strategy = _HttpWait(port, path).with_startup_timeout(int(timeout))
116
+ strategy._status_codes = set(codes) or {200}
117
+ if accept is not None:
118
+ strategy.for_status_code_matching(accept)
119
+ return strategy
120
+
121
+
122
+ class GenericContainer(DockerContainer):
123
+ """A container, as Testcontainers for Java's ``GenericContainer``: configured without Docker,
124
+ started with its dependencies, and reusable."""
125
+
126
+ _log = logging.getLogger("skipcheck_tm1_testcontainers")
127
+
128
+ def __init__(self, image: str, docker_client_kw: dict[str, Any] | None = None) -> None:
129
+ # DockerContainer's attributes, without its connecting to Docker: Java's containers are
130
+ # set up before anything talks to Docker
131
+ self.env: dict[str, str] = {}
132
+ self.ports: dict[str, int | None] = {}
133
+ self.volumes: dict[str, Any] = {}
134
+ self.tmpfs: dict[str, str] = {}
135
+ self.image = tc_config.hub_image_name_prefix + image
136
+ self._docker_client_kw = docker_client_kw or {}
137
+ self._lazy_docker: DockerClient | None = None
138
+ self._container: Any = None
139
+ self._command: str | list[str] | None = None
140
+ self._name: str | None = None
141
+ self._network: _TcNetwork | None = None
142
+ self._network_aliases: list[str] | None = None
143
+ self._kwargs: dict[str, Any] = {}
144
+ self._wait_strategy: Any = None
145
+ self._cached_container_info: Any = None
146
+ self._transferable_specs: list[Any] = []
147
+ self._dependencies: list[Any] = []
148
+ self._reuse = False
149
+ self._labels: dict[str, str] = {}
150
+ self._extra_hosts: dict[str, str] = {}
151
+ self._lock = threading.RLock()
152
+
153
+ @property # type: ignore[override]
154
+ def _docker(self) -> DockerClient:
155
+ if self._lazy_docker is None:
156
+ self._lazy_docker = DockerClient(**self._docker_client_kw)
157
+ return self._lazy_docker
158
+
159
+ # --- Configuration ---------------------------------------------------------------------
160
+
161
+ def with_network_aliases(self, *aliases: str) -> Self:
162
+ """Adds aliases, as Java does (testcontainers-python's replaces them)."""
163
+ self._network_aliases = [*(self._network_aliases or []), *aliases]
164
+ return self
165
+
166
+ def with_kwargs(self, **kwargs: Any) -> Self:
167
+ """Adds ``docker create`` arguments (testcontainers-python's replaces them)."""
168
+ self._kwargs.update(kwargs)
169
+ return self
170
+
171
+ def with_platform(self, platform: str) -> Self:
172
+ self._kwargs["platform"] = platform
173
+ return self
174
+
175
+ def with_extra_host(self, hostname: str, address: str) -> Self:
176
+ self._extra_hosts[hostname] = address
177
+ return self
178
+
179
+ def with_label(self, key: str, value: str) -> Self:
180
+ self._labels[key] = value
181
+ return self
182
+
183
+ def with_reuse(self, reuse: bool) -> Self:
184
+ """Keeps the container for later runs, when reuse is enabled (:func:`reuse_enabled`):
185
+ a later start with the same settings finds it and uses it."""
186
+ self._reuse = reuse
187
+ return self
188
+
189
+ def depends_on(self, *containers: Any) -> Self:
190
+ """Containers started before this one."""
191
+ for container in containers:
192
+ if container not in self._dependencies:
193
+ self._dependencies.append(container)
194
+ return self
195
+
196
+ @property
197
+ def dependencies(self) -> list[Any]:
198
+ return list(self._dependencies)
199
+
200
+ @property
201
+ def network(self) -> _TcNetwork | None:
202
+ return self._network
203
+
204
+ @property
205
+ def network_aliases(self) -> list[str]:
206
+ return list(self._network_aliases or [])
207
+
208
+ @property
209
+ def env_map(self) -> dict[str, str]:
210
+ return self.env
211
+
212
+ @property
213
+ def command_parts(self) -> list[str]:
214
+ if self._command is None:
215
+ return []
216
+ return shlex.split(self._command) if isinstance(self._command, str) else list(self._command)
217
+
218
+ @property
219
+ def should_be_reused(self) -> bool:
220
+ return self._reuse
221
+
222
+ def configure(self) -> None:
223
+ """Last settings before the container is created: Java's ``configure()``."""
224
+
225
+ def container_is_started(self) -> None:
226
+ """Once the container is up: Java's ``containerIsStarted``."""
227
+
228
+ # --- Running ---------------------------------------------------------------------------
229
+
230
+ @property
231
+ def is_running(self) -> bool:
232
+ if self._container is None:
233
+ return False
234
+ try:
235
+ self._container.reload()
236
+ except Exception: # noqa: BLE001 - gone
237
+ return False
238
+ return bool(self._container.status == "running")
239
+
240
+ @property
241
+ def host(self) -> str:
242
+ return self.get_container_host_ip()
243
+
244
+ def get_mapped_port(self, port: int) -> int:
245
+ return int(self.get_exposed_port(port))
246
+
247
+ @property
248
+ def container_id(self) -> str:
249
+ return self.get_container_id()
250
+
251
+ @property
252
+ def container_info(self) -> dict[str, Any]:
253
+ """``docker inspect`` of the container: Java's ``getContainerInfo()``."""
254
+ if self._container is None:
255
+ raise RuntimeError("The container isn't started yet")
256
+ self._container.reload()
257
+ return dict(self._container.attrs)
258
+
259
+ @property
260
+ def logger(self) -> logging.Logger:
261
+ return self._log
262
+
263
+ def start(self) -> Self:
264
+ with self._lock:
265
+ if self._container is not None and self.is_running:
266
+ return self
267
+ for dependency in self._dependencies:
268
+ if not dependency.is_running:
269
+ dependency.start()
270
+ self.configure()
271
+ if self._network is not None:
272
+ _ensure_created(self._network)
273
+ reuse = self._reuse and reuse_enabled()
274
+ if not reuse and not tc_config.ryuk_disabled:
275
+ Reaper.get_instance()
276
+ client = self.get_docker_client()
277
+ kwargs: dict[str, Any] = dict(self._kwargs)
278
+ if self._network is not None:
279
+ from docker import version
280
+ from docker.types import EndpointConfig
281
+
282
+ kwargs["network"] = self._network.name
283
+ kwargs["networking_config"] = {self._network.name: EndpointConfig(version.__version__, aliases=self._network_aliases)}
284
+ if self._extra_hosts:
285
+ kwargs["extra_hosts"] = {**kwargs.get("extra_hosts", {}), **self._extra_hosts}
286
+ if self.volumes:
287
+ kwargs["volumes"] = {host: {"bind": m["bind"], "mode": m["mode"]} for host, m in self.volumes.items()}
288
+ if self.tmpfs:
289
+ kwargs["tmpfs"] = self.tmpfs
290
+ if "network" not in kwargs and not get_docker_host():
291
+ host_network = client.find_host_network()
292
+ if host_network:
293
+ kwargs["network"] = host_network
294
+ labels = create_labels(self.image, self._labels)
295
+ existing = None
296
+ if reuse:
297
+ # Not reaped at the end of the session, and found again by its settings
298
+ labels.pop(LABEL_SESSION_ID, None)
299
+ labels[REUSE_HASH_LABEL] = self._hash(kwargs)
300
+ found = client.client.containers.list(filters={"label": f"{REUSE_HASH_LABEL}={labels[REUSE_HASH_LABEL]}", "status": "running"})
301
+ existing = found[0] if found else None
302
+ self._cached_container_info = None
303
+ if existing is not None:
304
+ self._log.info("Reusing container %s (%s)", existing.short_id, self.image)
305
+ self._container = existing
306
+ else:
307
+ self._log.info("Starting a container of %s", self.image)
308
+ import docker.errors
309
+
310
+ try:
311
+ client.client.images.get(self.image)
312
+ except docker.errors.ImageNotFound:
313
+ client.client.images.pull(self.image, platform=kwargs.get("platform"))
314
+ self._container = client.client.containers.create(
315
+ self.image,
316
+ command=self._command,
317
+ environment=self.env,
318
+ ports=self.ports,
319
+ name=self._name,
320
+ labels=labels,
321
+ **kwargs,
322
+ )
323
+ for spec in self._transferable_specs:
324
+ self._transfer_into_container(*spec)
325
+ self._container.start()
326
+ try:
327
+ if self._wait_strategy is not None:
328
+ self._wait_strategy.wait_until_ready(self)
329
+ self.container_is_started()
330
+ except BaseException:
331
+ if existing is None:
332
+ self.stop()
333
+ raise
334
+ return self
335
+
336
+ def stop(self, force: bool = True, delete_volume: bool = True) -> None:
337
+ with self._lock:
338
+ if self._container is not None:
339
+ import docker.errors
340
+
341
+ try:
342
+ self._container.remove(force=force, v=delete_volume)
343
+ except docker.errors.NotFound:
344
+ pass
345
+ self._container = None
346
+ self._cached_container_info = None
347
+
348
+ def close(self) -> None:
349
+ self.stop()
350
+
351
+ def __exit__(self, *exc: Any) -> None:
352
+ self.stop()
353
+
354
+ def _hash(self, kwargs: dict[str, Any]) -> str:
355
+ config = {
356
+ "image": self.image,
357
+ "command": self._command,
358
+ "env": self.env,
359
+ "ports": sorted(self.ports),
360
+ "labels": self._labels,
361
+ "kwargs": {k: v for k, v in kwargs.items() if k != "networking_config"},
362
+ "aliases": self._network_aliases,
363
+ "copies": [(str(t), dest) for t, dest, *_ in self._transferable_specs],
364
+ }
365
+ return hashlib.sha256(json.dumps(config, sort_keys=True, default=str).encode()).hexdigest()
366
+
367
+ def _transfer_into_container(self, transferable: Transferable, destination_in_container: str, mode: int) -> None:
368
+ # Java's MountableFile: a folder copied to a path is that path, so its contents go in it
369
+ if isinstance(transferable, Path) and transferable.is_dir():
370
+ buf = io.BytesIO()
371
+ with tarfile.open(fileobj=buf, mode="w") as tar:
372
+ for child in sorted(transferable.iterdir()):
373
+ tar.add(str(child), arcname=f"{destination_in_container.strip('/')}/{child.name}")
374
+ data = buf.getvalue()
375
+ else:
376
+ data = build_transfer_tar(transferable, destination_in_container, mode)
377
+ if not self._container.put_archive(path="/", data=data):
378
+ raise OSError(f"Failed to put archive into container at {destination_in_container}")
379
+
380
+
381
+ def share_network(a: GenericContainer, b: GenericContainer) -> None:
382
+ """Puts two containers that work together on one network: whichever either has, or a new one."""
383
+ network = a.network if a.network is not None else b.network
384
+ if network is None:
385
+ network = Network.new_network()
386
+ for container in (a, b):
387
+ if container.network is None:
388
+ container.with_network(network)
389
+ elif container.network is not network:
390
+ raise RuntimeError(
391
+ f"Containers that work together must share one Network, but {type(container).__name__} is on another. Give them the same Network."
392
+ )
@@ -0,0 +1,250 @@
1
+ """Cognos Analytics and Keycloak in Docker, for TM1 in CAM security: Java's ``CognosContainer``
2
+ and ``KeycloakContainer``."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ import enum
8
+ import json
9
+ import re
10
+ from dataclasses import dataclass, field
11
+ from typing import ClassVar
12
+
13
+ import httpx
14
+ from typing_extensions import Self
15
+
16
+ from ._container import GenericContainer, share_network, wait_for_http
17
+ from .sources import CognosSource, setting
18
+ from .tm1 import default_image
19
+
20
+ __all__ = ["CognosContainer", "KeycloakContainer", "Namespace", "User"]
21
+
22
+ NO_SOURCE_MESSAGE = (
23
+ "No Cognos source configured. Set one of COGNOS_PRIVATE_IMAGE, COGNOS_INSTALL_VOLUME, COGNOS_ZIP_DIR or "
24
+ "COGNOS_ZIP_URL, or put a casrv-*-linuxi38664h.zip in TM1_BUNDLE_DIR (as an environment variable or system "
25
+ "property) to run tests against Cognos."
26
+ )
27
+ """Java's ``RequiresCognos.NO_SOURCE_MESSAGE``."""
28
+
29
+ _NAME = re.compile(r"[A-Za-z0-9._-]+\Z")
30
+ _INSTALL_PATH = "/opt/ibm/cognos/analytics"
31
+ _STARTUP_TIMEOUT = 15 * 60.0
32
+
33
+
34
+ class Namespace(enum.Enum):
35
+ """A Cognos namespace TM1 can authenticate against."""
36
+
37
+ LDAP = "LDAP"
38
+ """The image's own LDAP, holding the test users."""
39
+ OIDC = "OIDC"
40
+ """Keycloak, through OpenID Connect: needs :meth:`CognosContainer.with_keycloak`."""
41
+
42
+ @property
43
+ def id(self) -> str:
44
+ """The namespace's ID: the ``CAMNamespace`` users log on with."""
45
+ return str(self.value)
46
+
47
+ @property
48
+ def type(self) -> str:
49
+ """The image's ``TM1_CAM_NAMESPACE_TYPE``."""
50
+ return str(self.value).lower()
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class User:
55
+ """A Cognos test user."""
56
+
57
+ name: str
58
+ password: str
59
+ groups: tuple[str, ...] = field(default_factory=tuple)
60
+
61
+ def __post_init__(self) -> None:
62
+ object.__setattr__(self, "groups", tuple(self.groups))
63
+
64
+
65
+ def _require_name(name: str, what: str) -> None:
66
+ if name is None or not _NAME.match(name):
67
+ raise ValueError(f"Bad {what} '{name}': use letters, digits, '.', '_' and '-'")
68
+
69
+
70
+ class CognosContainer(GenericContainer):
71
+ """Cognos Analytics in Docker, from the ``cognos-server`` image and a :class:`CognosSource`,
72
+ with test users in its LDAP namespace (:meth:`with_user`)."""
73
+
74
+ DEFAULT_IMAGE: ClassVar[str] = "ghcr.io/ajmyers/cognos-server"
75
+ SERVER_IMAGE: ClassVar[str] = "COGNOS_SERVER_IMAGE"
76
+ DISPATCHER_PORT: ClassVar[int] = 9300
77
+ NETWORK_ALIAS: ClassVar[str] = "cognos"
78
+ NAMESPACE: ClassVar[str] = "LDAP"
79
+
80
+ Namespace: ClassVar[type[Namespace]] = Namespace
81
+ User: ClassVar[type[User]] = User
82
+
83
+ def __init__(self, source: CognosSource, image: str | None = None) -> None:
84
+ if source is None:
85
+ raise ValueError("source must not be None")
86
+ super().__init__(image or default_image(source, self.DEFAULT_IMAGE, self.SERVER_IMAGE))
87
+ self._source = source
88
+ self._users: dict[str, User] = {}
89
+ self._keycloak: KeycloakContainer | None = None
90
+ self.with_exposed_ports(self.DISPATCHER_PORT)
91
+ self.with_network_aliases(self.NETWORK_ALIAS)
92
+ self.with_env("COGNOS_HOST", self.NETWORK_ALIAS)
93
+ # Cognos for Linux is x86-64 only. On Apple Silicon this runs under Rosetta.
94
+ self.with_platform("linux/amd64").with_kwargs(hostname=self.NETWORK_ALIAS)
95
+ # The image's healthcheck: 200 (anonymous session) or 441 (logon prompt, with users)
96
+ self.waiting_for(wait_for_http("/bi/v1/login", self.DISPATCHER_PORT, 200, 441, timeout=_STARTUP_TIMEOUT))
97
+ if isinstance(source, CognosSource.InstallVolume):
98
+ self.with_volume_mapping(source.name, _INSTALL_PATH, "rw")
99
+ elif isinstance(source, CognosSource.Zip):
100
+ self.with_volume_mapping(str(source.dir), "/ibm", "ro")
101
+ if source.file is not None:
102
+ self.with_env("COGNOS_ZIP", source.file)
103
+ elif isinstance(source, CognosSource.ZipUrl):
104
+ self.with_env("COGNOS_ZIP_URL", source.url)
105
+ if source.sha256 is not None:
106
+ self.with_env("COGNOS_ZIP_SHA256", source.sha256)
107
+ # CognosSource.PrivateImage: Cognos is already in the image
108
+
109
+ def with_user(self, name: str, password: str, *groups: str) -> Self:
110
+ """Adds a test user to the LDAP namespace, in groups that are created as needed."""
111
+ _require_name(name, "user name")
112
+ if password is None:
113
+ raise ValueError("password must not be None")
114
+ if not password or ":" in password or any(c.isspace() for c in password):
115
+ raise ValueError(f"The password for {name} must be non-empty, without ':' or spaces")
116
+ for group in groups:
117
+ _require_name(group, "group name")
118
+ if name in self._users:
119
+ raise ValueError(f"User {name} was already added")
120
+ self._users[name] = User(name, password, tuple(groups))
121
+ return self
122
+
123
+ def with_keycloak(self, keycloak: KeycloakContainer) -> Self:
124
+ """Adds an OIDC namespace backed by Keycloak, on one network with it."""
125
+ if keycloak is None:
126
+ raise ValueError("keycloak must not be None")
127
+ self._keycloak = keycloak
128
+ share_network(self, keycloak)
129
+ self.depends_on(keycloak)
130
+ self.with_env("COGNOS_KEYCLOAK_URL", keycloak.network_url)
131
+ return self
132
+
133
+ @property
134
+ def keycloak(self) -> KeycloakContainer | None:
135
+ """The Keycloak set with :meth:`with_keycloak`, or None if there's no OIDC namespace."""
136
+ return self._keycloak
137
+
138
+ @property
139
+ def users(self) -> list[User]:
140
+ """The test users, in the order they were added."""
141
+ return list(self._users.values())
142
+
143
+ def get_user(self, name: str) -> User:
144
+ """A test user by name. A ValueError if there's no such user."""
145
+ user = self._users.get(name)
146
+ if user is None:
147
+ raise ValueError(f"No test user {name}; add it with with_user")
148
+ return user
149
+
150
+ @property
151
+ def groups(self) -> list[str]:
152
+ """Every test user's groups, once each, in the order they were added."""
153
+ return list(dict.fromkeys(g for user in self._users.values() for g in user.groups))
154
+
155
+ @property
156
+ def source(self) -> CognosSource:
157
+ """Where Cognos comes from."""
158
+ return self._source
159
+
160
+ @property
161
+ def url(self) -> str:
162
+ """Cognos as seen from the host, such as ``http://localhost:54321/bi/``, ending in ``/``."""
163
+ return f"http://{self.host}:{self.get_mapped_port(self.DISPATCHER_PORT)}/bi/"
164
+
165
+ @property
166
+ def network_url(self) -> str:
167
+ """The dispatcher, as other containers on the network reach it."""
168
+ return f"http://{self.NETWORK_ALIAS}:{self.DISPATCHER_PORT}"
169
+
170
+ def cam_authorization(self, user: str, namespace: Namespace = Namespace.LDAP) -> str:
171
+ """A test user's ``CAMNamespace`` logon, for TM1 in CAM security."""
172
+ return CognosContainer.cam_authorization_for(user, self.get_user(user).password, namespace.id)
173
+
174
+ def passport(self, id_token: str) -> str:
175
+ """A CAM passport for an OIDC ID token (from :meth:`KeycloakContainer.id_token`)."""
176
+ body = json.dumps({"parameters": [{"name": "CAMNamespace", "value": Namespace.OIDC.id}, {"name": "CAMOIDCIdToken", "value": id_token}]})
177
+ url = f"http://{self.host}:{self.get_mapped_port(self.DISPATCHER_PORT)}/api/v1/session"
178
+ response = httpx.put(url, content=body, headers={"Content-Type": "application/json"}, timeout=60)
179
+ passport = response.cookies.get("cam_passport")
180
+ if passport is None:
181
+ raise RuntimeError(f"Cognos refused the ID token (HTTP {response.status_code}): {response.text}")
182
+ return passport
183
+
184
+ @staticmethod
185
+ def cam_authorization_for(user: str, password: str, namespace: str) -> str:
186
+ """``CAMNamespace`` with ``user:password:namespace``: Java's static ``camAuthorization``."""
187
+ return "CAMNamespace " + base64.b64encode(f"{user}:{password}:{namespace}".encode()).decode("ascii")
188
+
189
+ def users_spec(self) -> str:
190
+ """The users as the image's ``COGNOS_USERS`` takes them."""
191
+ return " ".join(u.name + ":" + u.password + (":" + ",".join(u.groups) if u.groups else "") for u in self._users.values())
192
+
193
+ def configure(self) -> None:
194
+ """Called by testcontainers before the container is created: passes the test users to the
195
+ image as ``COGNOS_USERS``."""
196
+ if self._users:
197
+ self.with_env("COGNOS_USERS", self.users_spec())
198
+
199
+ def container_is_started(self) -> None:
200
+ """Called once the container is up: logs where it is and what it came from."""
201
+ self.logger.info("Cognos is up at %s (%s), with %d test user(s) in namespace %s", self.url, self._source.describe(), len(self._users), self.NAMESPACE)
202
+
203
+
204
+ class KeycloakContainer(GenericContainer):
205
+ """Keycloak, for Cognos's OIDC namespace (:meth:`CognosContainer.with_keycloak`). The image
206
+ loads the ``cognos`` realm itself."""
207
+
208
+ DEFAULT_IMAGE: ClassVar[str] = "quay.io/keycloak/keycloak:26.4"
209
+ IMAGE: ClassVar[str] = "KEYCLOAK_IMAGE"
210
+ HTTP_PORT: ClassVar[int] = 8080
211
+ NETWORK_ALIAS: ClassVar[str] = "keycloak"
212
+ REALM: ClassVar[str] = "cognos"
213
+ APP_CLIENT: ClassVar[str] = "tm1-app"
214
+
215
+ def __init__(self, image: str | None = None) -> None:
216
+ override = setting(self.IMAGE)
217
+ super().__init__(image or (override.strip() if override and override.strip() else self.DEFAULT_IMAGE))
218
+ self.with_command(["start-dev"])
219
+ self.with_exposed_ports(self.HTTP_PORT)
220
+ self.with_network_aliases(self.NETWORK_ALIAS)
221
+ self.with_env("KC_BOOTSTRAP_ADMIN_USERNAME", "admin")
222
+ self.with_env("KC_BOOTSTRAP_ADMIN_PASSWORD", "admin")
223
+ self.with_env("KC_HTTP_ENABLED", "true")
224
+ # One issuer for Cognos and the tests, whichever address they use
225
+ self.with_env("KC_HOSTNAME", self.network_url)
226
+ self.waiting_for(wait_for_http("/realms/master", self.HTTP_PORT, 200, timeout=3 * 60.0))
227
+
228
+ @property
229
+ def network_url(self) -> str:
230
+ """Keycloak as other containers on its network reach it: ``http://keycloak:8080``. Also its
231
+ issuer's base. No trailing slash."""
232
+ return f"http://{self.NETWORK_ALIAS}:{self.HTTP_PORT}"
233
+
234
+ @property
235
+ def url(self) -> str:
236
+ """Keycloak as seen from the host, such as ``http://localhost:54321``, without a trailing
237
+ slash. Its admin console logs on as ``admin`` / ``admin``."""
238
+ return f"http://{self.host}:{self.get_mapped_port(self.HTTP_PORT)}"
239
+
240
+ def id_token(self, user: str, password: str) -> str:
241
+ """An ID token for a user of the realm, by password."""
242
+ response = httpx.post(
243
+ f"{self.url}/realms/{self.REALM}/protocol/openid-connect/token",
244
+ data={"grant_type": "password", "client_id": self.APP_CLIENT, "scope": "openid", "username": user, "password": password},
245
+ timeout=30,
246
+ )
247
+ match = re.search(r'"id_token"\s*:\s*"([^"]+)"', response.text)
248
+ if response.status_code != 200 or match is None:
249
+ raise RuntimeError(f"Keycloak refused {user} (HTTP {response.status_code}): {response.text}")
250
+ return match.group(1)