Skip to content

Commit

Permalink
feat: add ContainerInfo--object as return object to inspect_container
Browse files Browse the repository at this point in the history
  • Loading branch information
Khushiyant committed Sep 16, 2024
1 parent a365202 commit 4b5831d
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
39 changes: 36 additions & 3 deletions docker/api/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,37 @@
)


class ContainerInfo:
def __init__(self, info: dict):
self._info = info

def __repr__(self):
return (
f"<ContainerInfo id={self._info.get('Id')}, name={self._info.get('Name')}>"
)

def __getattr__(self, item):
"""
Dynamically fetch any attribute from the underlying dictionary.
This allows direct access to all fields without manually defining them.
"""
try:
return self._info[item]
except KeyError as err:
raise AttributeError(
f"'ContainerInfo' object has no attribute '{item}'"
) from err

def __getitem__(self, item):
"""
Optional: If you'd like to access attributes using bracket notation.
"""
return self._info.get(item)

def get_info(self):
"""Returns the entire dictionary for reference if needed"""
return self._info

class ContainerApiMixin:
@utils.check_resource('container')
def attach(self, container, stdout=True, stderr=True,
Expand Down Expand Up @@ -783,16 +814,18 @@ def inspect_container(self, container):
container (str): The container to inspect
Returns:
(dict): Similar to the output of `docker inspect`, but as a
single dict
(ContainerInfo): Similar to the output of `docker inspect`, but as a
docker.api.container.ContainerInfo object
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self._result(
container_info = self._result(
self._get(self._url("/containers/{0}/json", container)), True
)
return ContainerInfo(container_info)


@utils.check_resource('container')
def kill(self, container, signal=None):
Expand Down
16 changes: 16 additions & 0 deletions tests/integration/api_container_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1572,3 +1572,19 @@ def test_remove_link(self):
x['Id'].startswith(container2_id)
]
assert len(retrieved) == 2

class CoontainerInfoObejectTest(BaseAPIIntegrationTest):
def test_container_info_object(self):
container = self.client.create_container(
TEST_IMG, 'true', host_config=self.client.create_host_config())
self.tmp_containers.append(container)
self.client.start(container)

inspect_data = self.client.inspect_container(container)
assert isinstance(inspect_data, docker.api.container.ContainerInfo)
assert inspect_data['Config']['Image'] == TEST_IMG
assert inspect_data['HostConfig']['NetworkMode'] == 'bridge'

# attribute style access
assert inspect_data.Id == container['Id']
assert inspect_data["Id"] == container["Id"]

0 comments on commit 4b5831d

Please sign in to comment.