docker-py/tests
Felipe Ruhland d4310b2db0 Fix `KeyError` when creating a new secret
How to reproduce the issue:

```py
>>> import docker
>>> cli = docker.from_env()
>>> cli.secrets.create(name="any_name", data="1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/docker-py/docker/models/secrets.py", line 10, in __repr__
    return "<%s: '%s'>" % (self.__class__.__name__, self.name)
  File "/home/docker-py/docker/models/secrets.py", line 14, in name
    return self.attrs['Spec']['Name']
KeyError: 'Spec'
```

The exception raises because create secrets API `/secrets/create` only
return the `id` attribute:
https://docs.docker.com/engine/api/v1.41/#operation/SecretCreate
The secret model is created using just the `id` attribute and fails
when looking for Spec.Name attribute.

```py
def __repr__(self):
    return "<%s: '%s'>" % (self.__class__.__name__, self.name)
```

```py
@property
def name(self):
    return self.attrs['Spec']['Name']
```

I came up with a ugly solution but will prevent the problem to happen
again:

```py
def create(self, **kwargs):
    obj = self.client.api.create_secret(**kwargs)
+   obj.setdefault("Spec", {})["Name"] = kwargs.get("name")
    return self.prepare_model(obj)
```

After the API call, I added the name attribute to the right place to be
used on the property name.

```py
>>> import docker
>>> cli = docker.from_env()
>>> cli.secrets.create(name="any_name", data="1")
<Secret: 'any_name'>
```

It isn't the most elegant solution, but it will do the trick.
I had a previous PR #2517 when I propose using the `id` attribute
instead of `name` on the `__repr__` method, but I think this one will be better.

That fixes #2025

Signed-off-by: Felipe Ruhland <felipe.ruhland@gmail.com>
2021-03-24 18:03:54 +01:00
..
gpg-keys Make dockerpycreds part of the SDK under docker.credentials 2019-04-30 23:37:55 -07:00
integration Unit and integration tests added 2021-02-09 21:37:26 +01:00
ssh Shell out to SSH client for an ssh connection 2020-10-13 10:42:38 +02:00
ssh-keys Shell out to SSH client for an ssh connection 2020-10-13 10:42:38 +02:00
unit Fix `KeyError` when creating a new secret 2021-03-24 18:03:54 +01:00
Dockerfile Shell out to SSH client for an ssh connection 2020-10-13 10:42:38 +02:00
Dockerfile-dind-certs Update to python 3.7 (buster) and use build-args 2019-07-15 13:27:07 +02:00
Dockerfile-ssh-dind Fix ssh connection - don't override the host and port of the http pool 2020-11-18 14:44:24 +01:00
__init__.py Create tests module for setuptools test support 2013-07-13 01:07:04 -05:00
helpers.py Reorder imports 2019-05-01 00:35:12 -07:00