Skip to content

Testcontainer example #701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
checkpoint
Signed-off-by: Joe Bowbeer <joe.bowbeer@gmail.com>
  • Loading branch information
joebowbeer committed May 27, 2025
commit 2666f3d998c2083a7763f69e01897323dd0becd4
5 changes: 4 additions & 1 deletion examples/testcontainers/src/DaprContainer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@ limitations under the License.

// import { setTimeout } from "node:timers/promises";
// import { GenericContainer, Network, Wait } from "testcontainers";
import { Network } from "testcontainers";
import { DaprContainer, DAPRD_DEFAULT_GRPC_PORT, DAPRD_DEFAULT_HTTP_PORT } from "./DaprContainer";

// jest.setTimeout(120_000);

describe("DaprContainer", () => {
it("should start and stop", async () => {
const container = new DaprContainer("daprio/dapr:latest");
const network = await new Network().start();
const container = new DaprContainer("daprio/dapr:latest").withNetwork(network);
const startedContainer = await container.start();
expect(startedContainer.getHost()).toBeDefined();
expect(startedContainer.getMappedPort(DAPRD_DEFAULT_HTTP_PORT)).toBeDefined();
expect(startedContainer.getMappedPort(DAPRD_DEFAULT_GRPC_PORT)).toBeDefined();
await startedContainer.stop();
await network.stop();
}, 120_000);
});
158 changes: 79 additions & 79 deletions examples/testcontainers/src/DaprContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,19 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { AbstractStartedContainer, GenericContainer, Network, StartedTestContainer, Wait } from "testcontainers";
import {
AbstractStartedContainer,
GenericContainer,
log,
StartedNetwork,
StartedTestContainer,
StopOptions,
StoppedTestContainer,
Wait
} from "testcontainers";
import { DaprPlacementContainer } from "./DaprPlacementContainer";
import { DaprSchedulerContainer } from "./DaprSchedulerContainer";
import assert from "node:assert";

export const DAPR_VERSION = "1.15.4";
export const DAPR_RUNTIME_IMAGE = "daprio/daprd:" + DAPR_VERSION;
Expand All @@ -24,19 +36,20 @@ export const DAPR_PROTOCOL = "http";

