- Introduced DockerComposeManager class for programmatically creating and managing Docker Compose YAML files. - Added example script demonstrating usage of DockerComposeManager. - Created tests for service creation, modification, and removal. - Included project metadata in pyproject.toml and added linting instructions in copilot-instructions.md.
63 lines
2.2 KiB
Python
63 lines
2.2 KiB
Python
from pathlib import Path
|
|
|
|
import pytest
|
|
import yaml
|
|
|
|
from compose import DockerComposeManager
|
|
|
|
|
|
def test_create_and_save_service(tmp_path: Path) -> None:
|
|
compose_file: Path = tmp_path / "docker-compose.yml"
|
|
manager = DockerComposeManager(str(compose_file))
|
|
manager.create_service(
|
|
name="web",
|
|
image="nginx:latest",
|
|
ports=["80:80"],
|
|
environment={"ENV_VAR": "value"},
|
|
).save()
|
|
# Check file exists and content
|
|
assert compose_file.exists()
|
|
with compose_file.open() as f:
|
|
data = yaml.safe_load(f)
|
|
assert "web" in data["services"]
|
|
assert data["services"]["web"]["image"] == "nginx:latest"
|
|
assert data["services"]["web"]["ports"] == ["80:80"]
|
|
assert data["services"]["web"]["environment"] == {"ENV_VAR": "value"}
|
|
|
|
|
|
def test_modify_service(tmp_path: Path) -> None:
|
|
compose_file: Path = tmp_path / "docker-compose.yml"
|
|
manager = DockerComposeManager(str(compose_file))
|
|
manager.create_service(name="web", image="nginx:latest").save()
|
|
manager.modify_service(name="web", image="nginx:1.19", ports=["8080:80"]).save()
|
|
with compose_file.open() as f:
|
|
data = yaml.safe_load(f)
|
|
assert data["services"]["web"]["image"] == "nginx:1.19"
|
|
assert data["services"]["web"]["ports"] == ["8080:80"]
|
|
|
|
|
|
def test_remove_service(tmp_path: Path) -> None:
|
|
compose_file: Path = tmp_path / "docker-compose.yml"
|
|
manager = DockerComposeManager(str(compose_file))
|
|
manager.create_service(name="web", image="nginx:latest").save()
|
|
manager.remove_service("web").save()
|
|
with compose_file.open() as f:
|
|
data = yaml.safe_load(f)
|
|
assert "web" not in data["services"]
|
|
|
|
|
|
def test_context_manager(tmp_path: Path) -> None:
|
|
compose_file: Path = tmp_path / "docker-compose.yml"
|
|
with DockerComposeManager(str(compose_file)) as manager:
|
|
manager.create_service(name="web", image="nginx:latest")
|
|
with compose_file.open() as f:
|
|
data = yaml.safe_load(f)
|
|
assert "web" in data["services"]
|
|
|
|
|
|
def test_modify_nonexistent_service(tmp_path: Path) -> None:
|
|
compose_file: Path = tmp_path / "docker-compose.yml"
|
|
manager = DockerComposeManager(str(compose_file))
|
|
with pytest.raises(KeyError):
|
|
manager.modify_service("notfound", image="nginx:latest")
|