view release on metacpan or search on metacpan
.claude/agents/api-docker-test-writer.md view on Meta::CPAN
---
name: api-docker-test-writer
description: "Write API::Docker tests with Test::More and the Test::API::Docker::Mock route table. The default suite never touches a Docker daemon or the network; live paths stay gated on is_live()/can_write(). Use for test additions, regression scaf...
model: sonnet
briefing:
skills:
- api-docker-core
- api-docker-hazards
- docker-engine-api
- getty-perl-core
- getty-perl-moo
- kanban-issues-karr-ticket
---
.claude/agents/api-docker-test-writer.md view on Meta::CPAN
it existed to catch. Never normalise the value under test on the way into the
assertion.
- **Live and mock must both be able to pass, or the assertion is gated.** `test_docker`
ignores the route table entirely under `API_DOCKER_TEST_HOST` â an assertion tied to
fixture contents runs against a real daemon's data otherwise.
New fixtures are captured from a real daemon into `t/fixtures/*.json`, never hand-rolled
â and that includes wire formats. A test for the multiplexed log stream asserts against
bytes the engine actually produced, not against a frame header written from memory; the
Engine API reference above tells you what to expect, the socket tells you what is true.
Test filenames follow the existing flat, topical naming (`t/images.t`,
`t/images_push_auth.t`), one file per resource or per defect.
A test asserts intent: it must be able to fail when the logic changes. Reproduce a bug
before fixing it and leave the regression behind. Verify with `prove -lr t/`; a single
file with `prove -lv t/NN.t`.
.claude/skills/api-docker-core/SKILL.md view on Meta::CPAN
resource method goes through it (usually via `get`/`post`/`put`/`delete_request`).
A new endpoint never opens its own socket.
Options: `body` (JSON-encoded), `raw_body` + `content_type` (tarballs for
`/build`), `params` (query string), `headers` (extra request headers),
`on_event`/`on_frame`/`on_chunk` (streaming callbacks, see below).
`_request` prefixes the path with `/v$api_version`. `around _request` in
`API::Docker` triggers `negotiate_version` on the first call that is not
`/version` â so a mock that replaces `_request` must strip the `/vX.YZ` prefix
itself, which `Test::API::Docker::Mock` does.
## Invariants
- **`list` and `inspect` return generated `API::Docker::Type::*` objects**
(via `_wrap`/`_wrap_list`); everything else returns the raw daemon response.
`Networks`, `Volumes`, `Plugins`, `Secrets` and `Configs` answer both calls
with one class (one swagger definition each â `API::Docker::Type::Network`,
etc.); `Containers` and `Images` have two each â `ContainerSummary` /
`ContainerInspectResponse`, `ImageSummary` / `ImageInspect` (see
`API::Docker::API::Containers/"The two container shapes"`). Which resources
.claude/skills/api-docker-core/SKILL.md view on Meta::CPAN
`IO::Socket::SSL` in place of the plain socket â same reader, same writer,
same everything above it. `cert_path` names a directory in the `docker`
CLI's own layout (`ca.pem` trust anchor, `cert.pem`+`key.pem` this client's
identity), defaulting from `$ENV{DOCKER_CERT_PATH}`; `tls_insecure => 1`
turns verification off. `IO::Socket::SSL` is a recommended, not required,
dependency, loaded only once a TLS connection is opened. Detail:
`API::Docker::Role::HTTP`'s "TLS on a tcp:// connection".
- **No connection reuse.** Each `_request` calls `_reconnect` and closes
afterwards, streamed or not.
## Tests â `Test::API::Docker::Mock`
`test_docker('GET /images/json' => $fixture_or_coderef, ...)` returns a client
whose `_request` dispatches against the route table (exact key first, then the
key matched as a literal path -- it is `\Q..\E`-escaped, not a regex, so a
metacharacter in a route key means itself). A `GET /version` route is injected
when none is given.
**In live mode `test_docker` ignores the routes entirely** and returns a real
client against `$ENV{API_DOCKER_TEST_HOST}`. An assertion that only holds for
the fixture must sit behind `is_live()`; mutating tests behind `can_write()` /
lib/API/Docker/Error/Truncated.pm # croaked when the daemon closed before its announced response was complete
maint/spec-to-type.pl # generates lib/API/Docker/Type/*.pm from spec/ -- never overwrites
maint/spec-drift-check.pl # diffs spec/ against the registry, and spec against spec
maint/spec-common.pl # the spec loader shared by the two scripts above
maint/spec-to-type-names.yaml # inline-class naming exceptions the generator and checker share
maint/spec-to-type-prose.yaml # hand-written POD for fields/classes the swagger describes poorly
maint/spec-drift-exceptions.yaml # deliberate deviations the drift checker accepts
maint/spec-overlay.yaml # named fields of v1.55 grafted onto the v1.51 base model
spec/v1.41.yaml .. v1.55.yaml # Docker's own swagger, checked in; generation runs against v1.51 plus the overlay
t/ # tests (prove -lr t/)
t/lib/Test/API/Docker/Mock.pm # fixture-driven mock helper
t/fixtures/*.json # captured daemon responses
.claude/agents/ # the api-docker-* subagents
.claude/rules/api-docker-rules.md # house rules, auto-loaded every turn
.claude/skills/ # briefed skills (owned + skilletor-installed)
```
## Build and test
```bash
prove -lr t/ # canonical â recursive; plain `prove -l t/` skips subdirs
The test that covered this could not have caught it. Its decode
helper computed the missing padding and appended it before decoding,
so the assertions passed either way. It now decodes what the engine
would get, and a separate case pins the exact padded header.
- Document that this client speaks the Docker Engine HTTP API over a
socket and never shells out to the `docker` binary, so any engine
serving that API works -- Podman's rootless socket needs nothing
but `DOCKER_HOST`. The new CONTAINER ENGINES section also states
what socket discovery deliberately does not do: Docker contexts
(`currentContext`, `~/.docker/contexts/meta/*/meta.json`) are never
consulted, unlike the `docker` CLI, docker-java or Testcontainers.
0.002 2026-05-17 05:36:20Z
- HTTP role: `_request` now accepts a `headers => {}` option to set
extra HTTP request headers. Headers are sanitised against CR/LF
injection. Used by `images->push` to send `X-Registry-Auth`, and
available to any caller that needs custom headers.
- `images->push` now always sends an `X-Registry-Auth` header â the
Docker Engine refuses pushes without it (`HTTP 400: missing
X-Registry-Auth: invalid X-Registry-Auth header: EOF`). A new `auth`
option accepts a hashref of credentials (`username`, `password`,
t/fixtures/system_version.json
t/fixtures/volumes_list.json
t/images.t
t/images_build_prune.t
t/images_commit.t
t/images_push_auth.t
t/images_registry_auth.t
t/images_tar.t
t/json_body_booleans.t
t/legacy_stubs.t
t/lib/Test/API/Docker/FakeTransport.pm
t/lib/Test/API/Docker/Mock.pm
t/mock_harness.t
t/network_status.t
t/networks.t
t/plugins.t
t/read_timeout.t
t/registry_auth.t
t/release-changes_has_content.t
t/request_write.t
t/role_http.t
t/secrets_configs.t
"configure" : {
"requires" : {
"ExtUtils::MakeMaker" : "0"
}
},
"develop" : {
"recommends" : {
"Dist::Zilla::PluginBundle::Git::VersionManager" : "0.007"
},
"requires" : {
"Test::Pod" : "1.41",
"YAML::XS" : "0"
}
},
"runtime" : {
"recommends" : {
"IO::Socket::SSL" : "0"
},
"requires" : {
"Carp" : "0",
"Errno" : "0",
"Types::Standard" : "0",
"namespace::clean" : "0",
"overload" : "0",
"perl" : "5.014"
}
},
"test" : {
"requires" : {
"Exporter" : "0",
"Path::Tiny" : "0",
"Test::More" : "0"
}
}
},
"provides" : {
"API::Docker" : {
"file" : "lib/API/Docker.pm",
"version" : "0.006"
},
"API::Docker::API::Configs" : {
"file" : "lib/API/Docker/API/Configs.pm",
"class" : "Dist::Zilla::Plugin::MetaYAML",
"name" : "@Author::GETTY/@Filter/MetaYAML",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::Readme",
"name" : "@Author::GETTY/@Filter/Readme",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::ExtraTests",
"name" : "@Author::GETTY/@Filter/ExtraTests",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::ExecDir",
"name" : "@Author::GETTY/@Filter/ExecDir",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::ShareDir",
"name" : "@Author::GETTY/@Filter/ShareDir",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::MakeMaker",
"config" : {
"Dist::Zilla::Role::TestRunner" : {
"default_jobs" : 1
}
},
"name" : "@Author::GETTY/@Filter/MakeMaker",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::Manifest",
"name" : "@Author::GETTY/@Filter/Manifest",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::TestRelease",
"name" : "@Author::GETTY/@Filter/TestRelease",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::UploadToCPAN",
"name" : "@Author::GETTY/@Filter/UploadToCPAN",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::Author::GETTY::InstallCheck",
"name" : "@Author::GETTY/Author::GETTY::InstallCheck",
"class" : "Dist::Zilla::Plugin::MetaConfig",
"name" : "@Author::GETTY/MetaConfig",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::MetaJSON",
"name" : "@Author::GETTY/MetaJSON",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::PodSyntaxTests",
"name" : "@Author::GETTY/PodSyntaxTests",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::Test::ChangesHasContent",
"name" : "@Author::GETTY/Test::ChangesHasContent",
"version" : "0.011"
},
{
"class" : "Dist::Zilla::Plugin::MetaProvides::Package",
"config" : {
"Dist::Zilla::Plugin::MetaProvides::Package" : {
"finder_objects" : [
{
"class" : "Dist::Zilla::Plugin::FinderCode",
"name" : "@Author::GETTY/MetaProvides::Package/AUTOVIV/:InstallModulesPM",
"name" : ":InstallModules",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::FinderCode",
"name" : ":IncModules",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::FinderCode",
"name" : ":TestFiles",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::FinderCode",
"name" : ":ExtraTestFiles",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::FinderCode",
"name" : ":ExecFiles",
"version" : "6.040"
},
{
"class" : "Dist::Zilla::Plugin::FinderCode",
"name" : ":PerlExecFiles",
---
abstract: 'Perl client for the Docker Engine API'
author:
- 'Torsten Raudssus <getty@cpan.org>'
build_requires:
Exporter: '0'
Path::Tiny: '0'
Test::More: '0'
configure_requires:
ExtUtils::MakeMaker: '0'
dynamic_config: 0
generated_by: 'Dist::Zilla version 6.040, CPAN::Meta::Converter version 2.150010'
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: '1.4'
name: API-Docker
provides:
version: '6.040'
-
class: Dist::Zilla::Plugin::MetaYAML
name: '@Author::GETTY/@Filter/MetaYAML'
version: '6.040'
-
class: Dist::Zilla::Plugin::Readme
name: '@Author::GETTY/@Filter/Readme'
version: '6.040'
-
class: Dist::Zilla::Plugin::ExtraTests
name: '@Author::GETTY/@Filter/ExtraTests'
version: '6.040'
-
class: Dist::Zilla::Plugin::ExecDir
name: '@Author::GETTY/@Filter/ExecDir'
version: '6.040'
-
class: Dist::Zilla::Plugin::ShareDir
name: '@Author::GETTY/@Filter/ShareDir'
version: '6.040'
-
class: Dist::Zilla::Plugin::MakeMaker
config:
Dist::Zilla::Role::TestRunner:
default_jobs: 1
name: '@Author::GETTY/@Filter/MakeMaker'
version: '6.040'
-
class: Dist::Zilla::Plugin::Manifest
name: '@Author::GETTY/@Filter/Manifest'
version: '6.040'
-
class: Dist::Zilla::Plugin::TestRelease
name: '@Author::GETTY/@Filter/TestRelease'
version: '6.040'
-
class: Dist::Zilla::Plugin::UploadToCPAN
name: '@Author::GETTY/@Filter/UploadToCPAN'
version: '6.040'
-
class: Dist::Zilla::Plugin::Author::GETTY::InstallCheck
name: '@Author::GETTY/Author::GETTY::InstallCheck'
version: '0.328'
-
version: '0.002'
-
class: Dist::Zilla::Plugin::MetaConfig
name: '@Author::GETTY/MetaConfig'
version: '6.040'
-
class: Dist::Zilla::Plugin::MetaJSON
name: '@Author::GETTY/MetaJSON'
version: '6.040'
-
class: Dist::Zilla::Plugin::PodSyntaxTests
name: '@Author::GETTY/PodSyntaxTests'
version: '6.040'
-
class: Dist::Zilla::Plugin::Test::ChangesHasContent
name: '@Author::GETTY/Test::ChangesHasContent'
version: '0.011'
-
class: Dist::Zilla::Plugin::MetaProvides::Package
config:
Dist::Zilla::Plugin::MetaProvides::Package:
finder_objects:
-
class: Dist::Zilla::Plugin::FinderCode
name: '@Author::GETTY/MetaProvides::Package/AUTOVIV/:InstallModulesPM'
version: '6.040'
-
class: Dist::Zilla::Plugin::FinderCode
name: ':InstallModules'
version: '6.040'
-
class: Dist::Zilla::Plugin::FinderCode
name: ':IncModules'
version: '6.040'
-
class: Dist::Zilla::Plugin::FinderCode
name: ':TestFiles'
version: '6.040'
-
class: Dist::Zilla::Plugin::FinderCode
name: ':ExtraTestFiles'
version: '6.040'
-
class: Dist::Zilla::Plugin::FinderCode
name: ':ExecFiles'
version: '6.040'
-
class: Dist::Zilla::Plugin::FinderCode
name: ':PerlExecFiles'
version: '6.040'
-
Makefile.PL view on Meta::CPAN
"Path::Tiny" => 0,
"Scalar::Util" => 0,
"Socket" => 0,
"Types::Standard" => 0,
"namespace::clean" => 0,
"overload" => 0
},
"TEST_REQUIRES" => {
"Exporter" => 0,
"Path::Tiny" => 0,
"Test::More" => 0
},
"VERSION" => "0.006",
"test" => {
"TESTS" => "t/*.t"
}
);
my %FallbackPrereqs = (
"Carp" => 0,
Makefile.PL view on Meta::CPAN
"Import::Into" => 0,
"JSON::MaybeXS" => 0,
"Log::Any" => 0,
"MIME::Base64" => 0,
"Module::Runtime" => 0,
"Moo" => 0,
"Package::Stash" => 0,
"Path::Tiny" => 0,
"Scalar::Util" => 0,
"Socket" => 0,
"Test::More" => 0,
"Types::Standard" => 0,
"namespace::clean" => 0,
"overload" => 0
);
unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) {
delete $WriteMakefileArgs{TEST_REQUIRES};
delete $WriteMakefileArgs{BUILD_REQUIRES};
$WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs;
# Only the tcp:// transport with tls => 1 loads this, and it is loaded at the
# moment that connection is opened. It brings in Net::SSLeay, which is XS
# compiled against libssl; requiring it would make this client unbuildable
# where there are no OpenSSL headers, for the sake of a transport that the
# unix:// default -- local Docker, rootless Podman -- never uses.
recommends 'IO::Socket::SSL';
on test => sub {
requires 'Exporter';
requires 'Path::Tiny';
requires 'Test::More';
};
# The drift checker under maint/ reads Docker's swagger from spec/ and the
# exceptions file beside itself. YAML::XS rather than YAML::PP is not a
# preference: YAML::PP 0.41 will not parse the file Docker publishes -- see
# the comment at the top of maint/spec-drift-check.pl. Nothing under lib/
# loads a YAML parser.
on develop => sub {
requires 'YAML::XS';
};
lib/API/Docker.pm view on Meta::CPAN
L</host> resolves in two steps and no more: C<$ENV{DOCKER_HOST}>, then
C<unix:///var/run/docker.sock>. It deliberately does B<not> read Docker
contexts. C<currentContext> in F<~/.docker/config.json> and the matching
F<~/.docker/contexts/meta/*/meta.json> are ignored, so if you switch daemons
with C<docker context use>, that choice is not picked up here. Set
C<DOCKER_HOST> explicitly instead.
Other clients sit at different points on that scale. The C<docker> CLI and
docker-java resolve contexts, with C<DOCKER_HOST> outranking them when set.
docker-py's C<from_env()> reads C<DOCKER_HOST> and otherwise falls back to the
default socket, leaving contexts to a separate API. Testcontainers layers its
own F<~/.testcontainers.properties> and a rootless probe list
(C<$XDG_RUNTIME_DIR/docker.sock>, F<~/.docker/run/docker.sock>,
F<~/.docker/desktop/docker.sock>, C</run/user/$UID/docker.sock>) on top.
What none of them do is guess Podman's socket path: that probe list is for
rootless Docker, not for Podman. Every one of those projects documents
C<DOCKER_HOST> as the way to reach Podman, which is the same answer given
above.
=head1 ENVIRONMENT VARIABLES
misc/agent-context/.claude/agents/api-docker-test-writer.md view on Meta::CPAN
---
name: api-docker-test-writer
description: "Write API::Docker tests with Test::More and the Test::API::Docker::Mock route table. The default suite never touches a Docker daemon or the network; live paths stay gated on is_live()/can_write(). Use for test additions, regression scaf...
model: sonnet
briefing:
skills:
- api-docker-core
- api-docker-hazards
- docker-engine-api
- getty-perl-core
- getty-perl-moo
- kanban-issues-karr-ticket
---
misc/agent-context/.claude/agents/api-docker-test-writer.md view on Meta::CPAN
it existed to catch. Never normalise the value under test on the way into the
assertion.
- **Live and mock must both be able to pass, or the assertion is gated.** `test_docker`
ignores the route table entirely under `API_DOCKER_TEST_HOST` â an assertion tied to
fixture contents runs against a real daemon's data otherwise.
New fixtures are captured from a real daemon into `t/fixtures/*.json`, never hand-rolled
â and that includes wire formats. A test for the multiplexed log stream asserts against
bytes the engine actually produced, not against a frame header written from memory; the
Engine API reference above tells you what to expect, the socket tells you what is true.
Test filenames follow the existing flat, topical naming (`t/images.t`,
`t/images_push_auth.t`), one file per resource or per defect.
A test asserts intent: it must be able to fail when the logic changes. Reproduce a bug
before fixing it and leave the regression behind. Verify with `prove -lr t/`; a single
file with `prove -lv t/NN.t`.
misc/agent-context/.claude/rules/.local.engineering-discipline.md view on Meta::CPAN
adjacent code, comments and formatting alone.
4. **Read before you write** â Before new code, read the exports, the immediate callers and
the shared utilities; the project rules name the modules to read first. "Looks
orthogonal" is dangerous.
5. **Match the codebase's conventions, even if you disagree** â Conformance over taste.
Surface a harmful convention; never fork silently.
6. **Surface conflicts, don't average them** â When patterns contradict, pick one (more
recent, better tested), say why, and flag the other for cleanup.
7. **Goal-driven execution** â Define the success criteria first, then loop until they are
verified.
8. **Tests verify intent, not just behavior** â Reproduce a bug before fixing it and leave
the regression test behind; a test that cannot fail when the logic changes proves
nothing. A red test is a claim before it is a failure: say what it asserts and whether
your fix keeps that claim or replaces it. If the claim is wrong, fix the claim and say so.
9. **Back up before anything destructive** â Deleting, purging, overwriting, force-pushing,
migrating data: make it recoverable first (backup, branch, snapshot), or ask.
10. **Checkpoint, don't overrun** â After each significant step: done / verified / left.
Never continue from a state you can't describe back. When a session grows long or
muddy, summarize and start fresh rather than grind on.
11. **Fail loud** â "Done" is wrong if anything was skipped silently; report passed, failed
and skipped as they are â name every suite that skipped itself (missing dependency,
misc/agent-context/.claude/skills/api-docker-core/SKILL.md view on Meta::CPAN
resource method goes through it (usually via `get`/`post`/`put`/`delete_request`).
A new endpoint never opens its own socket.
Options: `body` (JSON-encoded), `raw_body` + `content_type` (tarballs for
`/build`), `params` (query string), `headers` (extra request headers),
`on_event`/`on_frame`/`on_chunk` (streaming callbacks, see below).
`_request` prefixes the path with `/v$api_version`. `around _request` in
`API::Docker` triggers `negotiate_version` on the first call that is not
`/version` â so a mock that replaces `_request` must strip the `/vX.YZ` prefix
itself, which `Test::API::Docker::Mock` does.
## Invariants
- **`list` and `inspect` return generated `API::Docker::Type::*` objects**
(via `_wrap`/`_wrap_list`); everything else returns the raw daemon response.
`Networks`, `Volumes`, `Plugins`, `Secrets` and `Configs` answer both calls
with one class (one swagger definition each â `API::Docker::Type::Network`,
etc.); `Containers` and `Images` have two each â `ContainerSummary` /
`ContainerInspectResponse`, `ImageSummary` / `ImageInspect` (see
`API::Docker::API::Containers/"The two container shapes"`). Which resources
misc/agent-context/.claude/skills/api-docker-core/SKILL.md view on Meta::CPAN
`IO::Socket::SSL` in place of the plain socket â same reader, same writer,
same everything above it. `cert_path` names a directory in the `docker`
CLI's own layout (`ca.pem` trust anchor, `cert.pem`+`key.pem` this client's
identity), defaulting from `$ENV{DOCKER_CERT_PATH}`; `tls_insecure => 1`
turns verification off. `IO::Socket::SSL` is a recommended, not required,
dependency, loaded only once a TLS connection is opened. Detail:
`API::Docker::Role::HTTP`'s "TLS on a tcp:// connection".
- **No connection reuse.** Each `_request` calls `_reconnect` and closes
afterwards, streamed or not.
## Tests â `Test::API::Docker::Mock`
`test_docker('GET /images/json' => $fixture_or_coderef, ...)` returns a client
whose `_request` dispatches against the route table (exact key first, then the
key matched as a literal path -- it is `\Q..\E`-escaped, not a regex, so a
metacharacter in a route key means itself). A `GET /version` route is injected
when none is given.
**In live mode `test_docker` ignores the routes entirely** and returns a real
client against `$ENV{API_DOCKER_TEST_HOST}`. An assertion that only holds for
the fixture must sit behind `is_live()`; mutating tests behind `can_write()` /
misc/agent-context/.claude/skills/docker-engine-api/examples/python/README.md view on Meta::CPAN
Select the actual socket first; do not run as root merely to bypass an unknown permission problem. For rootless Docker, pass the verified user socket path. The example's default supported range is 1.40â1.51 for its small read-only surface. It inter...
Container names, image names, IDs, and endpoints may be sensitive. Review output before sharing. Registry-auth helper output is credential material; never log it.
## Deliberate exclusions
No automatic Docker-context parsing, SSH transport, Windows named pipes, TLS transport, hijacked/interactive connections, retrying mutations, streaming content-type negotiation, registry credential helper integration, or full API coverage. Use a main...
## Integration evidence
Unit tests prove parser/helper behavior against fixtures only. Add tests against every advertised daemon version, platform, transport, and compatible implementation before production use. Test lost responses and effective policy enforcement, not only...
misc/agent-context/.claude/skills/docker-engine-api/examples/python/tests/test_engine_helpers.py view on Meta::CPAN
class ShortReader(io.BytesIO):
def read(self, size=-1):
return super().read(min(size, 1) if size >= 0 else 1)
def frame(kind, payload):
return bytes([kind, 0, 0, 0]) + struct.pack('>I', len(payload)) + payload
class VersionTests(unittest.TestCase):
def choose(self, server, **kwargs):
return negotiate_version(server, client_min='1.40', client_max='1.51', **kwargs)
def test_new_server_capped(self):
self.assertEqual(self.choose({'ApiVersion':'1.56','MinAPIVersion':'1.40'}), '1.51')
def test_old_server(self):
self.assertEqual(self.choose({'ApiVersion':'1.47','MinAPIVersion':'1.24'}), '1.47')
def test_disjoint(self):
with self.assertRaises(CompatibilityError): self.choose({'ApiVersion':'1.39','MinAPIVersion':'1.24'})
def test_new_min_disjoint(self):
misc/agent-context/.claude/skills/docker-engine-api/examples/python/tests/test_engine_helpers.py view on Meta::CPAN
with self.assertRaises(CompatibilityError): self.choose({'ApiVersion':'1.47'})
def test_explicit_legacy(self):
self.assertEqual(self.choose({'ApiVersion':'1.47'}, legacy_server_min='1.24'), '1.47')
def test_valid_pin(self):
self.assertEqual(self.choose({'ApiVersion':'1.51','MinAPIVersion':'1.40'}, pin='1.47'), '1.47')
def test_invalid_pin(self):
with self.assertRaises(CompatibilityError): self.choose({'ApiVersion':'1.51','MinAPIVersion':'1.40'}, pin='1.52')
def test_numeric_order(self): self.assertLess(parse_version('1.9'), parse_version('1.10'))
def test_bad_versions(self):
for value in ('1', '1.2.3', 'v1.51', '1.01', 1.51, None, True):
with self.subTest(value=value), self.assertRaises(CompatibilityError): parse_version(value)
def test_reversed_range(self):
with self.assertRaises(CompatibilityError): self.choose({'ApiVersion':'1.40','MinAPIVersion':'1.51'})
class AuthTests(unittest.TestCase):
def test_empty_padding(self): self.assertEqual(encode_registry_auth({}), 'e30=')
def test_round_trip(self):
obj={'username':'test','password':'äð','serveraddress':'registry.example.com'}
value=encode_registry_auth(obj)
self.assertEqual(json.loads(base64.urlsafe_b64decode(value)), obj)
self.assertNotIn('+',value)
self.assertNotIn('/',value)
def test_reject_non_string(self):
with self.assertRaises(TypeError): encode_registry_auth({'password':123})
class FrameTests(unittest.TestCase):
def test_short_reads(self):
self.assertEqual(list(iter_output(ShortReader(frame(1,b'OUT\n')+frame(2,b'ERR\n')))),[(1,b'OUT\n'),(2,b'ERR\n')])
def test_empty(self): self.assertEqual(list(iter_output(io.BytesIO())),[])
def test_zero_frame(self): self.assertEqual(list(iter_output(io.BytesIO(frame(1,b'')))),[(1,b'')])
def test_stdin_kind(self): self.assertEqual(list(iter_output(io.BytesIO(frame(0,b'x')))),[(0,b'x')])
def test_system_error(self):
with self.assertRaisesRegex(DaemonStreamError,'failure'): list(iter_output(io.BytesIO(frame(3,b'failure'))))
def test_bad_kind(self):
with self.assertRaises(ProtocolError): list(iter_output(io.BytesIO(frame(9,b''))))
def test_reserved(self):
misc/agent-context/.claude/skills/docker-engine-api/examples/python/tests/test_engine_helpers.py view on Meta::CPAN
self.assertEqual(b''.join(data for _,data in iter_output(io.BytesIO(frame(1,raw[:1])+frame(1,raw[1:])))),raw)
def test_nonblocking_reader(self):
class R:
def read(self,n): return None
with self.assertRaises(ProtocolError): read_exact(R(),8)
def test_zero_exact(self): self.assertEqual(read_exact(io.BytesIO(),0),b'')
def test_invalid_limit(self):
with self.assertRaises(ValueError): list(iter_output(io.BytesIO(),max_frame_bytes=0))
class NDJSONTests(unittest.TestCase):
def test_fragmented_final_line(self):
raw=b'{"status":"one"}\n{"status":"two"}'
self.assertEqual(list(iter_ndjson(ShortReader(raw))),[{'status':'one'},{'status':'two'}])
def test_crlf_and_blanks(self): self.assertEqual(list(iter_ndjson(io.BytesIO(b'\r\n{}\r\n\n'))),[{}])
def test_invalid_json(self):
with self.assertRaises(ProtocolError): list(iter_ndjson(io.BytesIO(b'{bad}\n')))
def test_invalid_utf8(self):
with self.assertRaises(ProtocolError): list(iter_ndjson(io.BytesIO(b'{"x":"\xff"}\n')))
def test_object_only(self):
with self.assertRaises(ProtocolError): list(iter_ndjson(io.BytesIO(b'[]\n')))
misc/agent-context/.claude/skills/docker-engine-api/references/clients/podman-and-other-engines.md view on Meta::CPAN
# Podman compatibility and other Engine-like implementations
> Read when: running a Docker API client against a non-Docker endpoint.
Podman's API service provides a Docker-compatible surface and a separate native Libpod surface. The current service documentation describes compatibility with Docker API v1.40 and notes that unsupported version prefixes are not rejected in the same w...
On Linux, rootless socket activation commonly exposes `$XDG_RUNTIME_DIR/podman/podman.sock`; rootful service and remote Desktop/VM setups differ. Confirm the endpoint and identity rather than inferring it from the command name.
## Capability tests, not product-name branching alone
Test discovery/version behavior, create/start/wait/remove, health fields, event payloads, logs with and without TTY, exec completion, volume ownership, filters, auth headers, build targets, and archive behavior. Record differences as supported adapta...
The absence of a version error does not prove support for every field at that prefix. Require effective-state verification for security restrictions. Preserve original server errors as diagnostics but do not parse product-specific English strings for...
## Security and transport
Podman's service still grants powerful access as the user running it. Rootless means a different privilege boundary, not harmless remote code execution. Use a local protected socket or authenticated remote transport and do not expose a naked TCP API....
For other compatibility daemons, require the same matrix. A successful `/_ping` and one container create are insufficient to claim Docker compatibility. Route native Libpod functionality to its own API client instead of pretending it is part of Docke...
## Primary sources
misc/agent-context/.claude/skills/docker-engine-api/references/http/request-shapes-and-encoding.md view on Meta::CPAN
```python
from urllib.parse import urlencode
import json
query = urlencode({"filters": json.dumps({"label": ["owner=example"]}), "all": "true"})
```
## Paths and references
Container names and unambiguous ID prefixes may be accepted, but store full IDs for ownership and subsequent mutations. Leading `/` in list-result names is a presentation/API convention, not something to copy blindly into a name-creation field.
Registry image references can contain host ports, repository slashes, tags, and digests. Use an endpoint-specific reference encoder and preserve the route's expected structure. Do not claim percent-encoding always breaks image paths; client, router, ...
## Input safety
Do not concatenate untrusted strings into paths, query strings, shell commands, or JSON text. Validate resource ownership separately from identifier syntax. Reject control characters and unexpected reference forms before request construction. Log san...
## Primary sources
- [Pinned Moby 28.5.2 API 1.51 schema (compatibility evidence, not latest)](https://raw.githubusercontent.com/moby/moby/v28.5.2/docs/api/v1.51.yaml)
- [Pinned Moby filter parser](https://raw.githubusercontent.com/moby/moby/v28.5.2/api/types/filters/parse.go)
- [Engine events behavior](https://docs.docker.com/reference/cli/docker/system/events/)
misc/agent-context/.claude/skills/docker-engine-api/references/observability/events-and-reconciliation.md view on Meta::CPAN
Establish an event stream and buffer a bounded overlap while obtaining a current snapshot. Reconcile by full resource ID and daemon identity. Apply buffered events, then continue streaming. Periodically reconcile authoritative list/inspect state agai...
There is no globally reliable monotonically increasing event ID you can treat as a Kafka offset. A composite deduplication key can include daemon, resource, action, timestamp, and selected attributes, but collisions/repeats still require idempotent s...
Keep filters narrow enough for workload and resource ownership, but do not filter out the lifecycle transitions needed to detect removals. Events from one Engine do not provide cluster-wide truth for unrelated daemons. Swarm event scope also differs ...
## Failure behavior
Separate stream health from workload health. A quiet connection may be normal, while a frozen proxy can look identical without a heartbeat/reconciliation policy. Do not restart workloads merely because the watcher lost connectivity. Bound reconnect b...
Store meaningful operational audit outside the daemon with redaction and retention. Test a burst larger than the retention window, a daemon restart, observer downtime, duplicate delivery, removal between list and inspect, and unknown event attributes...
## Primary sources
- [Engine events behavior](https://docs.docker.com/reference/cli/docker/system/events/)
- [Pinned Moby 28.5.2 API 1.51 schema (compatibility evidence, not latest)](https://raw.githubusercontent.com/moby/moby/v28.5.2/docs/api/v1.51.yaml)
- [Engine API version history](https://docs.docker.com/reference/api/engine/version-history/)
misc/agent-context/.claude/skills/docker-engine-api/references/observability/stats-and-accounting.md view on Meta::CPAN
Memory `usage` and the CLI's displayed âused memoryâ can differ because Docker's CLI subtracts cache-related values on Linux. cgroup v1/v2 expose different cache field names. Windows has different accounting again. Do not label every memory count...
## Collector design
Use bounded streaming connections or periodic one-shot requests according to fleet size. Deduplicate collection for consumers watching the same container. Separate polling concurrency from mutation capacity. Treat disappearing containers as expected ...
Record timestamp, daemon/container identity, sample interval, OS/cgroup context, raw counters needed for later interpretation, and computed values. Reset derivative state when identity or counter epoch changes. Percentages need a denominator: contain...
## Validation
Compare a controlled CPU workload and a memory/cache workload against the native CLI on the same host, then explain expected display differences. Test a container with limits, an unconstrained one, a stopped/removed one, and a rootless or Windows tar...
## Primary sources
- [Stats display versus API counters](https://docs.docker.com/reference/cli/docker/container/stats/)
- [Container resource constraints](https://docs.docker.com/engine/containers/resource_constraints/)
- [Pinned Moby 28.5.2 API 1.51 schema (compatibility evidence, not latest)](https://raw.githubusercontent.com/moby/moby/v28.5.2/docs/api/v1.51.yaml)
misc/agent-context/.claude/skills/docker-engine-api/references/resources/archives-and-copy.md view on Meta::CPAN
Treat archive paths as untrusted input. Before extraction, validate normalized paths stay inside the chosen destination. Reject absolute paths, `..` escapes, unsafe symlink/hardlink targets, and special device files unless explicitly required and app...
Use the archive library's current safe-extraction facilities where available and still define application policy; library defaults differ by version. A lexical path check alone is insufficient if symlinks in the destination can redirect later writes....
## Data consistency
Copying files from a running database container does not automatically produce a consistent backup. Mounted data and image/container layers have distinct lifecycles. Container export is not equivalent to image save and is not a backup of all attached...
## Permissions and direction
Copy source/destination semantics, directory existence, ownership, and symlink behavior can differ from a familiar local `cp`. Test the exact API direction and path shape. Do not grant arbitrary host destination paths through an agent-facing âdownl...
For uploads, ensure the destination is owned by the intended container and that overwriting config or executables is authorized. For downloads, redact or exclude secrets before exposing artifacts. Test traversal, deep nesting, oversized payloads, lin...
## Primary sources
- [Container copy and archive semantics](https://docs.docker.com/reference/cli/docker/container/cp/)
- [Pinned Moby 28.5.2 API 1.51 schema (compatibility evidence, not latest)](https://raw.githubusercontent.com/moby/moby/v28.5.2/docs/api/v1.51.yaml)
misc/agent-context/.claude/skills/docker-engine-api/references/streams/multiplexed-output.md view on Meta::CPAN
The usual output types are stdout=1 and stderr=2. Pinned Moby `stdcopy` also recognizes stdin=0 and system-error=3. Type 3 must not be silently displayed as ordinary application output. Treat unknown frame kinds as a protocol/compatibility event.
With TTY enabled, output is a raw PTY byte stream: no Docker multiplex headers and no recoverable stdout/stderr separation. Do not decide framing by sniffing the first bytes of arbitrary application output. Use known TTY configuration and endpoint be...
## Defensive decoder requirements
Read exactly eight header bytes across partial reads. Validate header/type according to your compatibility policy. Bound payload allocation and total buffering. Read the announced payload fully; distinguish clean EOF at a frame boundary from truncati...
The included helper intentionally rejects truncated frames and oversized payloads. Those are **client safety choices**, not a promise that every upstream decoder rejects them identically. Its default size cap is configurable and must be sized for the...
Test single-byte reads, multiple frames per read, zero-length frames, split UTF-8, system errors, invalid headers, truncated payloads, and TTY bypass. A clean interactive TTY test alone cannot validate a non-TTY log client.
## Primary sources
- [Pinned Moby stdcopy framing implementation](https://raw.githubusercontent.com/moby/moby/v28.5.2/pkg/stdcopy/stdcopy.go)
- [Docker Python SDK multiplexed streams](https://docker-py.readthedocs.io/en/stable/user_guides/multiplex.html)
- [Pinned Moby 28.5.2 API 1.51 schema (compatibility evidence, not latest)](https://raw.githubusercontent.com/moby/moby/v28.5.2/docs/api/v1.51.yaml)
misc/agent-context/.claude/skills/docker-engine-api/references/testing-and-conformance.md view on Meta::CPAN
|---|---|
| Version | Oldest supported, newest supported, newer-than-client, disjoint range |
| Transport | Every supported Unix/TLS/SSH/npipe path; actual reverse proxy if any |
| Engine | Docker rootful/rootless; Podman only when advertised |
| Platform | Linux/Windows and architectures actually supported |
| Streams | TTY/non-TTY, slow consumer, partial write/read, abrupt disconnect |
| Lifecycle | Fast exit, nonzero exit, timeout, lost create response, auto-remove race |
| Security | Rejected unsafe mounts/privileges; effective-state verification |
| Storage | Archive traversal, permissions, volume retention, scoped cleanup |
Use a dedicated disposable daemon/project, never a shared production target. Give fixtures unique labels and clean up only their IDs. Test no-op/status behavior and compare with the selected schema. Introduce an in-band pull/build failure after succe...
## Evidence report
Record versions, daemon identity, feature scope, tested transports, test results, known limitations, and unresolved discrepancies. Distinguish syntax/unit validation from a live daemon test. The delivery's validation report states which checks were a...
Before extending support, add a failing regression fixture that represents the new behavior. Do not broaden advertised compatibility merely because an API prefix is accepted or a server returns extra fields without error.
## Primary sources
- [Engine API overview and version matrix](https://docs.docker.com/reference/api/engine/)
misc/agent-context/.claude/skills/docker-engine-api/references/transport/version-negotiation.md view on Meta::CPAN
Do **not** simply adopt the server maximum: the client may not understand it. Prefix subsequent versioned operations with the selected version. Feature requirements must fit that version, and platform/implementation support must still be verified.
## Overrides and missing discovery fields
An explicit API version setting is a pin, not negotiation. Check that the chosen version lies within both supported ranges. Official CLI/SDK `DOCKER_API_VERSION` behavior can disable negotiation; make that visible in diagnostics.
For old or compatible implementations that omit a minimum version, choose and document a legacy compatibility policy. The included helper fails closed unless a caller supplies a deliberate fallback. Do not invent a server minimum silently. An unavail...
## Upgrade test cases
Test older server, newer server, disjoint ranges, explicit pin outside range, missing/malformed fields, and numeric ordering. Test a supported field and a field introduced later than the selected version. A server that ignores unknown fields can othe...
The included Python helper implements range intersection and pin validation with unit tests. Its configured client range belongs to the caller; its existence does not prove that the caller actually implements every endpoint in that range.
## Primary sources
- [Engine API overview and version matrix](https://docs.docker.com/reference/api/engine/)
- [Engine API version history](https://docs.docker.com/reference/api/engine/version-history/)
- [Pinned Moby 28.5.2 API 1.51 schema (compatibility evidence, not latest)](https://raw.githubusercontent.com/moby/moby/v28.5.2/docs/api/v1.51.yaml)
misc/agent-context/.claude/skills/perl-release-dist-ini/SKILL.md view on Meta::CPAN
| `[@Bundle]` | Plugin bundle |
| `[Plugin]` | Individual plugin |
## Plugin Loading Order
1. `[GatherDir]` - Collects files
2. `[PruneCruft]` - Removes unwanted files
3. `[Prereqs]` / `cpanfile` - Dependencies
4. `[Version plugins]` - PkgVersion, AutoVersion, etc.
5. `[Meta plugins]` - MetaJSON, MetaYAML
6. `[Test plugins]` - Tests
7. `[Release plugins]` - UploadToCPAN, etc.
8. `[VCS plugins]` - Git::Commit, Git::Tag, etc.
## Key Questions
1. Which plugin bundle is used?
2. Are there custom plugins configured?
3. Are prereqs in dist.ini or cpanfile?
4. What release mechanism is configured?
5. What is the version in dist.ini â and does the bundle auto-bump it post-release or is it manual?
misc/agent-context/CLAUDE.md view on Meta::CPAN
lib/API/Docker/Error/Truncated.pm # croaked when the daemon closed before its announced response was complete
maint/spec-to-type.pl # generates lib/API/Docker/Type/*.pm from spec/ -- never overwrites
maint/spec-drift-check.pl # diffs spec/ against the registry, and spec against spec
maint/spec-common.pl # the spec loader shared by the two scripts above
maint/spec-to-type-names.yaml # inline-class naming exceptions the generator and checker share
maint/spec-to-type-prose.yaml # hand-written POD for fields/classes the swagger describes poorly
maint/spec-drift-exceptions.yaml # deliberate deviations the drift checker accepts
maint/spec-overlay.yaml # named fields of v1.55 grafted onto the v1.51 base model
spec/v1.41.yaml .. v1.55.yaml # Docker's own swagger, checked in; generation runs against v1.51 plus the overlay
t/ # tests (prove -lr t/)
t/lib/Test/API/Docker/Mock.pm # fixture-driven mock helper
t/fixtures/*.json # captured daemon responses
.claude/agents/ # the api-docker-* subagents
.claude/rules/api-docker-rules.md # house rules, auto-loaded every turn
.claude/skills/ # briefed skills (owned + skilletor-installed)
```
## Build and test
```bash
prove -lr t/ # canonical â recursive; plain `prove -l t/` skips subdirs
t/author-pod-syntax.t view on Meta::CPAN
#!perl
BEGIN {
unless ($ENV{AUTHOR_TESTING}) {
print qq{1..0 # SKIP these tests are for testing by the author\n};
exit
}
}
# This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests
use strict; use warnings;
use Test::More;
use Test::Pod 1.41;
all_pod_files_ok();
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use_ok('API::Docker');
use_ok('API::Docker::Role::HTTP');
use_ok('API::Docker::API::System');
use_ok('API::Docker::API::Containers');
use_ok('API::Docker::API::Images');
use_ok('API::Docker::API::Networks');
use_ok('API::Docker::API::Volumes');
use_ok('API::Docker::API::Exec');
use_ok('API::Docker::API::Distribution');
use_ok('API::Docker::API::Plugins');
use_ok('API::Docker::Role::Entity');
use_ok('API::Docker::Role::Entity::Container');
use_ok('API::Docker::Role::Entity::Image');
use_ok('API::Docker::Role::Entity::Network');
use_ok('API::Docker::Role::Entity::Volume');
use_ok('API::Docker::Role::Entity::Plugin');
use_ok('API::Docker::Role::Entity::Secret');
use_ok('API::Docker::Role::Entity::Config');
# Test default construction. host resolves DOCKER_HOST before the socket path,
# so the socket default is only observable with that variable gone -- any
# machine pointing at rootless Podman has it set, and this test used to read it.
my $docker;
{
delete local $ENV{DOCKER_HOST};
$docker = API::Docker->new(api_version => '1.47');
}
isa_ok($docker, 'API::Docker');
is($docker->host, 'unix:///var/run/docker.sock', 'default host');
local $ENV{DOCKER_HOST} = 'tcp://from-env:2375';
is(
API::Docker->new(api_version => '1.47')->host,
'tcp://from-env:2375',
'DOCKER_HOST outranks the socket default',
);
}
is($docker->api_version, '1.47', 'api_version set');
is($docker->tls, 0, 'tls off by default');
# Test custom host
my $docker_tcp = API::Docker->new(
host => 'tcp://remote:2375',
api_version => '1.47',
);
is($docker_tcp->host, 'tcp://remote:2375', 'custom host');
# Test API accessors exist
can_ok($docker, qw(
system containers images networks volumes exec
distribution secrets configs plugins
));
# Test API accessor types
isa_ok($docker->system, 'API::Docker::API::System');
isa_ok($docker->containers, 'API::Docker::API::Containers');
isa_ok($docker->images, 'API::Docker::API::Images');
isa_ok($docker->networks, 'API::Docker::API::Networks');
isa_ok($docker->volumes, 'API::Docker::API::Volumes');
isa_ok($docker->exec, 'API::Docker::API::Exec');
isa_ok($docker->distribution, 'API::Docker::API::Distribution');
isa_ok($docker->secrets, 'API::Docker::API::Secrets');
isa_ok($docker->configs, 'API::Docker::API::Configs');
isa_ok($docker->plugins, 'API::Docker::API::Plugins');
t/connect_timeout.t view on Meta::CPAN
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Errno;
use File::Temp qw( tempdir );
use IO::Socket::UNIX;
use Time::HiRes qw( time );
use API::Docker;
use API::Docker::Error::Timeout;
# The connect timeout of API::Docker::Role::HTTP (karr k61).
#
# read_timeout (karr k59) bounds reading and nothing else, so a daemon that
t/connect_timeout.t view on Meta::CPAN
# not. connect_timeout is the other half.
#
# Nothing here reaches a Docker daemon and nothing here touches the network:
# the one end-to-end assertion runs against a local Unix listener whose backlog
# has been filled, which is the only way an AF_UNIX connect blocks at all. So
# there is no is_live()/can_write() gating -- it is unconditionally safe with
# no engine installed.
# A client that records what _build__socket was handed instead of connecting,
# so the per-request resolution can be asserted at the seam it has to cross.
package Test::ConnectTimeout::Probe;
use Moo;
extends 'API::Docker';
has seen => (is => 'ro', required => 1);
has pending => (is => 'ro', default => sub { [] });
sub _build__socket {
my ($self) = @_;
my $pending = $self->_pending_connect;
push @{ $self->seen }, $pending ? $pending->{timeout} : 'no pending';
t/connect_timeout.t view on Meta::CPAN
close $_ for @held;
close $srv;
};
# ---------------------------------------------------------------------------
subtest 'the per-request option overrides the attribute either way' => sub {
# What reached _build__socket, read where the constructors read it. Nothing
# about this can be seen from the outside -- the connect either blocks or it
# does not -- so the assertion is made at the seam the value has to cross.
my @seen;
my $probe = Test::ConnectTimeout::Probe->new(
host => 'unix:///nonexistent-api-docker-61.sock',
api_version => '1.41',
connect_timeout => 5,
seen => \@seen,
);
eval { $probe->get('/probe') };
eval { $probe->get('/probe', connect_timeout => 2) };
# Resolved with exists rather than truth, so 0 is "wait as long as it takes"
# rather than "no opinion", which is how a client-wide default is turned off
t/containers.t view on Meta::CPAN
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use lib 't/lib';
use Test::API::Docker::Mock;
use API::Docker::Role::Entity::Container;
use JSON::MaybeXS qw( encode_json );
check_live_access();
# --- Read Tests (always run) ---
# containers_list/container_inspect (karr k101 follow-up): a real capture,
# taken 2026-08-29 against Docker 29.7.2 (API 1.55) from a disposable
# apidocker-fixture-probe-<random> container (alpine:3, running `sleep 300`)
# created for the purpose and removed again once both endpoints were
# captured -- see the header of t/type_fixture_passthrough.t. Both fixtures
# describe the same container, so their Id fields agree; the list endpoint
# was filtered to that one container so the fixture stays small and
# deterministic, which is why there is only one to assert on here (a second,
# non-running container's is_running shape is covered directly, without a
t/containers.t view on Meta::CPAN
'b20ac7508d80182ba3cd1cbd006ac10c8a15f4f7590fa89c2078d146caf96555',
'container id');
is_deeply($first->names, ['/apidocker-fixture-probe-39a25e34'],
'container names');
is($first->image, 'alpine:3', 'container image');
is($first->state, 'running', 'container state');
ok($first->is_running, 'is_running returns true for running container');
}
};
# --- Write Tests (mock always, live only with WRITE) ---
subtest 'container lifecycle' => sub {
skip_unless_write();
my $name = 'api-docker-test-' . $$;
my $docker = test_docker(
'POST /containers/create' => sub {
my ($method, $path, %opts) = @_;
# containers->create moves `name` out of the config and into the
t/containers.t view on Meta::CPAN
},
);
my $result = $docker->containers->prune(filters => { until => ['24h'] });
is_deeply($result, { ContainersDeleted => ['abc'], SpaceReclaimed => 100 },
'the daemon response is returned unwrapped');
is_deeply($params->{filters}, { until => ['24h'] },
'the filters reached the query string, shape-normalised');
};
# --- Validation Tests (always run, no Docker needed) ---
subtest 'container ID required' => sub {
my $docker = test_docker();
eval { $docker->containers->inspect(undef) };
like($@, qr/Container ID required/, 'croak on missing ID for inspect');
eval { $docker->containers->start(undef) };
like($@, qr/Container ID required/, 'croak on missing ID for start');
t/containers_endpoints.t view on Meta::CPAN
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use FindBin;
use lib "$FindBin::Bin/lib";
use Test::API::Docker::Mock;
use JSON::MaybeXS qw( encode_json );
use MIME::Base64 qw( encode_base64 );
use API::Docker;
# The container endpoints this client did not expose:
#
# karr k18 GET/PUT/HEAD /containers/{id}/archive -- what docker cp is
# karr k19 POST /containers/{id}/attach -- the one-way variant
# karr k23 changes, export, resize
#
t/containers_endpoints.t view on Meta::CPAN
mtime => '2026-08-27T15:36:51.589296398Z',
linkTarget => '/etc/hostname',
);
my $STAT_HEADER = encode_base64(encode_json(\%STAT), '');
# ---------------------------------------------------------------------------
# A client whose socket is an in-memory sink and whose response is canned, so
# the real _request runs -- and with it raw => 1, raw_body, the query string
# and the verb. Same pattern as t/images_tar.t and t/streaming_shape.t; the
# mock harness replaces _request wholesale and can reach none of it.
package Test::ContainersEndpoints::FakeTransport;
use Moo;
extends 'API::Docker';
has canned => (is => 'rw', default => sub { [200, 'OK', {}, ''] });
has _sink => (is => 'rw');
sub _build__socket {
my ($self) = @_;
my $sink = '';
$self->_sink(\$sink);
t/containers_endpoints.t view on Meta::CPAN
}
sub request_body {
my ($body) = $_[0]->written =~ /\r\n\r\n(.*)\z/s;
return $body;
}
package main;
sub fake_client {
return Test::ContainersEndpoints::FakeTransport->new(
host => 'unix:///nonexistent.sock',
api_version => '1.41',
);
}
# ---------------------------------------------------------------------------
subtest 'the tar fixture really is a tar, so byte-exactness means something' => sub {
is length($TAR) % 512, 0, 'a whole number of 512-byte blocks';
is substr($TAR, 257, 5), 'ustar', 'ustar magic in the header block';
is unpack('Z100', $TAR), 'hostname', 'one member, named after the basename';