10
10
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11
11
# License for the specific language governing permissions and limitations
12
12
# under the License.
13
+ import atexit
13
14
import os
14
15
import urllib
15
16
import docker
17
+ from docker .errors import NotFound
16
18
from docker .models .containers import Container
19
+
17
20
from testcontainers .core .utils import inside_container
18
21
from testcontainers .core .utils import default_gateway_ip
22
+ from testcontainers .core .utils import setup_logger
23
+
24
+
25
+ LOGGER = setup_logger (__name__ )
26
+
27
+
28
+ def _stop_container (container ):
29
+ try :
30
+ container .stop ()
31
+ except NotFound :
32
+ pass
33
+ except Exception as ex :
34
+ LOGGER .warning ("failed to shut down container %s with image %s: %s" , container .id ,
35
+ container .image , ex )
19
36
20
37
21
38
class DockerClient (object ):
@@ -30,15 +47,18 @@ def run(self, image: str,
30
47
stdout : bool = True ,
31
48
stderr : bool = False ,
32
49
remove : bool = False , ** kwargs ) -> Container :
33
- return self .client .containers .run (image ,
34
- command = command ,
35
- stdout = stdout ,
36
- stderr = stderr ,
37
- remove = remove ,
38
- detach = detach ,
39
- environment = environment ,
40
- ports = ports ,
41
- ** kwargs )
50
+ container = self .client .containers .run (image ,
51
+ command = command ,
52
+ stdout = stdout ,
53
+ stderr = stderr ,
54
+ remove = remove ,
55
+ detach = detach ,
56
+ environment = environment ,
57
+ ports = ports ,
58
+ ** kwargs )
59
+ atexit .register (_stop_container , container )
60
+
61
+ return container
42
62
43
63
def port (self , container_id , port ):
44
64
port_mappings = self .client .api .port (container_id , port )
0 commit comments