or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-testcontainers

Python library for throwaway instances of anything that can run in a Docker container

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/testcontainers@4.12.x

To install, run

npx @tessl/cli install tessl/pypi-testcontainers@4.12.0

0

# Testcontainers

1

2

A comprehensive Python library for managing throwaway Docker instances in tests. Testcontainers enables developers to create isolated, reproducible test environments by programmatically spinning up Docker containers for databases, message queues, web services, and other infrastructure components during test execution.

3

4

## Package Information

5

6

- **Package Name**: testcontainers

7

- **Language**: Python

8

- **Installation**: `pip install testcontainers`

9

- **Python Support**: 3.9+

10

11

## Core Imports

12

13

```python

14

from testcontainers.core.container import DockerContainer

15

from testcontainers.core.network import Network

16

from testcontainers.core.waiting_utils import wait_for_logs, wait_for

17

```

18

19

For specialized containers:

20

21

```python

22

from testcontainers.postgres import PostgresContainer

23

from testcontainers.redis import RedisContainer

24

from testcontainers.mysql import MySqlContainer

25

from testcontainers.mongodb import MongoDbContainer

26

from testcontainers.kafka import KafkaContainer

27

from testcontainers.elasticsearch import ElasticSearchContainer

28

```

29

30

For compose orchestration:

31

32

```python

33

from testcontainers.compose import DockerCompose

34

```

35

36

For configuration and exceptions:

37

38

```python

39

from testcontainers.core.config import testcontainers_config

40

from testcontainers.core.exceptions import (

41

ContainerStartException,

42

ContainerConnectException,

43

NoSuchPortExposed

44

)

45

```

46

47

## Basic Usage

48

49

```python

50

from testcontainers.core.container import DockerContainer

51

from testcontainers.core.waiting_utils import wait_for_logs

52

53

# Basic container usage with context manager

54

with DockerContainer("hello-world") as container:

55

delay = wait_for_logs(container, "Hello from Docker!")

56

57

# Database container example

58

from testcontainers.postgres import PostgresContainer

59

60

with PostgresContainer("postgres:13") as postgres:

61

# Container automatically configured with database, user, password

62

connection_url = postgres.get_connection_url()

63

64

# Use with your database client

65

import psycopg2

66

conn = psycopg2.connect(connection_url)

67

cursor = conn.cursor()

68

cursor.execute("SELECT version();")

69

result = cursor.fetchone()

70

print(result)

71

72

# Compose orchestration example

73

from testcontainers.compose import DockerCompose

74

75

with DockerCompose(".", compose_file_name="docker-compose.test.yml") as compose:

76

# Get specific service container

77

web_container = compose.get_container("web")

78

db_container = compose.get_container("db")

79

80

# Get service endpoints

81

web_url = compose.get_service_host("web", 80)

82

db_host = compose.get_service_host("db", 5432)

83

```

84

85

## Architecture

86

87

Testcontainers follows a layered architecture enabling flexible container management:

88

89

- **DockerContainer**: Core container abstraction with fluent configuration API

90

- **Specialized Containers**: Pre-configured containers for specific services (databases, caches, etc.)

91

- **Compose Integration**: Full Docker Compose orchestration support

92

- **Waiting Strategies**: Robust container readiness detection

93

- **Resource Management**: Automatic cleanup via Ryuk or manual lifecycle control

94

95

This design provides both simplicity for common use cases and extensibility for complex testing scenarios, integrating seamlessly with pytest, unittest, and other Python testing frameworks.

96

97

## Capabilities

98

99

### Core Container Management

100

101

Fundamental Docker container lifecycle management with comprehensive configuration options, networking, volume mounting, and environment setup. Provides the foundation for all specialized containers.

102

103

```python { .api }

104

class DockerContainer:

105

def __init__(

106

self,

107

image: str,

108

docker_client_kw: Optional[dict] = None,

109

command: Optional[str] = None,

110

env: Optional[dict] = None,

111

name: Optional[str] = None,

112

ports: Optional[list] = None,

113

volumes: Optional[list] = None,

114

network: Optional[Network] = None,

115

network_aliases: Optional[list] = None,

116

**kwargs

117

): ...

118

119

def start(self) -> "DockerContainer": ...

120

def stop(self, force: bool = True, delete_volume: bool = True) -> None: ...

121

def get_exposed_port(self, port: int) -> str: ...

122

def get_container_host_ip(self) -> str: ...

123

def with_env(self, key: str, value: str) -> "DockerContainer": ...

124

def with_exposed_ports(self, *ports: int) -> "DockerContainer": ...

125

def with_bind_ports(self, container: int, host: Optional[int] = None) -> "DockerContainer": ...

126

def with_volume_mapping(self, host: str, container: str, mode: str = "ro") -> "DockerContainer": ...

127

```

