testcontainers 9.0.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -832,6 +832,85 @@ const container = await new GenericContainer("redis")
832
832
  .start();
833
833
  ```
834
834
 
835
+ ### HTTP
836
+
837
+ Default behaviour of waiting for a 200 response:
838
+
839
+ ```javascript
840
+ const { GenericContainer, Wait } = require("testcontainers");
841
+
842
+ const container = await new GenericContainer("redis")
843
+ .withExposedPorts(6379)
844
+ .withWaitStrategy(Wait.forHttp("/health", 8080))
845
+ .start();
846
+ ```
847
+
848
+ Specify status code:
849
+
850
+ ```javascript
851
+ .withWaitStrategy(Wait.forHttp("/health", 8080)
852
+ .forStatusCode(201))
853
+
854
+ .withWaitStrategy(Wait.forHttp("/health", 8080)
855
+ .forStatusCodeMatching(statusCode => statusCode === 201))
856
+ ```
857
+
858
+ Specify response body:
859
+
860
+ ```javascript
861
+ .withWaitStrategy(Wait.forHttp("/health", 8080)
862
+ .forResponsePredicate(response => response === "OK"))
863
+ ```
864
+
865
+ Customise the request:
866
+
867
+ ```javascript
868
+ .withWaitStrategy(Wait.forHttp("/health", 8080)
869
+ .withMethod("POST")
870
+ .withHeaders({ X_CUSTOM_VALUE: "custom" })
871
+ .withBasicCredentials("username", "password")
872
+ .withReadTimeout(10000))
873
+ ```
874
+
875
+ Use TLS:
876
+
877
+ ```javascript
878
+ .withWaitStrategy(Wait.forHttp("/health", 8443)
879
+ .useTls())
880
+ ```
881
+
882
+ Allow insecure TLS:
883
+
884
+ ```javascript
885
+ .withWaitStrategy(Wait.forHttp("/health", 8443)
886
+ .useTls()
887
+ .insecureTls())
888
+ ```
889
+
890
+ ### Other Startup Strategies
891
+
892
+ If none of these options meet your requirements, you can create your own subclass of `StartupCheckStrategy`:
893
+
894
+ ```javascript
895
+ const Dockerode = require("dockerode");
896
+ const {
897
+ GenericContainer,
898
+ StartupCheckStrategy,
899
+ StartupStatus
900
+ } = require("testcontainers");
901
+
902
+ class ReadyAfterDelayWaitStrategy extends StartupCheckStrategy {
903
+ public checkStartupState(dockerClient: Dockerode, containerId: string): Promise<StartupStatus> {
904
+ return new Promise((resolve) => setTimeout(() => resolve("SUCCESS"), 3000));
905
+ }
906
+ }
907
+
908
+ const container = await new GenericContainer("redis")
909
+ .withExposedPorts(6379)
910
+ .withWaitStrategy(new ReadyAfterDelayWaitStrategy())
911
+ .start();
912
+ ```
913
+
835
914
  ## Authentication
836
915
 
837
916
  Testcontainers will automatically pick up and use credentials from `$HOME/.docker/config.json`, using
@@ -22,6 +22,4 @@ export declare class DockerComposeEnvironment {
22
22
  withWaitStrategy(containerName: string, waitStrategy: WaitStrategy): this;
23
23
  withStartupTimeout(startupTimeout: number): this;
24
24
  up(services?: Array<string>): Promise<StartedDockerComposeEnvironment>;
25
- private waitForContainer;
26
- private getWaitStrategy;
27
25
  }
@@ -14,7 +14,6 @@ const bound_ports_1 = require("../bound-ports");
14
14
  const container_name_resolver_1 = require("../docker-compose/functions/container-name-resolver");
15
15
  const started_generic_container_1 = require("../generic-container/started-generic-container");
16
16
  const logger_1 = require("../logger");
17
- const port_check_1 = require("../port-check");
18
17
  const wait_strategy_1 = require("../wait-strategy");
19
18
  const reaper_1 = require("../reaper");
20
19
  const uuid_1 = require("../uuid");
@@ -26,6 +25,7 @@ const container_logs_1 = require("../docker/functions/container/container-logs")
26
25
  const started_docker_compose_environment_1 = require("./started-docker-compose-environment");
27
26
  const docker_compose_down_1 = require("../docker-compose/functions/docker-compose-down");
28
27
  const docker_compose_up_1 = require("../docker-compose/functions/docker-compose-up");
28
+ const wait_for_container_1 = require("../wait-for-container");
29
29
  class DockerComposeEnvironment {
30
30
  constructor(composeFilePath, composeFiles, uuid = new uuid_1.RandomUuid()) {
31
31
  this.build = false;
@@ -104,9 +104,11 @@ class DockerComposeEnvironment {
104
104
  .on("err", (data) => logger_1.containerLog.error(`${containerName}: ${data}`));
105
105
  const inspectResult = yield (0, inspect_container_1.inspectContainer)(container);
106
106
  const boundPorts = bound_ports_1.BoundPorts.fromInspectResult(inspectResult);
107
+ const host = (yield (0, docker_client_1.dockerClient)()).host;
108
+ const waitStrategy = (this.waitStrategy[containerName] ? this.waitStrategy[containerName] : (0, wait_strategy_1.defaultWaitStrategy)(host, container)).withStartupTimeout(this.startupTimeout);
107
109
  try {
108
110
  logger_1.log.info(`Waiting for container ${containerName} to be ready`);
109
- yield this.waitForContainer(container, containerName, boundPorts);
111
+ yield (0, wait_for_container_1.waitForContainer)(container, waitStrategy, host, boundPorts);
110
112
  logger_1.log.info(`Container ${containerName} is ready`);
111
113
  }
112
114
  catch (err) {
@@ -119,7 +121,7 @@ class DockerComposeEnvironment {
119
121
  }
120
122
  throw err;
121
123
  }
122
- return new started_generic_container_1.StartedGenericContainer(container, (yield (0, docker_client_1.dockerClient)()).host, inspectResult, boundPorts, containerName, this.getWaitStrategy((yield (0, docker_client_1.dockerClient)()).host, container, containerName).withStartupTimeout(this.startupTimeout));
124
+ return new started_generic_container_1.StartedGenericContainer(container, host, inspectResult, boundPorts, containerName, waitStrategy);
123
125
  })))).reduce((map, startedGenericContainer) => {
124
126
  const containerName = startedGenericContainer.getName();
125
127
  return Object.assign(Object.assign({}, map), { [containerName]: startedGenericContainer });
@@ -128,21 +130,5 @@ class DockerComposeEnvironment {
128
130
  return new started_docker_compose_environment_1.StartedDockerComposeEnvironment(startedGenericContainers, Object.assign(Object.assign({}, options), { composeOptions, environment: this.environment }));
129
131
  });
130
132
  }
131
- waitForContainer(container, containerName, boundPorts) {
132
- return __awaiter(this, void 0, void 0, function* () {
133
- const waitStrategy = this.getWaitStrategy((yield (0, docker_client_1.dockerClient)()).host, container, containerName);
134
- yield waitStrategy.withStartupTimeout(this.startupTimeout).waitUntilReady(container, boundPorts);
135
- });
136
- }
137
- getWaitStrategy(host, container, containerName) {
138
- if (this.waitStrategy[containerName]) {
139
- return this.waitStrategy[containerName];
140
- }
141
- else {
142
- const hostPortCheck = new port_check_1.HostPortCheck(host);
143
- const internalPortCheck = new port_check_1.InternalPortCheck(container);
144
- return new wait_strategy_1.HostPortWaitStrategy(hostPortCheck, internalPortCheck);
145
- }
146
- }
147
133
  }
148
134
  exports.DockerComposeEnvironment = DockerComposeEnvironment;
@@ -70,6 +70,4 @@ export declare class GenericContainer implements TestContainer {
70
70
  withCopyFilesToContainer(filesToCopy: FileToCopy[]): this;
71
71
  withCopyContentToContainer(contentsToCopy: ContentToCopy[]): this;
72
72
  protected getTarToCopy(): archiver.Archiver;
73
- private waitForContainer;
74
- private getWaitStrategy;
75
73
  }
@@ -16,7 +16,6 @@ exports.GenericContainer = void 0;
16
16
  const archiver_1 = __importDefault(require("archiver"));
17
17
  const bound_ports_1 = require("../bound-ports");
18
18
  const logger_1 = require("../logger");
19
- const port_check_1 = require("../port-check");
20
19
  const pull_policy_1 = require("../pull-policy");
21
20
  const reaper_1 = require("../reaper");
22
21
  const docker_image_name_1 = require("../docker-image-name");
@@ -30,14 +29,13 @@ const docker_client_1 = require("../docker/docker-client");
30
29
  const inspect_container_1 = require("../docker/functions/container/inspect-container");
31
30
  const start_container_1 = require("../docker/functions/container/start-container");
32
31
  const container_logs_1 = require("../docker/functions/container/container-logs");
33
- const stop_container_1 = require("../docker/functions/container/stop-container");
34
- const remove_container_1 = require("../docker/functions/container/remove-container");
35
32
  const put_container_archive_1 = require("../docker/functions/container/put-container-archive");
36
33
  const generic_container_builder_1 = require("./generic-container-builder");
37
34
  const started_generic_container_1 = require("./started-generic-container");
38
35
  const hash_1 = require("../hash");
39
36
  const get_container_1 = require("../docker/functions/container/get-container");
40
37
  const labels_1 = require("../labels");
38
+ const wait_for_container_1 = require("../wait-for-container");
41
39
  class GenericContainer {
42
40
  constructor(image) {
43
41
  this.image = image;
@@ -119,14 +117,18 @@ class GenericContainer {
119
117
  });
120
118
  }
121
119
  reuseContainer(startedContainer) {
120
+ var _a;
122
121
  return __awaiter(this, void 0, void 0, function* () {
123
122
  const inspectResult = yield (0, inspect_container_1.inspectContainer)(startedContainer);
124
123
  const boundPorts = bound_ports_1.BoundPorts.fromInspectResult(inspectResult).filter(this.ports);
125
- yield this.waitForContainer(startedContainer, boundPorts);
126
- return new started_generic_container_1.StartedGenericContainer(startedContainer, (yield (0, docker_client_1.dockerClient)()).host, inspectResult, boundPorts, inspectResult.name, this.getWaitStrategy((yield (0, docker_client_1.dockerClient)()).host, startedContainer).withStartupTimeout(this.startupTimeout));
124
+ const host = (yield (0, docker_client_1.dockerClient)()).host;
125
+ const waitStrategy = ((_a = this.waitStrategy) !== null && _a !== void 0 ? _a : (0, wait_strategy_1.defaultWaitStrategy)(host, startedContainer)).withStartupTimeout(this.startupTimeout);
126
+ yield (0, wait_for_container_1.waitForContainer)(startedContainer, waitStrategy, host, boundPorts);
127
+ return new started_generic_container_1.StartedGenericContainer(startedContainer, host, inspectResult, boundPorts, inspectResult.name, waitStrategy);
127
128
  });
128
129
  }
129
130
  startContainer(createContainerOptions) {
131
+ var _a;
130
132
  return __awaiter(this, void 0, void 0, function* () {
131
133
  const container = yield (0, create_container_1.createContainer)(createContainerOptions);
132
134
  if (!this.imageName.isHelperContainer() && port_forwarder_1.PortForwarderInstance.isRunning()) {
@@ -159,8 +161,10 @@ class GenericContainer {
159
161
  .on("err", (data) => logger_1.containerLog.error(`${container.id}: ${data.trim()}`));
160
162
  const inspectResult = yield (0, inspect_container_1.inspectContainer)(container);
161
163
  const boundPorts = bound_ports_1.BoundPorts.fromInspectResult(inspectResult).filter(this.ports);
162
- yield this.waitForContainer(container, boundPorts);
163
- const startedContainer = new started_generic_container_1.StartedGenericContainer(container, (yield (0, docker_client_1.dockerClient)()).host, inspectResult, boundPorts, inspectResult.name, this.getWaitStrategy((yield (0, docker_client_1.dockerClient)()).host, container).withStartupTimeout(this.startupTimeout));
164
+ const host = (yield (0, docker_client_1.dockerClient)()).host;
165
+ const waitStrategy = ((_a = this.waitStrategy) !== null && _a !== void 0 ? _a : (0, wait_strategy_1.defaultWaitStrategy)(host, container)).withStartupTimeout(this.startupTimeout);
166
+ yield (0, wait_for_container_1.waitForContainer)(container, waitStrategy, host, boundPorts);
167
+ const startedContainer = new started_generic_container_1.StartedGenericContainer(container, host, inspectResult, boundPorts, inspectResult.name, waitStrategy);
164
168
  if (this.postStart) {
165
169
  yield this.postStart(startedContainer, inspectResult, boundPorts);
166
170
  }
@@ -284,34 +288,5 @@ class GenericContainer {
284
288
  }
285
289
  return this.tarToCopy;
286
290
  }
287
- waitForContainer(container, boundPorts) {
288
- return __awaiter(this, void 0, void 0, function* () {
289
- logger_1.log.debug(`Waiting for container to be ready: ${container.id}`);
290
- const waitStrategy = this.getWaitStrategy((yield (0, docker_client_1.dockerClient)()).host, container);
291
- try {
292
- yield waitStrategy.withStartupTimeout(this.startupTimeout).waitUntilReady(container, boundPorts);
293
- logger_1.log.info("Container is ready");
294
- }
295
- catch (err) {
296
- logger_1.log.error(`Container failed to be ready: ${err}`);
297
- try {
298
- yield (0, stop_container_1.stopContainer)(container, { timeout: 0 });
299
- yield (0, remove_container_1.removeContainer)(container, { removeVolumes: true });
300
- }
301
- catch (stopErr) {
302
- logger_1.log.error(`Failed to stop container after it failed to be ready: ${stopErr}`);
303
- }
304
- throw err;
305
- }
306
- });
307
- }
308
- getWaitStrategy(host, container) {
309
- if (this.waitStrategy) {
310
- return this.waitStrategy;
311
- }
312
- const hostPortCheck = new port_check_1.HostPortCheck(host);
313
- const internalPortCheck = new port_check_1.InternalPortCheck(container);
314
- return new wait_strategy_1.HostPortWaitStrategy(hostPortCheck, internalPortCheck);
315
- }
316
291
  }
317
292
  exports.GenericContainer = GenericContainer;
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { RestartOptions, StartedTestContainer, StopOptions, ExecOptions, StoppedTestContainer } from "../test-container";
2
+ import { ExecOptions, RestartOptions, StartedTestContainer, StopOptions, StoppedTestContainer } from "../test-container";
3
3
  import Dockerode from "dockerode";
4
4
  import { ExecResult, Labels } from "../docker/types";
5
5
  import { InspectResult } from "../docker/functions/container/inspect-container";
@@ -17,7 +17,6 @@ export declare class StartedGenericContainer implements StartedTestContainer {
17
17
  stop(options?: Partial<StopOptions>): Promise<StoppedTestContainer>;
18
18
  restart(options?: Partial<RestartOptions>): Promise<void>;
19
19
  private stopContainer;
20
- private waitForContainer;
21
20
  getHost(): string;
22
21
  getMappedPort(port: number): number;
23
22
  getId(): string;
@@ -19,6 +19,7 @@ const container_logs_1 = require("../docker/functions/container/container-logs")
19
19
  const stopped_generic_container_1 = require("./stopped-generic-container");
20
20
  const stop_container_1 = require("../docker/functions/container/stop-container");
21
21
  const restart_container_1 = require("../docker/functions/container/restart-container");
22
+ const wait_for_container_1 = require("../wait-for-container");
22
23
  class StartedGenericContainer {
23
24
  constructor(container, host, inspectResult, boundPorts, name, waitStrategy) {
24
25
  this.container = container;
@@ -39,7 +40,7 @@ class StartedGenericContainer {
39
40
  yield (0, restart_container_1.restartContainer)(this.container, resolvedOptions);
40
41
  this.inspectResult = yield (0, inspect_container_1.inspectContainer)(this.container);
41
42
  this.boundPorts = bound_ports_1.BoundPorts.fromInspectResult(this.inspectResult).filter(Array.from(this.boundPorts.iterator()).map((port) => port[0]));
42
- yield this.waitForContainer(this.container, this.boundPorts);
43
+ yield (0, wait_for_container_1.waitForContainer)(this.container, this.waitStrategy, this.host, this.boundPorts);
43
44
  });
44
45
  }
45
46
  stopContainer(options = {}) {
@@ -51,26 +52,6 @@ class StartedGenericContainer {
51
52
  return new stopped_generic_container_1.StoppedGenericContainer();
52
53
  });
53
54
  }
54
- waitForContainer(container, boundPorts) {
55
- return __awaiter(this, void 0, void 0, function* () {
56
- logger_1.log.debug(`Waiting for container to be ready: ${container.id}`);
57
- try {
58
- yield this.waitStrategy.waitUntilReady(container, boundPorts);
59
- logger_1.log.info("Container is ready");
60
- }
61
- catch (err) {
62
- logger_1.log.error(`Container failed to be ready: ${err}`);
63
- try {
64
- yield (0, stop_container_1.stopContainer)(container, { timeout: 0 });
65
- yield (0, remove_container_1.removeContainer)(container, { removeVolumes: true });
66
- }
67
- catch (stopErr) {
68
- logger_1.log.error(`Failed to stop container after it failed to be ready: ${stopErr}`);
69
- }
70
- throw err;
71
- }
72
- });
73
- }
74
55
  getHost() {
75
56
  return this.host;
76
57
  }
@@ -0,0 +1,27 @@
1
+ import Dockerode from "dockerode";
2
+ import { BoundPorts } from "./bound-ports";
3
+ import { AbstractWaitStrategy } from "./wait-strategy";
4
+ export declare class HttpWaitStrategy extends AbstractWaitStrategy {
5
+ private readonly path;
6
+ private readonly port;
7
+ private protocol;
8
+ private method;
9
+ private headers;
10
+ private predicates;
11
+ private _allowInsecure;
12
+ private readTimeout;
13
+ constructor(path: string, port: number);
14
+ forStatusCode(statusCode: number): HttpWaitStrategy;
15
+ forStatusCodeMatching(predicate: (statusCode: number) => boolean): HttpWaitStrategy;
16
+ forResponsePredicate(predicate: (response: string) => boolean): HttpWaitStrategy;
17
+ withMethod(method: string): HttpWaitStrategy;
18
+ withHeaders(headers: {
19
+ [key: string]: string;
20
+ }): HttpWaitStrategy;
21
+ withBasicCredentials(username: string, password: string): HttpWaitStrategy;
22
+ withReadTimeout(readTimeout: number): HttpWaitStrategy;
23
+ usingTls(): HttpWaitStrategy;
24
+ allowInsecure(): HttpWaitStrategy;
25
+ waitUntilReady(container: Dockerode.Container, host: string, boundPorts: BoundPorts): Promise<void>;
26
+ private getAgent;
27
+ }
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.HttpWaitStrategy = void 0;
16
+ const wait_strategy_1 = require("./wait-strategy");
17
+ const retry_strategy_1 = require("./retry-strategy");
18
+ const node_fetch_1 = __importDefault(require("node-fetch"));
19
+ const https_1 = __importDefault(require("https"));
20
+ class HttpWaitStrategy extends wait_strategy_1.AbstractWaitStrategy {
21
+ constructor(path, port) {
22
+ super();
23
+ this.protocol = "http";
24
+ this.method = "GET";
25
+ this.headers = {};
26
+ this.predicates = [];
27
+ this._allowInsecure = false;
28
+ this.readTimeout = 1000;
29
+ this.path = path;
30
+ this.port = port;
31
+ }
32
+ forStatusCode(statusCode) {
33
+ this.predicates.push((response) => __awaiter(this, void 0, void 0, function* () { return response.status === statusCode; }));
34
+ return this;
35
+ }
36
+ forStatusCodeMatching(predicate) {
37
+ this.predicates.push((response) => __awaiter(this, void 0, void 0, function* () { return predicate(response.status); }));
38
+ return this;
39
+ }
40
+ forResponsePredicate(predicate) {
41
+ this.predicates.push((response) => __awaiter(this, void 0, void 0, function* () { return predicate(yield response.text()); }));
42
+ return this;
43
+ }
44
+ withMethod(method) {
45
+ this.method = method;
46
+ return this;
47
+ }
48
+ withHeaders(headers) {
49
+ this.headers = Object.assign(Object.assign({}, this.headers), headers);
50
+ return this;
51
+ }
52
+ withBasicCredentials(username, password) {
53
+ const base64Encoded = Buffer.from(`${username}:${password}`).toString("base64");
54
+ this.headers = Object.assign(Object.assign({}, this.headers), { Authorization: `Bearer ${base64Encoded}` });
55
+ return this;
56
+ }
57
+ withReadTimeout(readTimeout) {
58
+ this.readTimeout = readTimeout;
59
+ return this;
60
+ }
61
+ usingTls() {
62
+ this.protocol = "https";
63
+ return this;
64
+ }
65
+ allowInsecure() {
66
+ this._allowInsecure = true;
67
+ return this;
68
+ }
69
+ waitUntilReady(container, host, boundPorts) {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ yield new retry_strategy_1.IntervalRetryStrategy(this.readTimeout).retryUntil(() => __awaiter(this, void 0, void 0, function* () {
72
+ try {
73
+ const url = `${this.protocol}://${host}:${boundPorts.getBinding(this.port)}${this.path}`;
74
+ return yield (0, node_fetch_1.default)(url, {
75
+ method: this.method,
76
+ timeout: this.readTimeout,
77
+ headers: this.headers,
78
+ agent: this.getAgent(),
79
+ });
80
+ }
81
+ catch (_a) {
82
+ return undefined;
83
+ }
84
+ }), (response) => {
85
+ if (response === undefined) {
86
+ return false;
87
+ }
88
+ else if (!this.predicates.length) {
89
+ return response.ok;
90
+ }
91
+ else {
92
+ return this.predicates.every((predicate) => predicate(response));
93
+ }
94
+ }, () => {
95
+ throw new Error(`URL ${this.path} not accessible after ${this.startupTimeout}ms for ${container.id}`);
96
+ }, this.startupTimeout);
97
+ });
98
+ }
99
+ getAgent() {
100
+ if (this._allowInsecure) {
101
+ return new https_1.default.Agent({
102
+ rejectUnauthorized: false,
103
+ });
104
+ }
105
+ }
106
+ }
107
+ exports.HttpWaitStrategy = HttpWaitStrategy;
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export { StoppedDockerComposeEnvironment } from "./docker-compose-environment/st
8
8
  export { DownedDockerComposeEnvironment } from "./docker-compose-environment/downed-docker-compose-environment";
