testshed 0.0.1__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.
Files changed (37) hide show
  1. kloudkit/testshed/__init__.py +1 -0
  2. kloudkit/testshed/_internal/state.py +35 -0
  3. kloudkit/testshed/core/__init__.py +6 -0
  4. kloudkit/testshed/core/bootstrap.py +41 -0
  5. kloudkit/testshed/core/wrapper.py +42 -0
  6. kloudkit/testshed/docker/__init__.py +16 -0
  7. kloudkit/testshed/docker/container.py +51 -0
  8. kloudkit/testshed/docker/container_config.py +45 -0
  9. kloudkit/testshed/docker/decorators.py +23 -0
  10. kloudkit/testshed/docker/factory.py +68 -0
  11. kloudkit/testshed/docker/inline_volume.py +41 -0
  12. kloudkit/testshed/docker/probes/http_probe.py +23 -0
  13. kloudkit/testshed/docker/probes/readiness_check.py +48 -0
  14. kloudkit/testshed/docker/runtime/cleanup.py +30 -0
  15. kloudkit/testshed/docker/runtime/error_handler.py +33 -0
  16. kloudkit/testshed/docker/runtime/file_system.py +62 -0
  17. kloudkit/testshed/docker/runtime/shell.py +75 -0
  18. kloudkit/testshed/docker/volume_manager.py +48 -0
  19. kloudkit/testshed/fixtures/__init__.py +56 -0
  20. kloudkit/testshed/fixtures/docker.py +36 -0
  21. kloudkit/testshed/fixtures/playwright.py +29 -0
  22. kloudkit/testshed/fixtures/shed.py +69 -0
  23. kloudkit/testshed/playwright/__init__.py +4 -0
  24. kloudkit/testshed/playwright/factory.py +33 -0
  25. kloudkit/testshed/plugin/__init__.py +17 -0
  26. kloudkit/testshed/plugin/addoptions.py +89 -0
  27. kloudkit/testshed/plugin/configure.py +63 -0
  28. kloudkit/testshed/plugin/presenter.py +21 -0
  29. kloudkit/testshed/py.typed +0 -0
  30. kloudkit/testshed/utils/network.py +13 -0
  31. kloudkit/testshed/utils/version.py +33 -0
  32. testshed-0.0.1.dist-info/METADATA +176 -0
  33. testshed-0.0.1.dist-info/RECORD +37 -0
  34. testshed-0.0.1.dist-info/WHEEL +5 -0
  35. testshed-0.0.1.dist-info/entry_points.txt +2 -0
  36. testshed-0.0.1.dist-info/licenses/LICENSE +21 -0
  37. testshed-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,35 @@
