Skip to content

Commit

Permalink
Fix for multiple container start invocations with custom labels
Browse files Browse the repository at this point in the history
When invoking .start() multiple times on the same DockerContainer instance,
the call fails with "ValueError: The org.testcontainers namespace is reserved for internal use" error.

Example code:

```
from testcontainers.core.container import DockerContainer
container = DockerContainer("alpine:latest").with_kwargs(labels={})
container.start()
container.stop()
container.start()
```

The fix is to update labels for the container in a copy of the user-provided dictionary,
so that:
* the code doesn't mutate user structures
* avoid side effects, allowing for multiple .start() invocations
  • Loading branch information
neykov committed Feb 11, 2025
1 parent 9317736 commit 31f3f68
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions core/testcontainers/core/labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@ def create_labels(image: str, labels: Optional[dict[str, str]]) -> dict[str, str
if k.startswith(TESTCONTAINERS_NAMESPACE):
raise ValueError("The org.testcontainers namespace is reserved for internal use")

labels[LABEL_LANG] = "python"
labels[LABEL_TESTCONTAINERS] = "true"
labels[LABEL_VERSION] = importlib.metadata.version("testcontainers")
tc_labels = {
**labels,
LABEL_LANG: "python",
LABEL_TESTCONTAINERS: "true",
LABEL_VERSION: importlib.metadata.version("testcontainers"),
}

if image == c.ryuk_image:
return labels
return tc_labels

labels[LABEL_SESSION_ID] = SESSION_ID
return labels
tc_labels[LABEL_SESSION_ID] = SESSION_ID
return tc_labels

0 comments on commit 31f3f68

Please # to comment.