9
9
  export { Network, StartedNetwork, StoppedNetwork } from "./network";
10
10
  export { Wait } from "./wait";
11
+ export { StartupCheckStrategy, StartupStatus } from "./startup-check-strategy";
11
12
  export { PullPolicy, DefaultPullPolicy, AlwaysPullPolicy } from "./pull-policy";
12
13
  export { PostgreSqlContainer, StartedPostgreSqlContainer } from "./modules/postgresql/postgresql-container";
13
14
  export { KafkaContainer, StartedKafkaContainer } from "./modules/kafka/kafka-container";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StartedMongoDBContainer = exports.MongoDBContainer = exports.StartedNatsContainer = exports.NatsContainer = exports.StartedMySqlContainer = exports.MySqlContainer = exports.StartedElasticsearchContainer = exports.ElasticsearchContainer = exports.StartedArangoContainer = exports.ArangoDBContainer = exports.StartedNeo4jContainer = exports.Neo4jContainer = exports.StartedKafkaContainer = exports.KafkaContainer = exports.StartedPostgreSqlContainer = exports.PostgreSqlContainer = exports.AlwaysPullPolicy = exports.DefaultPullPolicy = exports.Wait = exports.StoppedNetwork = exports.StartedNetwork = exports.Network = exports.DownedDockerComposeEnvironment = exports.StoppedDockerComposeEnvironment = exports.StartedDockerComposeEnvironment = exports.DockerComposeEnvironment = exports.TestContainers = exports.GenericContainerBuilder = exports.GenericContainer = void 0;
