Skip to content

Commit 1774c55

Browse files
Mark Andreevtillahoffmann
authored andcommitted
Add stop_silent for stop containers after exit (#104)
1 parent b67b590 commit 1774c55

File tree

2 files changed

+15
-33
lines changed

2 files changed

+15
-33
lines changed

testcontainers/core/cleaner.py

Lines changed: 9 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,16 @@
1-
import atexit
2-
31
from docker.errors import NotFound
42

53
from testcontainers.core.utils import setup_logger
64

75
logger = setup_logger(__name__)
86

97

10-
class ResourceCleaner:
11-
__INSTANCE = None
12-
13-
def __init__(self):
14-
self.containers = []
15-
16-
def attach(self, container):
17-
self.containers.append(container)
18-
19-
return container
20-
21-
def clean(self):
22-
for c in self.containers:
23-
try:
24-
c.stop()
25-
except NotFound:
26-
pass
27-
except Exception as e:
28-
logger.exception(e)
29-
30-
@classmethod
31-
def instance(cls):
32-
if cls.__INSTANCE is None:
33-
cls.__INSTANCE = ResourceCleaner()
34-
atexit.register(cls.__INSTANCE.clean)
35-
36-
return cls.__INSTANCE
8+
def stop_silent(container):
9+
def wrapper():
10+
try:
11+
container.stop()
12+
except NotFound:
13+
pass
14+
except Exception as e:
15+
logger.exception(e)
16+
return wrapper

testcontainers/core/docker_client.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@
1010
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
1111
# License for the specific language governing permissions and limitations
1212
# under the License.
13+
import atexit
1314
import os
1415
import urllib
1516
import docker
1617
from docker.models.containers import Container
1718

18-
from testcontainers.core.cleaner import ResourceCleaner
19+
from testcontainers.core.cleaner import stop_silent
1920
from testcontainers.core.utils import inside_container
2021
from testcontainers.core.utils import default_gateway_ip
2122

@@ -32,8 +33,7 @@ def run(self, image: str,
3233
stdout: bool = True,
3334
stderr: bool = False,
3435
remove: bool = False, **kwargs) -> Container:
35-
return ResourceCleaner.instance().attach(
36-
self.client.containers.run(image,
36+
container = self.client.containers.run(image,
3737
command=command,
3838
stdout=stdout,
3939
stderr=stderr,
@@ -42,7 +42,9 @@ def run(self, image: str,
4242
environment=environment,
4343
ports=ports,
4444
**kwargs)
45-
)
45+
atexit.register(stop_silent(container))
46+
47+
return container
4648

4749
def port(self, container_id, port):
4850
port_mappings = self.client.api.port(container_id, port)

0 commit comments

Comments
 (0)