testshed 0.0.7__tar.gz

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 (49) hide show
  1. testshed-0.0.7/LICENSE +21 -0
  2. testshed-0.0.7/PKG-INFO +203 -0
  3. testshed-0.0.7/README.md +172 -0
  4. testshed-0.0.7/pyproject.toml +72 -0
  5. testshed-0.0.7/setup.cfg +4 -0
  6. testshed-0.0.7/src/kloudkit/testshed/__init__.py +1 -0
  7. testshed-0.0.7/src/kloudkit/testshed/core/__init__.py +4 -0
  8. testshed-0.0.7/src/kloudkit/testshed/core/bootstrap.py +58 -0
  9. testshed-0.0.7/src/kloudkit/testshed/core/state.py +72 -0
  10. testshed-0.0.7/src/kloudkit/testshed/core/wrapper.py +42 -0
  11. testshed-0.0.7/src/kloudkit/testshed/docker/__init__.py +16 -0
  12. testshed-0.0.7/src/kloudkit/testshed/docker/container.py +51 -0
  13. testshed-0.0.7/src/kloudkit/testshed/docker/container_config.py +45 -0
  14. testshed-0.0.7/src/kloudkit/testshed/docker/decorators.py +27 -0
  15. testshed-0.0.7/src/kloudkit/testshed/docker/factory.py +70 -0
  16. testshed-0.0.7/src/kloudkit/testshed/docker/probes/http_probe.py +30 -0
  17. testshed-0.0.7/src/kloudkit/testshed/docker/probes/readiness_check.py +39 -0
  18. testshed-0.0.7/src/kloudkit/testshed/docker/runtime/cleanup.py +37 -0
  19. testshed-0.0.7/src/kloudkit/testshed/docker/runtime/error_handler.py +49 -0
  20. testshed-0.0.7/src/kloudkit/testshed/docker/runtime/file_system.py +66 -0
  21. testshed-0.0.7/src/kloudkit/testshed/docker/runtime/shell.py +86 -0
  22. testshed-0.0.7/src/kloudkit/testshed/docker/volumes/base_volume.py +50 -0
  23. testshed-0.0.7/src/kloudkit/testshed/docker/volumes/inline_volume.py +18 -0
  24. testshed-0.0.7/src/kloudkit/testshed/docker/volumes/remote_volume.py +37 -0
  25. testshed-0.0.7/src/kloudkit/testshed/docker/volumes/volume_manager.py +49 -0
  26. testshed-0.0.7/src/kloudkit/testshed/fixtures/docker.py +41 -0
  27. testshed-0.0.7/src/kloudkit/testshed/fixtures/generic.py +52 -0
  28. testshed-0.0.7/src/kloudkit/testshed/fixtures/playwright.py +31 -0
  29. testshed-0.0.7/src/kloudkit/testshed/fixtures/shed.py +76 -0
  30. testshed-0.0.7/src/kloudkit/testshed/playwright/__init__.py +4 -0
  31. testshed-0.0.7/src/kloudkit/testshed/playwright/factory.py +30 -0
  32. testshed-0.0.7/src/kloudkit/testshed/plugin/__init__.py +9 -0
  33. testshed-0.0.7/src/kloudkit/testshed/plugin/addoptions.py +76 -0
  34. testshed-0.0.7/src/kloudkit/testshed/plugin/configure.py +50 -0
  35. testshed-0.0.7/src/kloudkit/testshed/plugin/fixtures.py +15 -0
  36. testshed-0.0.7/src/kloudkit/testshed/plugin/markers.py +19 -0
  37. testshed-0.0.7/src/kloudkit/testshed/plugin/presenter.py +17 -0
  38. testshed-0.0.7/src/kloudkit/testshed/plugin/session.py +19 -0
  39. testshed-0.0.7/src/kloudkit/testshed/plugin/validation.py +30 -0
  40. testshed-0.0.7/src/kloudkit/testshed/py.typed +0 -0
  41. testshed-0.0.7/src/kloudkit/testshed/utils/http.py +26 -0
  42. testshed-0.0.7/src/kloudkit/testshed/utils/network.py +13 -0
  43. testshed-0.0.7/src/kloudkit/testshed/utils/version.py +33 -0
  44. testshed-0.0.7/src/testshed.egg-info/PKG-INFO +203 -0
  45. testshed-0.0.7/src/testshed.egg-info/SOURCES.txt +47 -0
  46. testshed-0.0.7/src/testshed.egg-info/dependency_links.txt +1 -0
  47. testshed-0.0.7/src/testshed.egg-info/entry_points.txt +2 -0
  48. testshed-0.0.7/src/testshed.egg-info/requires.txt +11 -0
  49. testshed-0.0.7/src/testshed.egg-info/top_level.txt +1 -0