3
+ exports.StartedMongoDBContainer = exports.MongoDBContainer = exports.StartedNatsContainer = exports.NatsContainer = exports.StartedMySqlContainer = exports.MySqlContainer = exports.StartedElasticsearchContainer = exports.ElasticsearchContainer = exports.StartedArangoContainer = exports.ArangoDBContainer = exports.StartedNeo4jContainer = exports.Neo4jContainer = exports.StartedKafkaContainer = exports.KafkaContainer = exports.StartedPostgreSqlContainer = exports.PostgreSqlContainer = exports.AlwaysPullPolicy = exports.DefaultPullPolicy = exports.StartupCheckStrategy = exports.Wait = exports.StoppedNetwork = exports.StartedNetwork = exports.Network = exports.DownedDockerComposeEnvironment = exports.StoppedDockerComposeEnvironment = exports.StartedDockerComposeEnvironment = exports.DockerComposeEnvironment = exports.TestContainers = exports.GenericContainerBuilder = exports.GenericContainer = void 0;
4
4
  var generic_container_1 = require("./generic-container/generic-container");
5
5
  Object.defineProperty(exports, "GenericContainer", { enumerable: true, get: function () { return generic_container_1.GenericContainer; } });
6
6
  var generic_container_builder_1 = require("./generic-container/generic-container-builder");
