Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion src/testcontainers/core/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
import pathlib
import sys
import tarfile
from collections.abc import Iterator
from dataclasses import dataclass
from os import PathLike
from socket import socket
from types import TracebackType
from typing import TYPE_CHECKING, Any, Optional, TypedDict, Union
from typing import TYPE_CHECKING, Any, BinaryIO, Optional, TypedDict, Union

import docker.errors
from docker import version
Expand All @@ -32,10 +33,31 @@

if TYPE_CHECKING:
from docker.models.containers import Container
from typing_extensions import Buffer

logger = setup_logger(__name__)


class _ArchiveReader(io.RawIOBase):
"""Expose Docker's archive chunks as a sequential file for tarfile."""

def __init__(self, chunks: Iterator[bytes]) -> None:
self._chunks = filter(None, chunks)
self._pending = memoryview(b"")

def readable(self) -> bool:
return True

def readinto(self, buffer: "Buffer", /) -> int:
view = memoryview(buffer).cast("B")
if view and not self._pending:
self._pending = memoryview(next(self._chunks, b""))
size = min(len(view), len(self._pending))
view[:size] = self._pending[:size]
self._pending = self._pending[size:]
return size


class Mount(TypedDict):
bind: str
mode: str
Expand Down Expand Up @@ -456,6 +478,33 @@ def copy_from_container(self, source_in_container: str, destination_on_host: pat
if extracted is not None:
destination_on_host.write_bytes(extracted.read())

def copy_file_from_container_to(self, source_in_container: str, destination: BinaryIO) -> None:
"""Copy one regular file into an open binary stream at its current position.

Leave the destination open. A failed transfer can leave partial output.
"""
chunk_size = 64 * 1024
chunks, _ = self.get_wrapped_container().get_archive(source_in_container, chunk_size=chunk_size)
try:
with io.BufferedReader(_ArchiveReader(chunks)) as reader, tarfile.open(fileobj=reader, mode="r|") as tar:
member = tar.next()
if member is None or not member.isfile():
raise ValueError(f"Expected a regular file at {source_in_container!r}")
extracted = tar.extractfile(member)
assert extracted is not None
with extracted:
while block := extracted.read(chunk_size):
remaining = memoryview(block)
while remaining:
written = destination.write(remaining)
if not written:
raise OSError("Destination stream made no progress writing file data")
remaining = remaining[written:]
finally:
close = getattr(chunks, "close", None)
if close is not None:
close()


class Reaper:
"""
Expand Down
45 changes: 45 additions & 0 deletions tests/core/test_transferable.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import io
import tarfile
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from unittest.mock import Mock

import pytest

Expand Down Expand Up @@ -164,3 +166,46 @@ def test_copy_directory_into_container(tmp_path: Path):
result = container.exec(f"cat {destination_in_container}/my_directory/my_file")
assert result.exit_code == 0
assert result.output == b"hello world"


def test_stream_file_before_archive_is_exhausted(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("testcontainers.core.container.DockerClient", Mock())
container = DockerContainer("bash")
wrapped = Mock()
monkeypatch.setattr(container, "_container", wrapped)
payload = bytes(range(256)) * 4096
archive = build_transfer_tar(payload, "/data")
consumed = 0
closed = False

def chunks() -> Iterator[bytes]:
nonlocal consumed, closed
try:
for offset in range(0, len(archive), 4093):
chunk = archive[offset : offset + 4093]
consumed += len(chunk)
yield chunk
finally:
closed = True

class Sink(io.BytesIO):
def write(self, data: Any, /) -> int:
if self.tell() == 0:
assert 0 < consumed < len(payload)
return super().write(data[:5000])

wrapped.get_archive.return_value = chunks(), {}
sink = Sink()
container.copy_file_from_container_to("/data", sink)
assert closed
assert sink.getvalue() == payload


def test_stream_from_running_container():
with DockerContainer("bash", command="sleep infinity") as container:
container.copy_into_container(b"data\x00", "/data")
destination = io.BytesIO()
container.copy_file_from_container_to("/data", destination)
assert destination.getvalue() == b"data\x00"
with pytest.raises(ValueError, match="regular file"):
container.copy_file_from_container_to("/tmp", destination)