Commit 83cd775f authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Refactor container_file tests fixture

parent 07737386
Loading
Loading
Loading
Loading
+26 −10
Original line number Diff line number Diff line
@@ -10,6 +10,8 @@ Step implementations involving creating files in containers

from __future__ import annotations

from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Iterator

from behave import fixture
@@ -17,25 +19,39 @@ from behave import given
from behave import use_fixture
from behave.runner import Context
from behave_utils.docker import Cli
from behave_utils.docker import Container
from wp import running_site_fixture


@given("{path} exists in the {container}")
def step_impl(context: Context, path: str, container: str) -> None:
@given("{path:Path} exists in the {container_name}")
def step_impl(context: Context, path: Path, container_name: str) -> None:
	"""
	Create a file in the named container
	"""
	site = use_fixture(running_site_fixture, context)
	container = getattr(site, container_name)
	use_fixture(container_file, context, path, container)


@fixture
def container_file(context: Context, path: str, container_name: str) -> Iterator[None]:
def container_file(context: Context, path: Path, container: Container) -> Iterator[None]:
	"""
	Create a file in a named container as a fixture
	Create a file in a container as a fixture
	"""
	site = use_fixture(running_site_fixture, context)
	container = getattr(site, container_name)
	text = context.text.encode("utf-8") if context.text else b"This is a data file!"

	# For running containers, use commands within the container to make and delete the file
	# This relies on "tee" and "rm" existing in the container image
	if container.is_running():
		run = Cli(container)
	run("tee", path, input=(context.text or "This is a data file!"))
		run("tee", path, input=text)
		yield
		run("rm", path)
		return

	# For unstarted containers, write to a temporary file and add it to the volumes mapping
	with NamedTemporaryFile("wb") as temp:
		temp.write(text)
		temp.close()
		container.volumes.append((path, Path(temp.name)))
		yield