128

129

[Core Container Management](./core-containers.md)

130

131

### Database Containers

132

133

Pre-configured containers for popular databases including PostgreSQL, MySQL, MongoDB, Redis, and many others. Each provides service-specific configuration options and connection utilities.

134

135

```python { .api }

136

class PostgresContainer:

137

def __init__(

138

self,

139

image: str = "postgres:latest",

140

port: int = 5432,

141

username: Optional[str] = None,

142

password: Optional[str] = None,

143

dbname: Optional[str] = None,

144

**kwargs

145

): ...

146

def get_connection_url(self, host: Optional[str] = None) -> str: ...

147

148

class MySqlContainer:

149

def __init__(

150

self,

151

image: str = "mysql:latest",

152

username: Optional[str] = None,

153

password: Optional[str] = None,

154

dbname: Optional[str] = None,

155

**kwargs

156

): ...

157

def get_connection_url(self) -> str: ...

158

159

class MongoDbContainer:

160

def __init__(

161

self,

162

image: str = "mongo:latest",

163

port: int = 27017,

164

username: Optional[str] = None,

165

password: Optional[str] = None,

166

**kwargs

167

): ...

168

def get_connection_url(self) -> str: ...

169

def get_connection_client(self): ...

170

```

171

172

[Database Containers](./database-containers.md)

173

174

### Cache and Messaging Containers

175

176

Containers for caching systems, message queues, and pub/sub services including Redis, Kafka, RabbitMQ, NATS, and messaging brokers with client integration.

177

178

```python { .api }

179

class RedisContainer:

180

def __init__(

181

self,

182

image: str = "redis:latest",

183

port: int = 6379,

184

password: Optional[str] = None,

185

**kwargs

186

): ...

187

def get_client(self, **kwargs): ...

188

189

class KafkaContainer:

190

def __init__(

191

self,

192

image: str = "confluentinc/cp-kafka:7.6.0",

193

port: int = 9093,

194

**kwargs

195

): ...

196

def get_bootstrap_server(self) -> str: ...

197

def with_kraft(self) -> "KafkaContainer": ...

198

```

199

200

[Cache and Messaging](./cache-messaging.md)

201

202

### Docker Compose Orchestration

203

204

Complete Docker Compose integration for managing multi-container environments, service discovery, and complex application stacks during testing.

205

206

```python { .api }

207

class DockerCompose:

208

def __init__(

209

self,

210

context: str,

211

compose_file_name: Optional[str] = None,

212

pull: bool = False,

213

build: bool = False,

214

wait: bool = True,

215

**kwargs

216

): ...

217

218

def start(self) -> "DockerCompose": ...

219

def stop(self, down: bool = True) -> None: ...

220

def get_container(self, service_name: str) -> ComposeContainer: ...

221

def get_service_host(self, service_name: str, port: int) -> str: ...

222

def get_service_port(self, service_name: str, port: int) -> int: ...

223

def exec_in_container(self, command: str, service_name: str): ...

224

```

225

226

[Docker Compose](./compose.md)

227

228

### Waiting Strategies and Utilities

229

230

Robust container readiness detection, log monitoring, and condition waiting utilities for reliable test execution across different container types and startup behaviors.

231

232

```python { .api }

233

def wait_container_is_ready(*transient_exceptions) -> Callable: ...

234

235

def wait_for_logs(

236

container: DockerContainer,

237

predicate: Union[str, Callable],

238

timeout: float = 120,

239

interval: float = 1,

240

**kwargs

241

) -> float: ...

242

243

def wait_for(condition: Callable, timeout: float = 120, interval: float = 1) -> bool: ...

244

```

245

246

[Waiting Strategies](./waiting-strategies.md)

247

248

### Search and Analytics Containers

249

250

Specialized containers for search engines, analytics platforms, and data processing including Elasticsearch, OpenSearch, ClickHouse, and vector databases.

251

252

```python { .api }

253

class ElasticSearchContainer:

254

def __init__(self, image: str = "elasticsearch", port: int = 9200, **kwargs): ...

255

def get_url(self) -> str: ...

256

257

class ClickHouseContainer:

258

def __init__(self, image: str = "clickhouse/clickhouse-server", **kwargs): ...

259

def get_connection_url(self) -> str: ...

260

```

261

262

[Search and Analytics](./search-analytics.md)