export class DaprContainer extends GenericContainer {
private daprLogLevel = "info";
private appChannelAddress = "localhost";
private appChannelAddress = "localhost"; // TODO?
private placementService = "placement";
private schedulerService = "scheduler";
private placementDockerImageName = DAPR_PLACEMENT_IMAGE;
private schedulerDockerImageName = DAPR_SCHEDULER_IMAGE;
// private configuration: Configuration;
private placementContainer: GenericContainer;
private schedulerContainer: GenericContainer;
private appName: string;
private appPort: number;
private appHealthCheckPath: string;
private shouldReusePlacement: boolean;
private shouldReuseScheduler: boolean;
private placementContainer?: DaprPlacementContainer;
private schedulerContainer?: DaprSchedulerContainer;
private appName?: string;
private appPort?: number;
private appHealthCheckPath?: string;
// private shouldReusePlacement?: boolean;
// private shouldReuseScheduler?: boolean;
private startedNetwork?: StartedNetwork;

constructor(image = DAPR_RUNTIME_IMAGE) {
super(image);
Expand All @@ -46,87 +59,70 @@ export class DaprContainer extends GenericContainer {
.withStartupTimeout(120_000)
}

public withNetwork(network: StartedNetwork): this {
this.startedNetwork = network;
return super.withNetwork(network);
}

public override async start(): Promise<StartedDaprContainer> {
return new StartedDaprContainer(await super.start());
assert(this.startedNetwork, "Network must be provided before starting the container");
if (!this.placementContainer) {
this.placementContainer = new DaprPlacementContainer(this.placementDockerImageName)
.withNetwork(this.startedNetwork)
.withNetworkAliases(this.placementService);
}
if (!this.schedulerContainer) {
this.schedulerContainer = new DaprSchedulerContainer(this.schedulerDockerImageName)
.withNetwork(this.startedNetwork)
.withNetworkAliases(this.schedulerService);
}
const containers = await Promise.all([
this.placementContainer.start(),
this.schedulerContainer.start(),
]);
return new StartedDaprContainer(await super.start(), containers);
}

protected override async beforeContainerCreated(): Promise<void> {
this.withCommand([
assert(this.placementContainer, "Placement container must be provided");
assert(this.schedulerContainer, "Scheduler container must be provided");
const cmds = [
"./daprd",
"--app-id",
"FIXME",
this.appName ?? "dapr-app",
"--dapr-listen-addresses=0.0.0.0",
"--app-protocol",
DAPR_PROTOCOL,
"--placement-host-address",
`${this.placementService}:50005`,
`${this.placementService}:${this.placementContainer.getPort()}`,
"--scheduler-host-address",
`${this.schedulerService}:51005`,
]);

// if (!this.networkMode) {
// this.withNetwork(await new Network().start());
// }

// if (this.placementContainer == null) {
// this.placementContainer = new DaprPlacementContainer(this.placementDockerImageName)
// .withNetwork(getNetwork())
// .withNetworkAliases(placementService)
// .withReuse(this.shouldReusePlacement);
// this.placementContainer.start();
// }

// if (this.schedulerContainer == null) {
// this.schedulerContainer = new DaprSchedulerContainer(this.schedulerDockerImageName)
// .withNetwork(getNetwork())
// .withNetworkAliases(schedulerService)
// .withReuse(this.shouldReuseScheduler);
// this.schedulerContainer.start();
// }

// List<String> cmds = new ArrayList<>();
// cmds.add("./daprd");
// cmds.add("--app-id");
// cmds.add(appName);
// cmds.add("--dapr-listen-addresses=0.0.0.0");
// cmds.add("--app-protocol");
// cmds.add(DAPR_PROTOCOL.getName());
// cmds.add("--placement-host-address");
// cmds.add(placementService + ":50005");
// cmds.add("--scheduler-host-address");
// cmds.add(schedulerService + ":51005");

// if (appChannelAddress != null && !appChannelAddress.isEmpty()) {
// cmds.add("--app-channel-address");
// cmds.add(appChannelAddress);
`${this.schedulerService}:${this.schedulerContainer.getPort()}`,
"--log-level",
this.daprLogLevel,
// "--resources-path",
// "/dapr-resources",
];

if (this.appChannelAddress) {
cmds.push("--app-channel-address", this.appChannelAddress);
}

if (this.appPort) {
cmds.push("--app-port", this.appPort.toString());
}

if (this.appHealthCheckPath) {
cmds.push("--enable-app-health-check", "--app-health-check-path", this.appHealthCheckPath);
}

// if (this.configuration) {
// cmds.push("--config", `/dapr-resources/${this.configuration.getName()}.yaml`);
// }

// if (appPort != null) {
// cmds.add("--app-port");
// cmds.add(Integer.toString(appPort));
// }
log.info("> `daprd` Command: \n");
log.info("\t" + cmds + "\n");

// if (appHealthCheckPath != null && !appHealthCheckPath.isEmpty()) {
// cmds.add("--enable-app-health-check");
// cmds.add("--app-health-check-path");
// cmds.add(appHealthCheckPath);
// }

// if (configuration != null) {
// cmds.add("--config");
// cmds.add("/dapr-resources/" + configuration.getName() + ".yaml");
// }

// cmds.add("--log-level");
// cmds.add(daprLogLevel.toString());
// cmds.add("--resources-path");
// cmds.add("/dapr-resources");

// String[] cmdArray = cmds.toArray(new String[]{});
// LOGGER.info("> `daprd` Command: \n");
// LOGGER.info("\t" + Arrays.toString(cmdArray) + "\n");

// withCommand(cmdArray);
this.withCommand(cmds);

// if (configuration != null) {
// String configurationYaml = CONFIGURATION_CONVERTER.convert(configuration);
Expand Down Expand Up @@ -172,8 +168,6 @@ export class DaprContainer extends GenericContainer {

// withCopyToContainer(Transferable.of(endpointYaml), "/dapr-resources/" + endpoint.getName() + ".yaml");
// }

// dependsOn(placementContainer, schedulerContainer);
}

// public override async start(): Promise<StartedK3sContainer> {
Expand All @@ -199,9 +193,15 @@ export class DaprContainer extends GenericContainer {
}

export class StartedDaprContainer extends AbstractStartedContainer {
constructor(startedTestContainer: StartedTestContainer) {
constructor(startedTestContainer: StartedTestContainer, private readonly containers: StartedTestContainer[]) {
super(startedTestContainer);
}

async stop(options?: Partial<StopOptions>): Promise<StoppedTestContainer> {
const stoppedTestContainer = await super.stop(options);
await Promise.all(this.containers.map((container) => container.stop(options)));
return stoppedTestContainer;
}
}

// export class StartedK3sContainer extends AbstractStartedContainer {
Expand Down
38 changes: 38 additions & 0 deletions examples/testcontainers/src/DaprPlacementContainer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { GenericContainer, Wait } from "testcontainers";

export class DaprPlacementContainer extends GenericContainer {
private placementPort = 50005;

constructor(image: string) {
super(image);
this.withWaitStrategy(Wait.forLogMessage(/Placement service started/))
.withStartupTimeout(120_000)
}

protected async beforeContainerCreated(): Promise<void> {
this.withExposedPorts(this.placementPort);
this.withCommand(["./placement", "-port", this.placementPort.toString()]);
}

withPort(port: number): this {
this.placementPort = port;
return this;
}

getPort(): number {
return this.placementPort;
}
}
42 changes: 42 additions & 0 deletions examples/testcontainers/src/DaprSchedulerContainer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { GenericContainer, Wait } from "testcontainers";

export class DaprSchedulerContainer extends GenericContainer {
private schedulerPort = 51005;

constructor(image: string) {
super(image);
this.withWaitStrategy(Wait.forLogMessage(/Dapr Scheduler listening/))
.withStartupTimeout(120_000)
}

protected async beforeContainerCreated(): Promise<void> {
this.withCopyContentToContainer([
{ content: "", target: "./default-dapr-scheduler-server-0/dapr-0.1/", mode: 0o777 },
{ content: "", target: "./dapr-scheduler-existing-cluster/", mode: 0o777 },
]);
this.withExposedPorts(this.schedulerPort);
this.withCommand(["./scheduler", "--port", this.schedulerPort.toString(), "--etcd-data-dir", "."]);
}

withPort(port: number): this {
this.schedulerPort = port;
return this;
}

getPort(): number {
return this.schedulerPort;
}
}