1
+ from dataclasses import dataclass, field
2
+ from pathlib import Path
3
+
4
+
5
+ @dataclass(slots=True)
6
+ class Options:
7
+ labels: dict[str, str] = field(
8
+ default_factory=lambda: {"com.kloudkit.testshed": "testing-container"}
9
+ )
10
+ network: str = "testshed-network"
11
+ image: str | None = None
12
+ tag: str = "tests"
13
+ src_path: Path | None = None
14
+ tests_path: Path | None = None
15
+ stubs_path: Path | None = None
16
+
17
+ @property
18
+ def image_and_tag(self) -> str:
19
+ """Fully-qualified Docker testing image for test runs."""
20
+
21
+ sep = ":"
22
+
23
+ if self.tag.startswith("sha"):
24
+ sep = "@"
25
+
26
+ return f"{self.image}{sep}{self.tag}"
27
+
28
+
29
+ _state: Options = Options()
30
+
31
+
32
+ def get_state() -> Options:
33
+ """Get the current state."""
34
+
35
+ return _state
@@ -0,0 +1,6 @@
1
+ from kloudkit.testshed.core.wrapper import Wrapper
2
+
3
+
4
+ __all__ = (
5
+ "Wrapper",
6
+ )
@@ -0,0 +1,41 @@
1
+ from pathlib import Path
2
+
3
+ from python_on_whales import docker
4
+
5
+ import pytest
6
+
7
+
8
+ def init_shed_network(network: str) -> None:
9
+ """Ensure the required Docker network exists."""
10
+
11
+ if not docker.network.exists(network):
12
+ docker.network.create(network)
13
+
14
+
15
+ def init_shed_image(
16
+ image: str,
17
+ *,
18
+ require_local_image: bool,
19
+ force_build: bool,
20
+ context_path: Path,
21
+ ) -> None:
22
+ """Build the Docker image when missing or rebuild is forced."""
23
+
24
+ image_missing = not docker.image.exists(image)
25
+
26
+ if image_missing and require_local_image:
27
+ pytest.exit(f"Required image [{image}] not found. Aborting")
28
+
29
+ if image_missing:
30
+ print(f"Testing image [{image}] not found")
31
+ force_build = True
32
+
33
+ if force_build:
34
+ print(f"Forcing build of test image [{image}]")
35
+
36
+ docker.build(
37
+ context_path=context_path,
38
+ pull=True,
39
+ progress="plain",
40
+ tags=image,
41
+ )
@@ -0,0 +1,42 @@
1
+ from types import SimpleNamespace
2
+ from typing import Any, Generic, TypeVar
3
+
4
+
5
+ T = TypeVar("T")
6
+
7
+
8
+ class Wrapper(Generic[T]):
9
+ __slots__ = ("_wrapped", "_args")
10
+
11
+ def __init__(self, wrapped: T, **kwargs: Any) -> None:
12
+ self._wrapped: T = wrapped
13
+ self._args = SimpleNamespace(**kwargs)
14
+
15
+ def __getattr__(self, name: str) -> Any:
16
+ """Delegate lookups to the wrapped object."""
17
+
18
+ return getattr(self._wrapped, name)
19
+
20
+ def __dir__(self) -> list[str]:
21
+ """Augment `dir` with attributes from the wrapped object."""
22
+
23
+ return sorted(set(super().__dir__()) | set(dir(self._wrapped)))
24
+
25
+ def __repr__(self) -> str:
26
+ """Representation of the wrapper, including passed keyword args."""
27
+
28
+ args_dict = vars(self._args)
29
+ suffix = ""
30
+
31
+ if args_dict:
32
+ kv = ", ".join(f"{k}={args_dict[k]!r}" for k in sorted(args_dict))
33
+
34
+ suffix = f", {kv}"
35
+
36
+ return f"{type(self).__name__}({self._wrapped!r}{suffix})"
37
+
38
+ @property
39
+ def wrapped(self) -> T:
40
+ """Get the underlying wrapped object with its precise type."""
41
+
42
+ return self._wrapped
@@ -0,0 +1,16 @@
1
+ from python_on_whales import DockerException, docker
2
+
3
+ from kloudkit.testshed.docker.container import Container
4
+ from kloudkit.testshed.docker.factory import Factory
5
+ from kloudkit.testshed.docker.inline_volume import InlineVolume
6
+ from kloudkit.testshed.docker.probes.http_probe import HttpProbe
7
+
8
+
9
+ __all__ = (
10
+ "Container",
11
+ "docker",
12
+ "DockerException",
13
+ "Factory",
14
+ "HttpProbe",
15
+ "InlineVolume",
16
+ )
@@ -0,0 +1,51 @@
1
+ from python_on_whales import Container as NativeContainer, docker
2
+
3
+ from kloudkit.testshed.core.wrapper import Wrapper
4
+ from kloudkit.testshed.docker.runtime.file_system import FileSystem
5
+ from kloudkit.testshed.docker.runtime.shell import Shell
6
+
7
+
8
+ class Container(Wrapper[NativeContainer]):
9
+ BASH_PATH = "/bin/bash"
10
+ SH_PATH = "/bin/sh"
11
+ ZSH_PATH = "/usr/bin/zsh"
12
+
13
+ LOGIN_SHELL = False
14
+ DEFAULT_USER = None
15
+ DEFAULT_SHELL = None
16
+
17
+ def ip(self) -> str:
18
+ """Retrieve internal IP address of container."""
19
+
20
+ return self.execute(["hostname", "-i"])
21
+
22
+ @property
23
+ def fs(self) -> FileSystem:
24
+ """Higher order file system."""
25
+
26
+ return FileSystem(self)
27
+
28
+ @property
29
+ def execute(self) -> Shell:
30
+ """Higher order execution."""
31
+
32
+ return Shell(
33
+ self._wrapped,
34
+ bash_path=self.BASH_PATH,
35
+ sh_path=self.SH_PATH,
36
+ zsh_path=self.ZSH_PATH,
37
+ user=self.DEFAULT_USER,
38
+ shell=self.DEFAULT_SHELL,
39
+ login_shell=self.LOGIN_SHELL,
40
+ )
41
+
42
+ @classmethod
43
+ def run(cls, *args, **kwargs):
44
+ """Wrap the native `docker.run`."""
45
+
46
+ instance = docker.run(*args, **kwargs)
47
+
48
+ if isinstance(instance, str):
49
+ return instance
50
+
51
+ return cls(instance)
@@ -0,0 +1,45 @@
1
+ from dataclasses import dataclass
2
+ from typing import Self
3
+
4
+ import pytest
5
+
6
+
7
+ @dataclass(frozen=True, slots=True)
8
+ class ContainerConfig:
9
+ envs: dict[str, str]
10
+ volumes: tuple[str, ...]
11
+ args: dict[str, str]
12
+ test_name: str
13
+
14
+ @property
15
+ def has_overrides(self) -> bool:
16
+ """If any fields are non-empty."""
17
+
18
+ return bool(self.envs or self.volumes or self.args)
19
+
20
+ def to_dict(self) -> dict:
21
+ """Return a plain dict with merged configs."""
22
+
23
+ return dict(
24
+ envs=self.envs,
25
+ volumes=self.volumes,
26
+ test_name=self.test_name,
27
+ **self.args,
28
+ )
29
+
30
+ @classmethod
31
+ def create(cls, request: pytest.FixtureRequest) -> Self:
32
+ """Create configs from a pytest request of the current node."""
33
+
34
+ item = request.node
35
+
36
+ config_marker = item.get_closest_marker("shed_config")
37
+ env_marker = item.get_closest_marker("shed_env")
38
+ volumes_marker = item.get_closest_marker("shed_volumes")
39
+
40
+ return cls(
41
+ envs=env_marker.kwargs if env_marker else {},
42
+ volumes=tuple(volumes_marker.args) if volumes_marker else tuple(),
43
+ test_name=item.nodeid,
44
+ args=(config_marker.kwargs if config_marker else {}),
45
+ )
@@ -0,0 +1,23 @@
1
+ from kloudkit.testshed.docker.inline_volume import InlineVolume
2
+
3
+ import pytest
4
+
5
+
6
+ def shed_config(**configs) -> pytest.MarkDecorator:
7
+ """Assign generic configs to the `shed` instance."""
8
+
9
+ return pytest.mark.shed_config(**configs)
10
+
11
+
12
+ def shed_env(**envs) -> pytest.MarkDecorator:
13
+ """Assign environment variables to the `shed` instance."""
14
+
15
+ return pytest.mark.shed_env(**envs)
16
+
17
+
18
+ def shed_volumes(
19
+ *mounts: tuple[str, str] | InlineVolume,
20
+ ) -> pytest.MarkDecorator:
21
+ """Assign volume mounts to the `shed` instance."""
22
+
23
+ return pytest.mark.shed_volumes(*mounts)
@@ -0,0 +1,68 @@
1
+ from kloudkit.testshed._internal.state import get_state
2
+ from kloudkit.testshed.docker.container import Container
3
+ from kloudkit.testshed.docker.probes.http_probe import HttpProbe
4
+ from kloudkit.testshed.docker.probes.readiness_check import ReadinessCheck
5
+ from kloudkit.testshed.docker.runtime.cleanup import Cleanup
6
+ from kloudkit.testshed.docker.volume_manager import VolumeManager
7
+
8
+
9
+ class Factory:
10
+ def __init__(self):
11
+ self._containers: list[Container] = []
12
+ self._volume_manager = VolumeManager()
13
+
14
+ def __call__(self, *args, **kwargs) -> Container | str:
15
+ """Delegate to `build`."""
16
+
17
+ return self.build(*args, **kwargs)
18
+
19
+ def build(
20
+ self,
21
+ image: str,
22
+ *,
23
+ detach: bool = True,
24
+ probe: HttpProbe | None = None,
25
+ container_class: type[Container] | None = None,
26
+ test_name: str | None = None,
27
+ **kwargs,
28
+ ) -> Container | str:
29
+ """Create a Docker container to use in test-cases."""
30
+
31
+ container_class = container_class or Container
32
+
33
+ container = container_class.run(
34
+ image,
35
+ remove=True,
36
+ labels=self._prepare_labels(test_name),
37
+ detach=detach,
38
+ networks=kwargs.pop("networks", [get_state().network]),
39
+ volumes=self._volume_manager.normalize(kwargs.pop("volumes", [])),
40
+ **kwargs,
41
+ )
42
+
43
+ if isinstance(container, str):
44
+ return container
45
+
46
+ self._containers.append(container)
47
+
48
+ if probe:
49
+ ReadinessCheck(container, probe).wait()
50
+
51
+ return container
52
+
53
+ def _prepare_labels(self, test_name: str | None) -> dict:
54
+ """Prepare labels to track Docker container instance."""
55
+
56
+ labels = get_state().labels
57
+
58
+ if test_name:
59
+ labels["com.kloudkit.testshed.test"] = test_name
60
+
61
+ return labels
62
+
63
+ def cleanup(self) -> None:
64
+ """Force-remove all containers started during test-cases."""
65
+
66
+ Cleanup.run(self._containers, get_state().labels)
67
+
68
+ self._volume_manager.cleanup()
@@ -0,0 +1,41 @@
1
+ import os
2
+ import tempfile
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+
6
+
7
+ @dataclass
8
+ class InlineVolume:
9
+ """A volume mount created from inline content written to a temporary file."""
10
+
11
+ path: Path | str
12
+ _content: bytes | str
13
+ _mode: int = 0o644
14
+ _temp_path: Path | str | None = field(default=None, init=False, repr=False)
15
+
16
+ def create(self) -> str:
17
+ """Create the temporary file and return its path."""
18
+
19
+ if self._temp_path is not None:
20
+ return self._temp_path
21
+
22
+ temp_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
23
+
24
+ try:
25
+ temp_file.write(self._content)
26
+ temp_file.flush()
27
+
28
+ self._temp_path = temp_file.name
29
+
30
+ os.chmod(self._temp_path, self._mode)
31
+ finally:
32
+ temp_file.close()
33
+
34
+ return self._temp_path
35
+
36
+ def cleanup(self) -> None:
37
+ """Clean up the temporary file."""
38
+
39
+ if self._temp_path and Path(self._temp_path).exists():
40
+ os.unlink(self._temp_path)
41
+ self._temp_path = None
@@ -0,0 +1,23 @@
1
+ from dataclasses import asdict, dataclass, replace
2
+ from typing import Self
3
+
4
+
5
+ @dataclass(slots=True)
6
+ class HttpProbe:
7
+ host: str = "http://localhost"
8
+ port: int | None = None
9
+ endpoint: str | None = None
10
+ command: str = "curl"
11
+ timeout: float = 30.0
12
+
13
+ def merge(
14
+ self, other: "HttpProbe", *, ignore_none: bool = True
15
+ ) -> Self:
16
+ """Merge two Probes."""
17
+
18
+ if not ignore_none:
19
+ return replace(self, **asdict(other))
20
+
21
+ overlay = {k: v for k, v in asdict(other).items() if v is not None}
22
+
23
+ return replace(self, **overlay)
@@ -0,0 +1,48 @@
1
+ import time
2
+
3
+ from python_on_whales.exceptions import DockerException
4
+
5
+ from kloudkit.testshed.docker.container import Container
6
+ from kloudkit.testshed.docker.probes.http_probe import HttpProbe
7
+
8
+ import pytest
9
+
10
+
11
+ class ReadinessCheck:
12
+ def __init__(self, container: Container, probe: HttpProbe):
13
+ self._container: Container = container
14
+ self._probe: HttpProbe = probe
15
+
16
+ @property
17
+ def url(self) -> str:
18
+ """Full probe target URL."""
19
+
20
+ port = f":{self._probe.port}" if self._probe.port else ""
21
+ endpoint = self._probe.endpoint if self._probe.endpoint else ""
22
+
23
+ return "".join((self._probe.host, port, endpoint))
24
+
25
+ @property
26
+ def command(self) -> list[str]:
27
+ """Full probe test command."""
28
+
29
+ return [*self._probe.command.split(" "), self.url]
30
+
31
+ def wait(self) -> None:
32
+ """Wait until a container responds on the given endpoint."""
33
+
34
+ deadline = time.time() + self._probe.timeout
35
+
36
+ failure_message = (
37
+ f"URL [{self.url}] was not reachable within {self._probe.timeout}s"
38
+ )
39
+
40
+ while time.time() < deadline:
41
+ try:
42
+ self._container.execute(self.command, raises=True)
43
+
44
+ return
45
+ except DockerException:
46
+ time.sleep(0.1)
47
+
48
+ pytest.fail(failure_message, pytrace=False)
@@ -0,0 +1,30 @@
1
+ import contextlib
2
+
3
+ from python_on_whales import docker
4
+ from python_on_whales.exceptions import DockerException
5
+
6
+ from kloudkit.testshed._internal.state import get_state
7
+ from kloudkit.testshed.docker.container import Container
8
+
9
+
10
+ class Cleanup:
11
+ @classmethod
12
+ def run(
13
+ cls,
14
+ containers: list[Container] | None = None,
15
+ labels: dict | None = None,
16
+ ) -> None:
17
+ """Force-remove all provided containers or labeled."""
18
+
19
+ if containers is None:
20
+ labels = labels or get_state().labels
21
+
22
+ key, value = next(iter(labels.items()))
23
+
24
+ containers = docker.container.list(
25
+ all=True, filters=[("label", f"{key}={value}")]
26
+ )
27
+
28
+ for container in containers:
29
+ with contextlib.suppress(DockerException):
30
+ container.remove(force=True, volumes=True)
@@ -0,0 +1,33 @@
1
+ import functools
2
+ from typing import Callable, ParamSpec, TypeVar
3
+
4
+ from python_on_whales.exceptions import DockerException, NoSuchContainer
5
+
6
+ import pytest
7
+
8
+
9
+ P = ParamSpec("P")
10
+ T = TypeVar("T")
11
+
12
+
13
+ def error_handler(fn: Callable[P, T]) -> Callable[P, T]:
14
+ """Handle Docker related error output."""
15
+
16
+ @functools.wraps(fn)
17
+ def _wrapped(self, *args, **kwargs):
18
+ raises = kwargs.pop("raises", False)
19
+
20
+ try:
21
+ return fn(self, *args, **kwargs)
22
+ except NoSuchContainer as error:
23
+ failure = str(error)
24
+ except DockerException as error:
25
+ if raises:
26
+ raise
27
+
28
+ failure = str(error)
29
+
30
+ if failure:
31
+ pytest.fail(failure, pytrace=False)
32
+
33
+ return _wrapped
@@ -0,0 +1,62 @@
1
+ import json
2
+ import tempfile
3
+ from pathlib import Path
4
+
5
+ import yaml
6
+ from python_on_whales import docker
7
+
8
+ from kloudkit.testshed.core.wrapper import Wrapper
9
+ from kloudkit.testshed.docker.runtime.error_handler import error_handler
10
+
11
+
12
+ class FileSystem(Wrapper["Container"]):
13
+ def exists(self, path: str | Path) -> bool:
14
+ """Check if a file or directory exists."""
15
+
16
+ result = self._wrapped.execute(
17
+ ["test", "-e", path, "&&", "echo", "yes", "||", "echo", "no"]
18
+ )
19
+
20
+ return "yes" in result
21
+
22
+ def json(self, path: str | Path) -> dict:
23
+ """Retrieve the content of a file as json."""
24
+
25
+ return json.loads(self(path))
26
+
27
+ def yaml(self, path: str | Path) -> dict:
28
+ """Retrieve the content of a file as yaml."""
29
+
30
+ return yaml.safe_load(self(path))
31
+
32
+ def text(self, path: str | Path) -> str:
33
+ """Retrieve the content of a file as text."""
34
+
35
+ return self.bytes(path).decode("utf-8")
36
+
37
+ @error_handler
38
+ def bytes(self, path: str | Path) -> bytes:
39
+ """Retrieve the content of a file as bytes."""
40
+
41
+ with tempfile.NamedTemporaryFile(delete=True) as tmp_file:
42
+ docker.copy((self._wrapped.id, path), tmp_file.name)
43
+
44
+ return Path(tmp_file.name).read_bytes()
45
+
46
+ @error_handler
47
+ def ls(self, path: str | Path, *, hidden=False) -> tuple[str, ...]:
48
+ """Retrieve directory listing for a given path."""
49
+
50
+ flags = "-1"
51
+
52
+ if hidden:
53
+ flags = f"{flags}a"
54
+
55
+ return tuple(
56
+ self._wrapped.execute(["\\ls", flags, str(path)]).splitlines()
57
+ )
58
+
59
+ def __call__(self, path: str | Path) -> str:
60
+ """Retrieve the content of a file for a given path."""
61
+
62
+ return self.text(path)
@@ -0,0 +1,75 @@
1
+ from typing import Iterable
2
+
3
+ from python_on_whales import Container as NativeContainer
4
+
5
+ from kloudkit.testshed.core.wrapper import Wrapper
6
+ from kloudkit.testshed.docker.runtime.error_handler import error_handler
7
+
8
+
9
+ class Shell(Wrapper[NativeContainer]):
10
+ @error_handler
11
+ def _execute(
12
+ self,
13
+ command: list[str] | tuple[str] | str,
14
+ shell: str = None,
15
+ login_shell: bool | None = None,
16
+ raises=False,
17
+ **kwargs,
18
+ ) -> Iterable[tuple[str, bytes]] | str | None:
19
+ """Execute commands natively using the default shell."""
20
+
21
+ flags = (
22
+ "-cli"
23
+ if (login_shell if login_shell is not None else self._args.login_shell)
24
+ else "-c"
25
+ )
26
+
27
+ user = kwargs.pop("user", self._args.user)
28
+
29
+ shell = shell or (
30
+ self._args.shell if self._args.shell is not None else None
31
+ )
32
+
33
+ if shell:
34
+ if not isinstance(command, str):
35
+ command = " ".join(command)
36
+
37
+ command = [shell, flags, command]
38
+
39
+ return self._wrapped.execute(command, user=user, **kwargs)
40
+
41
+ def bash(
42
+ self,
43
+ command: list[str] | tuple[str] | str,
44
+ **kwargs,
45
+ ) -> Iterable[tuple[str, bytes]] | str | None:
46
+ """Execute commands using `bash` shell."""
47
+
48
+ return self._execute(command, shell=self._args.bash_path, **kwargs)
49
+
50
+ def zsh(
51
+ self,
52
+ command: list[str] | tuple[str] | str,
53
+ **kwargs,
54
+ ) -> Iterable[tuple[str, bytes]] | str | None:
55
+ """Execute commands using `zsh` shell."""
56
+
57
+ return self._execute(command, shell=self._args.zsh_path, **kwargs)
58
+
59
+ def sh(
60
+ self,
61
+ command: list[str] | tuple[str] | str,
62
+ **kwargs,
63
+ ) -> Iterable[tuple[str, bytes]] | str | None:
64
+ """Execute commands using `sh` shell."""
65
+
66
+ return self._execute(command, shell=self._args.sh_path, **kwargs)
67
+
68
+ def __call__(
69
+ self,
70
+ command: list[str] | tuple[str] | str,
71
+ **kwargs,
72
+ ) -> Iterable[tuple[str, bytes]] | str | None:
73
+ """Execute using the native method."""
74
+
75
+ return self._execute(command, **kwargs)