testshed-0.0.7/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KloudKIT
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.4
2
+ Name: testshed
3
+ Version: 0.0.7
4
+ Summary: 🛠️ PyTest's tool shed: Docker up, Playwright on, cleanup done
5
+ Author-email: Dov Benyomin Sohacheski <b@kloud.email>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/kloudkit/testshed
8
+ Project-URL: Bug Tracker, https://github.com/kloudkit/testshed/issues
9
+ Project-URL: Source Code, https://github.com/kloudkit/testshed
10
+ Keywords: pytest,docker,fixtures,playwright,testing
11
+ Classifier: Framework :: Pytest
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: playwright<2.0.0,>=1.57.0
21
+ Requires-Dist: pytest>=9.0.2
22
+ Requires-Dist: python-on-whales<1.0.0,>=0.80.0
23
+ Requires-Dist: PyYAML<7.0.0,>=6.0.3
24
+ Requires-Dist: requests<3.0.0,>=2.32.5
25
+ Provides-Extra: dev
26
+ Requires-Dist: pre-commit>=4.5.1; extra == "dev"
27
+ Requires-Dist: ruff>=0.14.11; extra == "dev"
28
+ Requires-Dist: coverage>=7.13.1; extra == "dev"
29
+ Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # KloudKIT TestShed
33
+
34
+ > Meet **KloudKIT TestShed**, a tidy home for your integration-testing power tools.
35
+ >
36
+ > It snap-fits into `pytest`, auto-provisions Docker, runs Playwright, and cleans up after itself
37
+ > so you can focus on building sharp tests.
38
+
39
+ ## Features
40
+
41
+ - **Automated Docker management:** Spin up and control containers from tests.
42
+ - **Playwright integration:** Run browser tests in isolated Docker environments.
43
+ - **Configurable via markers & CLI:** Tune environments per test or suite.
44
+ - **Automatic resource cleanup:** Ensures a clean state after tests.
45
+
46
+ ## Installation
47
+
48
+ ```sh
49
+ pip install testshed
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Fixture Auto-Discovery
55
+
56
+ TestShed fixtures are automatically available when `--shed` is enabled.
57
+
58
+ ```bash
59
+ pytest --shed
60
+ ```
61
+
62
+ For manual control or when `--shed` is not used, you can still import specific fixtures:
63
+
64
+ ```python
65
+ from kloudkit.testshed.fixtures.docker import docker_sidecar
66
+ from kloudkit.testshed.fixtures.shed import shed
67
+ from kloudkit.testshed.fixtures.playwright import playwright_browser
68
+ ```
69
+
70
+ ### Docker container testing
71
+
72
+ TestShed provides fixtures to manage containers inside your tests.
73
+
74
+ #### High-level `shed` fixtures
75
+
76
+ Use the `shed` fixture for smart container management with configurable defaults:
77
+
78
+ ```python
79
+ import pytest
80
+
81
+ from kloudkit.testshed.docker import Container, HttpProbe
82
+
83
+ class MyAppContainer(Container):
84
+ DEFAULT_USER = "app"
85
+
86
+ @pytest.fixture(scope="session")
87
+ def shed_container_defaults():
88
+ """Override this fixture to set project-specific defaults."""
89
+
90
+ return {
91
+ "container_class": MyAppContainer,
92
+ "envs": {"APP_PORT": 3000},
93
+ "probe": HttpProbe(port=3000, endpoint="/health"),
94
+ }
95
+
96
+ def test_my_app(shed):
97
+ # Uses your configured defaults automatically
98
+ assert shed.execute("whoami") == "app"
99
+
100
+ @shed_env(DEBUG="true")
101
+ def test_my_app_with_debug(shed):
102
+ # New container with override, merged with defaults
103
+ assert shed.execute("echo $DEBUG") == "true"
104
+ assert shed.execute("echo $APP_PORT") == "3000"
105
+ ```
106
+
107
+ You can also use the factory directly:
108
+
109
+ ```python
110
+ def test_custom_setup(shed_factory):
111
+ container = shed_factory(envs={"CUSTOM_VAR": "value"})
112
+ # ... test logic ...
113
+ ```
114
+
115
+ #### Basic Docker container
116
+
117
+ For a lower-level API, use the `docker_sidecar` fixture to create containers:
118
+
119
+ ```python
120
+ import pytest
121
+
122
+ def test_my_docker_app(docker_sidecar):
123
+ # Launch a simple Nginx container
124
+ nginx = docker_sidecar("nginx:latest", publish=[(8080, 80)])
125
+
126
+ # Execute a command inside the container
127
+ assert "nginx version" in nginx.execute(["nginx", "-v"])
128
+
129
+ # Access the container's IP
130
+ print(f"Nginx container IP: {nginx.ip()}")
131
+
132
+ # Interact with the file system
133
+ assert "/usr/share/nginx/html" in nginx.fs.ls("/usr/share/nginx")
134
+ ```
135
+
136
+ #### Configure containers with decorators
137
+
138
+ Configure containers using `pytest` markers/decorators:
139
+
140
+ - **`@shed_config(**kwargs)`:** Generic container args.
141
+ - **`@shed_env(**envs)`:** Environment variables.
142
+ - **`@shed_volumes(*mounts)`:** Volume mounts as `(source, dest)` or `BaseVolume`.
143
+ - **`@shed_mutable()`:** Force non-default shed for tests that perform mutable operations.
144
+
145
+ ```python
146
+ from kloudkit.testshed.docker import InlineVolume, RemoteVolume
147
+
148
+ @shed_env(MY_ENV_VAR="hello")
149
+ @shed_volumes(
150
+ ("/path/to/host/data", "/app/data"),
151
+ InlineVolume("/app/config.txt", "any content you want", mode=0o644),
152
+ RemoteVolume("/app/remote-config.json", "https://api.example.com/config.json", mode=0o644),
153
+ )
154
+ def test_configured_docker_app(shed):
155
+ # ... test logic ...
156
+ ```
157
+
158
+ ### Playwright browser testing
159
+
160
+ Get a Playwright browser instance running in Docker via `playwright_browser`:
161
+
162
+ ```python
163
+ def test_example_website(playwright_browser):
164
+ page = playwright_browser.new_page()
165
+ page.goto("http://example.com")
166
+ assert "Example Domain" in page.title()
167
+ # ... more Playwright test logic ...
168
+ ```
169
+
170
+ ### Command-line options
171
+
172
+ TestShed extends `pytest` with options to control the Docker environment:
173
+
174
+ - **`--shed`:** Enable TestShed for the current test suite *(default: disabled)*.
175
+ - **`--shed-image IMAGE`:** Base image *(e.g., `ghcr.io/acme/app`)*.
176
+ - **`--shed-tag TAG|SHA`:** Image tag or digest *(default: `tests`)*.
177
+ - **`--shed-build-context DIR`:** Docker build context *(default: `pytest.ini` directory)*.
178
+ - **`--shed-image-policy POLICY`:** Image acquisition policy for building or pulling *(default: `pull`)*.
179
+ - **`--shed-skip-bootstrap`:** Skip Docker bootstrapping *(useful for unit tests)*.
180
+
181
+ > [!NOTE]
182
+ > When TestShed is installed globally, you must explicitly enable it per suite with
183
+ > `--shed`.
184
+ > This prevents it from configuring Docker in projects that don't use it.
185
+
186
+ #### Image Policies
187
+
188
+ The `--shed-image-policy` option controls how TestShed acquires Docker images:
189
+
190
+ - **`pull`** *(default)***:** Pull image if not found locally, build as fallback.
191
+ - **`build`:** Build only if image doesn't exist locally.
192
+ - **`require`:** Require existing local image *(fails if not found)*.
193
+ - **`rebuild`:** Always rebuild the image.
194
+
195
+ #### Examples
196
+
197
+ ```bash
198
+ # Enable TestShed for your suite
199
+ pytest --shed --shed-image my-test-image --shed-image-policy rebuild
200
+
201
+ # Run tests without TestShed (default)
202
+ pytest
203
+ ```
@@ -0,0 +1,172 @@
1
+ # KloudKIT TestShed
2
+
3
+ > Meet **KloudKIT TestShed**, a tidy home for your integration-testing power tools.
4
+ >
5
+ > It snap-fits into `pytest`, auto-provisions Docker, runs Playwright, and cleans up after itself
6
+ > so you can focus on building sharp tests.
7
+
8
+ ## Features
9
+
10
+ - **Automated Docker management:** Spin up and control containers from tests.
11
+ - **Playwright integration:** Run browser tests in isolated Docker environments.
12
+ - **Configurable via markers & CLI:** Tune environments per test or suite.
13
+ - **Automatic resource cleanup:** Ensures a clean state after tests.
14
+
15
+ ## Installation
16
+
17
+ ```sh
18
+ pip install testshed
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### Fixture Auto-Discovery
24
+
25
+ TestShed fixtures are automatically available when `--shed` is enabled.
26
+
27
+ ```bash
28
+ pytest --shed
29
+ ```
30
+
31
+ For manual control or when `--shed` is not used, you can still import specific fixtures:
32
+
33
+ ```python
34
+ from kloudkit.testshed.fixtures.docker import docker_sidecar
35
+ from kloudkit.testshed.fixtures.shed import shed
36
+ from kloudkit.testshed.fixtures.playwright import playwright_browser
37
+ ```
38
+
39
+ ### Docker container testing
40
+
41
+ TestShed provides fixtures to manage containers inside your tests.
42
+
43
+ #### High-level `shed` fixtures
44
+
45
+ Use the `shed` fixture for smart container management with configurable defaults:
46
+
47
+ ```python
48
+ import pytest
49
+
50
+ from kloudkit.testshed.docker import Container, HttpProbe
51
+
52
+ class MyAppContainer(Container):
53
+ DEFAULT_USER = "app"
54
+
55
+ @pytest.fixture(scope="session")
56
+ def shed_container_defaults():
57
+ """Override this fixture to set project-specific defaults."""
58
+
59
+ return {
60
+ "container_class": MyAppContainer,
61
+ "envs": {"APP_PORT": 3000},
62
+ "probe": HttpProbe(port=3000, endpoint="/health"),
63
+ }
64
+
65
+ def test_my_app(shed):
66
+ # Uses your configured defaults automatically
67
+ assert shed.execute("whoami") == "app"
68
+
69
+ @shed_env(DEBUG="true")
70
+ def test_my_app_with_debug(shed):
71
+ # New container with override, merged with defaults
72
+ assert shed.execute("echo $DEBUG") == "true"
73
+ assert shed.execute("echo $APP_PORT") == "3000"
74
+ ```
75
+
76
+ You can also use the factory directly:
77
+
78
+ ```python
79
+ def test_custom_setup(shed_factory):
80
+ container = shed_factory(envs={"CUSTOM_VAR": "value"})
81
+ # ... test logic ...
82
+ ```
83
+
84
+ #### Basic Docker container
85
+
86
+ For a lower-level API, use the `docker_sidecar` fixture to create containers:
87
+
88
+ ```python
89
+ import pytest
90
+
91
+ def test_my_docker_app(docker_sidecar):
92
+ # Launch a simple Nginx container
93
+ nginx = docker_sidecar("nginx:latest", publish=[(8080, 80)])
94
+
95
+ # Execute a command inside the container
96
+ assert "nginx version" in nginx.execute(["nginx", "-v"])
97
+
98
+ # Access the container's IP
99
+ print(f"Nginx container IP: {nginx.ip()}")
100
+
101
+ # Interact with the file system
102
+ assert "/usr/share/nginx/html" in nginx.fs.ls("/usr/share/nginx")
103
+ ```
104
+
105
+ #### Configure containers with decorators
106
+
107
+ Configure containers using `pytest` markers/decorators:
108
+
109
+ - **`@shed_config(**kwargs)`:** Generic container args.
110
+ - **`@shed_env(**envs)`:** Environment variables.
111
+ - **`@shed_volumes(*mounts)`:** Volume mounts as `(source, dest)` or `BaseVolume`.
112
+ - **`@shed_mutable()`:** Force non-default shed for tests that perform mutable operations.
113
+
114
+ ```python
115
+ from kloudkit.testshed.docker import InlineVolume, RemoteVolume
116
+
117
+ @shed_env(MY_ENV_VAR="hello")
118
+ @shed_volumes(
119
+ ("/path/to/host/data", "/app/data"),
120
+ InlineVolume("/app/config.txt", "any content you want", mode=0o644),
121
+ RemoteVolume("/app/remote-config.json", "https://api.example.com/config.json", mode=0o644),
122
+ )
123
+ def test_configured_docker_app(shed):
124
+ # ... test logic ...
125
+ ```
126
+
127
+ ### Playwright browser testing
128
+
129
+ Get a Playwright browser instance running in Docker via `playwright_browser`:
130
+
131
+ ```python
132
+ def test_example_website(playwright_browser):
133
+ page = playwright_browser.new_page()
134
+ page.goto("http://example.com")
135
+ assert "Example Domain" in page.title()
136
+ # ... more Playwright test logic ...
137
+ ```
138
+
139
+ ### Command-line options
140
+
141
+ TestShed extends `pytest` with options to control the Docker environment:
142
+
143
+ - **`--shed`:** Enable TestShed for the current test suite *(default: disabled)*.
144
+ - **`--shed-image IMAGE`:** Base image *(e.g., `ghcr.io/acme/app`)*.
145
+ - **`--shed-tag TAG|SHA`:** Image tag or digest *(default: `tests`)*.
146
+ - **`--shed-build-context DIR`:** Docker build context *(default: `pytest.ini` directory)*.
147
+ - **`--shed-image-policy POLICY`:** Image acquisition policy for building or pulling *(default: `pull`)*.
148
+ - **`--shed-skip-bootstrap`:** Skip Docker bootstrapping *(useful for unit tests)*.
149
+
150
+ > [!NOTE]
151
+ > When TestShed is installed globally, you must explicitly enable it per suite with
152
+ > `--shed`.
153
+ > This prevents it from configuring Docker in projects that don't use it.
154
+
155
+ #### Image Policies
156
+
157
+ The `--shed-image-policy` option controls how TestShed acquires Docker images:
158
+
159
+ - **`pull`** *(default)***:** Pull image if not found locally, build as fallback.
160
+ - **`build`:** Build only if image doesn't exist locally.
161
+ - **`require`:** Require existing local image *(fails if not found)*.
162
+ - **`rebuild`:** Always rebuild the image.
163
+
164
+ #### Examples
165
+
166
+ ```bash
167
+ # Enable TestShed for your suite
168
+ pytest --shed --shed-image my-test-image --shed-image-policy rebuild
169
+
170
+ # Run tests without TestShed (default)
171
+ pytest
172
+ ```
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "testshed"
7
+ description = "🛠️ PyTest's tool shed: Docker up, Playwright on, cleanup done"
8
+ requires-python = ">=3.11"
9
+ authors = [{ name = "Dov Benyomin Sohacheski", email = "b@kloud.email" }]
10
+ license = { text = "MIT" }
11
+ keywords = ["pytest", "docker", "fixtures", "playwright", "testing"]
12
+ classifiers = [
13
+ "Framework :: Pytest",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Typing :: Typed",
19
+ ]
20
+ dependencies = [
21
+ "playwright>=1.57.0,<2.0.0",
22
+ "pytest>=9.0.2",
23
+ "python-on-whales>=0.80.0,<1.0.0",
24
+ "PyYAML>=6.0.3,<7.0.0",
25
+ "requests>=2.32.5,<3.0.0",
26
+ ]
27
+ dynamic = ["readme", "version"]
28
+
29
+ [project.urls]
30
+ "Homepage" = "https://github.com/kloudkit/testshed"
31
+ "Bug Tracker" = "https://github.com/kloudkit/testshed/issues"
32
+ "Source Code" = "https://github.com/kloudkit/testshed"
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pre-commit>=4.5.1",
37
+ "ruff>=0.14.11",
38
+ "coverage>=7.13.1",
39
+ "pytest-cov>=7.0.0",
40
+ ]
41
+
42
+ [project.entry-points.pytest11]
43
+ testshed = "kloudkit.testshed.plugin"
44
+
45
+ [tool.setuptools.dynamic]
46
+ readme = { file = ["README.md"], content-type = "text/markdown" }
47
+ version = { attr = "kloudkit.testshed.__version__" }
48
+
49
+ [tool.coverage.run]
50
+ source = ["kloudkit.testshed"]
51
+ omit = [
52
+ "*/tests/*",
53
+ "*/__pycache__/*",
54
+ "*/venv/*",
55
+ "*/.venv/*"
56
+ ]
57
+
58
+ [tool.coverage.report]
59
+ exclude_lines = [
60
+ "@(abc\\.)?abstractmethod",
61
+ "# pragma: no cover",
62
+ "if __name__ == .__main__.:",
63
+ "def __repr__",
64
+ "raise AssertionError",
65
+ "raise NotImplementedError"
66
+ ]
67
+ show_missing = true
68
+ precision = 2
69
+ fail_under = 80
70
+
71
+ [tool.coverage.html]
72
+ directory = "htmlcov"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ __version__ = "0.0.7"
@@ -0,0 +1,4 @@
1
+ from kloudkit.testshed.core.wrapper import Wrapper
2
+
3
+
4
+ __all__ = ("Wrapper",)
@@ -0,0 +1,58 @@
1
+ from pathlib import Path
2
+ from typing import Literal
3
+
4
+ from python_on_whales import docker
5
+
6
+ import pytest
7
+
8
+
9
+ def _build(image: str, context_path: Path) -> None:
10
+ print(f"Building image [{image}]")
11
+ docker.build(
12
+ context_path=context_path,
13
+ pull=True,
14
+ progress="plain",
15
+ tags=image,
16
+ )
17
+
18
+
19
+ def init_shed_network(network: str) -> None:
20
+ """Ensure the required Docker network exists."""
21
+
22
+ if not docker.network.exists(network):
23
+ docker.network.create(network)
24
+
25
+
26
+ def init_shed_image(
27
+ image: str,
28
+ *,
29
+ policy: Literal["pull", "build", "require", "rebuild"],
30
+ context_path: Path,
31
+ ) -> None:
32
+ """Acquire the Docker image based on the specified policy."""
33
+
34
+ image_exists = docker.image.exists(image)
35
+
36
+ match policy:
37
+ case "require":
38
+ if not image_exists:
39
+ raise pytest.UsageError(f"Required image [{image}] not found.")
40
+
41
+ case "build":
42
+ if not image_exists:
43
+ _build(image, context_path)
44
+
45
+ case "rebuild":
46
+ _build(image, context_path)
47
+
48
+ case "pull":
49
+ if image_exists:
50
+ return
51
+
52
+ try:
53
+ print(f"Testing image [{image}] not found")
54
+ print(f"Attempting to pull image [{image}]")
55
+ docker.pull(image)
56
+ except Exception as e:
57
+ print(f"Pull failed ({e})")
58
+ _build(image, context_path)
@@ -0,0 +1,72 @@
1
+ import os
2
+ import random
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+
7
+ def _generate_instance_key(project_name: str) -> str:
8
+ """Generate a unique instance identifier for containers and networks."""
9
+
10
+ xdist_worker = os.getenv("PYTEST_XDIST_WORKER")
11
+ random_suffix = f"{random.randint(1000, 9999)}"
12
+
13
+ instance_parts = filter(
14
+ None,
15
+ ["testshed", project_name, random_suffix, xdist_worker],
16
+ )
17
+
18
+ return "-".join(instance_parts)
19
+
20
+
21
+ @dataclass(slots=True)
22
+ class ShedState:
23
+ instance_key: str
24
+ image: str
25
+ tag: str
26
+ src_path: Path
27
+ tests_path: Path
28
+ stubs_path: Path
29
+
30
+ @property
31
+ def labels(self) -> dict[str, str]:
32
+ """Labels for tracking Docker containers."""
33
+
34
+ return {"com.kloudkit.testshed": self.instance_key}
35
+
36
+ @property
37
+ def network(self) -> str:
38
+ """Network name for Docker containers."""
39
+
40
+ return self.instance_key
41
+
42
+ @property
43
+ def image_and_tag(self) -> str:
44
+ """Fully-qualified Docker testing image for test runs."""
45
+
46
+ sep = ":"
47
+
48
+ if self.tag.startswith("sha"):
49
+ sep = "@"
50
+
51
+ return f"{self.image}{sep}{self.tag}"
52
+
53
+ @classmethod
54
+ def create(
55
+ cls,
56
+ project_name: str,
57
+ image: str,
58
+ tag: str,
59
+ src_path: Path,
60
+ tests_path: Path,
61
+ stubs_path: Path,
62
+ ) -> "ShedState":
63
+ """Create a ShedState instance with a dynamic instance key."""
64
+
65
+ return cls(
66
+ instance_key=_generate_instance_key(project_name),
67
+ image=image,
68
+ tag=tag,
69
+ src_path=src_path,
70
+ tests_path=tests_path,
71
+ stubs_path=stubs_path,
72
+ )
@@ -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.probes.http_probe import HttpProbe
5
+ from kloudkit.testshed.docker.volumes.inline_volume import InlineVolume
6
+ from kloudkit.testshed.docker.volumes.remote_volume import RemoteVolume
7
+
8
+
9
+ __all__ = (
10
+ "Container",
11
+ "docker",
12
+ "DockerException",
13
+ "HttpProbe",
14
+ "InlineVolume",
15
+ "RemoteVolume",
16
+ )