@@ -21,6 +21,8 @@ Object.defineProperty(exports, "StartedNetwork", { enumerable: true, get: functi
21
21
  Object.defineProperty(exports, "StoppedNetwork", { enumerable: true, get: function () { return network_1.StoppedNetwork; } });
22
22
  var wait_1 = require("./wait");
23
23
  Object.defineProperty(exports, "Wait", { enumerable: true, get: function () { return wait_1.Wait; } });
24
+ var startup_check_strategy_1 = require("./startup-check-strategy");
25
+ Object.defineProperty(exports, "StartupCheckStrategy", { enumerable: true, get: function () { return startup_check_strategy_1.StartupCheckStrategy; } });
24
26
  var pull_policy_1 = require("./pull-policy");
25
27
  Object.defineProperty(exports, "DefaultPullPolicy", { enumerable: true, get: function () { return pull_policy_1.DefaultPullPolicy; } });
26
28
  Object.defineProperty(exports, "AlwaysPullPolicy", { enumerable: true, get: function () { return pull_policy_1.AlwaysPullPolicy; } });
package/dist/reaper.js CHANGED
@@ -18,6 +18,7 @@ const images_1 = require("./images");
18
18
  const port_1 = require("./port");
19
19
  const labels_1 = require("./labels");
20
20
  const wait_1 = require("./wait");
21
+ const retry_strategy_1 = require("./retry-strategy");
21
22
  class RealReaper {
22
23
  constructor(container, socket) {
23
24
  this.container = container;
@@ -97,28 +98,38 @@ class ReaperInstance {
97
98
  const containerId = startedContainer.getId();
98
99
  const host = startedContainer.getHost();
99
100
  const port = startedContainer.getMappedPort(8080);
100
- logger_1.log.debug(`Connecting to Reaper ${containerId} on ${host}:${port}`);
101
- const socket = new net_1.Socket();
102
- socket.unref();
103
- socket
104
- .on("timeout", () => logger_1.log.error(`Reaper ${containerId} socket timed out`))
105
- .on("error", (err) => logger_1.log.error(`Reaper ${containerId} socket error: ${err}`))
106
- .on("close", (hadError) => {
107
- if (hadError) {
108
- logger_1.log.error(`Connection to Reaper ${containerId} closed with error`);
109
- }
110
- else {
111
- logger_1.log.warn(`Connection to Reaper ${containerId} closed`);
112
- }
113
- });
114
- return new Promise((resolve) => {
115
- socket.connect((0, port_1.getContainerPort)(port), host, () => {
116
- logger_1.log.debug(`Connected to Reaper ${containerId}`);
117
- socket.write(`label=${labels_1.LABEL_SESSION_ID}=${session_id_1.sessionId}\r\n`);
118
- const reaper = new RealReaper(startedContainer, socket);
119
- resolve(reaper);
101
+ const retryStrategy = new retry_strategy_1.IntervalRetryStrategy(1000);
102
+ const retryResult = yield retryStrategy.retryUntil((attempt) => {
103
+ return new Promise((resolve) => {
104
+ logger_1.log.debug(`Connecting to Reaper (attempt ${attempt + 1}) ${containerId} on ${host}:${port}`);
105
+ const socket = new net_1.Socket();
106
+ socket
107
+ .unref()
108
+ .on("timeout", () => logger_1.log.error(`Reaper ${containerId} socket timed out`))
109
+ .on("error", (err) => logger_1.log.error(`Reaper ${containerId} socket error: ${err}`))
110
+ .on("close", (hadError) => {
111
+ if (hadError) {
112
+ logger_1.log.error(`Connection to Reaper ${containerId} closed with error`);
113
+ }
114
+ else {
115
+ logger_1.log.warn(`Connection to Reaper ${containerId} closed`);
116
+ }
117
+ resolve(undefined);
118
+ })
119
+ .connect((0, port_1.getContainerPort)(port), host, () => {
120
+ logger_1.log.debug(`Connected to Reaper ${containerId}`);
121
+ socket.write(`label=${labels_1.LABEL_SESSION_ID}=${session_id_1.sessionId}\r\n`);
122
+ const reaper = new RealReaper(startedContainer, socket);
123
+ resolve(reaper);
124
+ });
120
125
  });
121
- });
126
+ }, (result) => result !== undefined, () => new Error(`Failed to connect to Reaper ${containerId}`), 4000);
127
+ if (retryResult instanceof RealReaper) {
128
+ return retryResult;
129
+ }
130
+ else {
131
+ throw retryResult;
132
+ }
122
133
  });
123
134
  }
124
135
  }
@@ -12,6 +12,6 @@ declare abstract class AbstractRetryStrategy<T, U> implements RetryStrategy<T, U
12
12
  export declare class IntervalRetryStrategy<T, U> extends AbstractRetryStrategy<T, U> {
13
13
  private readonly interval;
14
14
  constructor(interval: number);
15
- retryUntil(fn: () => Promise<T>, predicate: (result: T) => boolean, onTimeout: () => U, timeout: number): Promise<T | U>;
15
+ retryUntil(fn: (attempt: number) => Promise<T>, predicate: (result: T) => boolean, onTimeout: () => U, timeout: number): Promise<T | U>;
16
16
  }
17
17
  export {};
@@ -30,13 +30,14 @@ class IntervalRetryStrategy extends AbstractRetryStrategy {
30
30
  retryUntil(fn, predicate, onTimeout, timeout) {
31
31
  return __awaiter(this, void 0, void 0, function* () {
32
32
  const startTime = this.clock.getTime();
33
- let result = yield fn();
33
+ let attemptNumber = 0;
34
+ let result = yield fn(attemptNumber++);
34
35
  while (!predicate(result)) {
35
36
  if (this.hasTimedOut(timeout, startTime)) {
36
37
  return onTimeout();
37
38
  }
38
39
  yield this.wait(this.interval);
39
- result = yield fn();
40
+ result = yield fn(attemptNumber++);
40
41
  }
41
42
  return result;
42
43
  });
@@ -0,0 +1,8 @@
1
+ import { AbstractWaitStrategy } from "./wait-strategy";
2
+ import Dockerode from "dockerode";
3
+ import { BoundPorts } from "./bound-ports";
4
+ export declare type StartupStatus = "PENDING" | "SUCCESS" | "FAIL";
5
+ export declare abstract class StartupCheckStrategy extends AbstractWaitStrategy {
6
+ abstract checkStartupState(dockerClient: Dockerode, containerId: string): Promise<StartupStatus>;
7
+ waitUntilReady(container: Dockerode.Container, host: string, ports: BoundPorts): Promise<void>;
8
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.StartupCheckStrategy = void 0;
13
+ const wait_strategy_1 = require("./wait-strategy");
14
+ const retry_strategy_1 = require("./retry-strategy");
15
+ const docker_client_1 = require("./docker/docker-client");
16
+ class StartupCheckStrategy extends wait_strategy_1.AbstractWaitStrategy {
17
+ waitUntilReady(container, host, ports) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ const { dockerode } = yield (0, docker_client_1.dockerClient)();
20
+ const startupStatus = yield new retry_strategy_1.IntervalRetryStrategy(1000).retryUntil(() => __awaiter(this, void 0, void 0, function* () { return yield this.checkStartupState(dockerode, container.id); }), (startupStatus) => startupStatus === "SUCCESS" || startupStatus === "FAIL", () => new Error(`Container not accessible after ${this.startupTimeout}ms for ${container.id}`), this.startupTimeout);
21
+ if (startupStatus instanceof Error) {
22
+ throw startupStatus;
23
+ }
24
+ else if (startupStatus === "FAIL") {
25
+ throw new Error(`Container failed to start for ${container.id}`);
26
+ }
27
+ });
28
+ }
29
+ }
30
+ exports.StartupCheckStrategy = StartupCheckStrategy;
@@ -0,0 +1,4 @@
1
+ import Dockerode from "dockerode";
2
+ import { BoundPorts } from "./bound-ports";
3
+ import { WaitStrategy } from "./wait-strategy";
4
+ export declare const waitForContainer: (container: Dockerode.Container, waitStrategy: WaitStrategy, host: string, boundPorts: BoundPorts) => Promise<void>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.waitForContainer = void 0;
13
+ const logger_1 = require("./logger");
14
+ const stop_container_1 = require("./docker/functions/container/stop-container");
15
+ const remove_container_1 = require("./docker/functions/container/remove-container");
16
+ const waitForContainer = (container, waitStrategy, host, boundPorts) => __awaiter(void 0, void 0, void 0, function* () {
17
+ logger_1.log.debug(`Waiting for container to be ready: ${container.id}`);
18
+ try {
19
+ yield waitStrategy.waitUntilReady(container, host, boundPorts);
20
+ logger_1.log.info("Container is ready");
21
+ }
22
+ catch (err) {
23
+ logger_1.log.error(`Container failed to be ready: ${err}`);
24
+ try {
25
+ yield (0, stop_container_1.stopContainer)(container, { timeout: 0 });
26
+ yield (0, remove_container_1.removeContainer)(container, { removeVolumes: true });
27
+ }
28
+ catch (stopErr) {
29
+ logger_1.log.error(`Failed to stop container after it failed to be ready: ${stopErr}`);
30
+ }
31
+ throw err;
32
+ }
33
+ });
34
+ exports.waitForContainer = waitForContainer;
@@ -2,19 +2,19 @@ import { BoundPorts } from "./bound-ports";
2
2
  import { PortCheck } from "./port-check";
3
3
  import Dockerode from "dockerode";
4
4
  export interface WaitStrategy {
5
- waitUntilReady(container: Dockerode.Container, boundPorts: BoundPorts): Promise<void>;
5
+ waitUntilReady(container: Dockerode.Container, host: string, boundPorts: BoundPorts): Promise<void>;
6
6
  withStartupTimeout(startupTimeout: number): WaitStrategy;
7
7
  }
8
- declare abstract class AbstractWaitStrategy implements WaitStrategy {
8
+ export declare abstract class AbstractWaitStrategy implements WaitStrategy {
9
9
  protected startupTimeout: number;
10
- abstract waitUntilReady(container: Dockerode.Container, boundPorts: BoundPorts): Promise<void>;
10
+ abstract waitUntilReady(container: Dockerode.Container, host: string, boundPorts: BoundPorts): Promise<void>;
11
11
  withStartupTimeout(startupTimeout: number): WaitStrategy;
12
12
  }
13
13
  export declare class HostPortWaitStrategy extends AbstractWaitStrategy {
14
14
  private readonly hostPortCheck;
15
15
  private readonly internalPortCheck;
16
16
  constructor(hostPortCheck: PortCheck, internalPortCheck: PortCheck);
17
- waitUntilReady(container: Dockerode.Container, boundPorts: BoundPorts): Promise<void>;
17
+ waitUntilReady(container: Dockerode.Container, host: string, boundPorts: BoundPorts): Promise<void>;
18
18
  private waitForHostPorts;
19
19
  private waitForInternalPorts;
20
20
  private waitForPort;
@@ -28,4 +28,4 @@ export declare class LogWaitStrategy extends AbstractWaitStrategy {
28
28
  export declare class HealthCheckWaitStrategy extends AbstractWaitStrategy {
29
29
  waitUntilReady(container: Dockerode.Container): Promise<void>;
30
30
  }
31
- export {};
31
+ export declare const defaultWaitStrategy: (host: string, container: Dockerode.Container) => HostPortWaitStrategy;
@@ -12,9 +12,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.HealthCheckWaitStrategy = exports.LogWaitStrategy = exports.HostPortWaitStrategy = void 0;
15
+ exports.defaultWaitStrategy = exports.HealthCheckWaitStrategy = exports.LogWaitStrategy = exports.HostPortWaitStrategy = exports.AbstractWaitStrategy = void 0;
16
16
  const byline_1 = __importDefault(require("byline"));
17
17
  const logger_1 = require("./logger");
18
+ const port_check_1 = require("./port-check");
18
19
  const retry_strategy_1 = require("./retry-strategy");
19
20
  const container_logs_1 = require("./docker/functions/container/container-logs");
20
21
  const inspect_container_1 = require("./docker/functions/container/inspect-container");
@@ -27,13 +28,14 @@ class AbstractWaitStrategy {
27
28
  return this;
28
29
  }
29
30
  }
31
+ exports.AbstractWaitStrategy = AbstractWaitStrategy;
30
32
  class HostPortWaitStrategy extends AbstractWaitStrategy {
31
33
  constructor(hostPortCheck, internalPortCheck) {
32
34
  super();
33
35
  this.hostPortCheck = hostPortCheck;
34
36
  this.internalPortCheck = internalPortCheck;
35
37
  }
36
- waitUntilReady(container, boundPorts) {
38
+ waitUntilReady(container, host, boundPorts) {
37
39
  return __awaiter(this, void 0, void 0, function* () {
38
40
  yield Promise.all([this.waitForHostPorts(container, boundPorts), this.waitForInternalPorts(container, boundPorts)]);
39
41
  });
@@ -127,3 +129,5 @@ class HealthCheckWaitStrategy extends AbstractWaitStrategy {
127
129
  }
128
130
  }
129
131
  exports.HealthCheckWaitStrategy = HealthCheckWaitStrategy;
132
+ const defaultWaitStrategy = (host, container) => new HostPortWaitStrategy(new port_check_1.HostPortCheck(host), new port_check_1.InternalPortCheck(container));
133
+ exports.defaultWaitStrategy = defaultWaitStrategy;
package/dist/wait.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { Log, WaitStrategy } from "./wait-strategy";
2
+ import { HttpWaitStrategy } from "./http-wait-strategy";
2
3
  export declare class Wait {
3
4
  static forLogMessage(message: Log | RegExp): WaitStrategy;
4
5
  static forHealthCheck(): WaitStrategy;
6
+ static forHttp(path: string, port: number): HttpWaitStrategy;
5
7
  }
package/dist/wait.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Wait = void 0;
4
4
  const wait_strategy_1 = require("./wait-strategy");
5
+ const http_wait_strategy_1 = require("./http-wait-strategy");
5
6
  class Wait {
6
7
  static forLogMessage(message) {
7
8
  return new wait_strategy_1.LogWaitStrategy(message);
@@ -9,5 +10,8 @@ class Wait {
9
10
  static forHealthCheck() {
10
11
  return new wait_strategy_1.HealthCheckWaitStrategy();
11
12
  }
13
+ static forHttp(path, port) {
14
+ return new http_wait_strategy_1.HttpWaitStrategy(path, port);
15
+ }
12
16
  }
13
17
  exports.Wait = Wait;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "testcontainers",
3
3
  "author": "Cristian Greco",
4
- "version": "9.0.0",
4
+ "version": "9.1.0",
5
5
  "main": "dist/index",
6
6
  "types": "dist/index",
7
7
  "keywords": [