263

264

### Cloud Services Integration

265

266

Containers for cloud service emulation and integration including LocalStack for AWS services, Azure emulators, and Google Cloud Platform services for local development and testing.

267

268

```python { .api }

269

class LocalStackContainer:

270

def __init__(

271

self,

272

image: str = "localstack/localstack:2.0.1",

273

edge_port: int = 4566,

274

**kwargs

275

): ...

276

def with_services(self, *services: str) -> "LocalStackContainer": ...

277

def get_url(self) -> str: ...

278

def get_client(self, name: str, **kwargs): ...

279

```

280

281

[Cloud Services](./cloud-services.md)

282

283

### Web and Testing Containers

284

285

Containers for web services, browser automation, and testing infrastructure including Nginx, Selenium WebDriver, and specialized testing utilities.

286

287

```python { .api }

288

class BrowserWebDriverContainer:

289

def __init__(

290

self,

291

capabilities: dict,

292

image: Optional[str] = None,

293

port: int = 4444,

294

**kwargs

295

): ...

296

def get_driver(self): ...

297

def get_connection_url(self) -> str: ...

298

def with_options(self, options) -> "BrowserWebDriverContainer": ...

299

300

class NginxContainer:

301

def __init__(self, image: str = "nginx:alpine", port: int = 80, **kwargs): ...

302

def get_url(self) -> str: ...

303

```

304

305

[Web and Testing](./web-testing.md)

306

307

### Additional Service Containers

308

309

Additional specialized containers for various development and testing needs.

310

311

```python { .api }

312

class VaultContainer:

313

def __init__(self, image: str = "vault:latest", port: int = 8200, **kwargs): ...

314

def get_url(self) -> str: ...

315

316

class MailpitContainer:

317

def __init__(self, image: str = "axllent/mailpit:latest", **kwargs): ...

318

def get_smtp_host(self) -> str: ...

319

def get_web_url(self) -> str: ...

320

321

class OllamaContainer:

322

def __init__(self, image: str = "ollama/ollama:latest", **kwargs): ...

323

def get_endpoint_url(self) -> str: ...

324

325

class SftpContainer:

326

def __init__(self, image: str = "atmoz/sftp:latest", **kwargs): ...

327

def get_connection_url(self) -> str: ...

328

```

329

330

## Configuration and Error Handling

331

332

### Global Configuration

333

334

```python { .api }

335

from testcontainers.core.config import testcontainers_config

336

337

# Configuration properties

338

testcontainers_config.max_tries: int

339

testcontainers_config.sleep_time: int

340

testcontainers_config.timeout: int

341

testcontainers_config.ryuk_disabled: bool

342

```

343

344

### Exception Types

345

346

```python { .api }

347

class ContainerStartException(RuntimeError): ...

348

class ContainerConnectException(RuntimeError): ...

349

class ContainerIsNotRunning(RuntimeError): ...

350

class NoSuchPortExposed(RuntimeError): ...

351

```

352

353

## Available Container Modules

354

355

The library includes 45+ specialized container modules providing pre-configured containers for popular services:

356

357

**Databases**: postgres, mysql, mongodb, redis, cassandra, clickhouse, cockroachdb, cosmosdb, db2, influxdb, mssql, neo4j, oracle-free, scylla, trino

358

359

**Vector Databases**: chroma, milvus, qdrant, weaviate

360

361

**Message Brokers**: kafka, mqtt, nats, rabbitmq

362

363

**Search & Analytics**: elasticsearch, opensearch

364

365

**Storage & Cache**: azurite, memcached, minio, registry, vault

366

367

**Development Tools**: generic, keycloak, k3s, mailpit, nginx, ollama, selenium, sftp

368

369

**Cloud Services**: aws, google, localstack, openfga

370

371

Each specialized container follows similar patterns with service-specific configuration methods and client getters appropriate for the service type.

372

373

## Exception Types

374

375

```python { .api }

376

from testcontainers.core.exceptions import (

377

ContainerStartException,

378

ContainerConnectException,

379

ContainerIsNotRunning,

380

NoSuchPortExposed

381

)

382

383

class ContainerStartException(RuntimeError):

384

"""Raised when container fails to start properly."""

385

386

class ContainerConnectException(RuntimeError):

387

"""Raised when connection to container fails."""

388

389

class ContainerIsNotRunning(RuntimeError):

390

"""Raised when operation requires running container but container is not running."""

391

392

class NoSuchPortExposed(RuntimeError):

393

"""Raised when trying to access a port that was not exposed."""

394

```