diff --git a/README.md b/README.md index 80c8946114..a824bd2d0d 100644 --- a/README.md +++ b/README.md @@ -513,6 +513,175 @@ aws --endpoint-url http://localhost:4566 s3 rm s3://my-bucket/demo.txt rm -f "$tmp_file" ``` +## Testcontainers + +Floci has first-class Testcontainers modules so you can start a real Floci instance from your tests with zero manual setup — no running daemon, no shared state, no port conflicts. + +| Language | Package | Latest | Registry | Source | +|---|---|---|---|---| +| Java | `io.floci:testcontainers-floci` | `1.4.0` | [Maven Central](https://mvnrepository.com/artifact/io.floci/testcontainers-floci) | [GitHub](https://github.com/floci-io/testcontainers-floci) | +| Node.js | `@floci/testcontainers` | `0.1.0` | [npm](https://www.npmjs.com/package/@floci/testcontainers) | [GitHub](https://github.com/floci-io/testcontainers-floci-node) | +| Python | `testcontainers-floci` | `0.1.1` | [PyPI](https://pypi.org/project/testcontainers-floci/) | [GitHub](https://github.com/floci-io/testcontainers-floci-python) | +| Go | — | 🚧 In progress | — | [GitHub](https://github.com/floci-io/testcontainers-floci-go) | + +### Java + +Add the dependency (Testcontainers 1.x / Spring Boot 3.x): + +```xml + + io.floci + testcontainers-floci + 1.4.0 + test + +``` + +For Testcontainers 2.x / Spring Boot 4.x use version `2.5.0`. + +Basic usage with JUnit 5: + +```java +@Testcontainers +class S3IntegrationTest { + + @Container + static FlociContainer floci = new FlociContainer(); + + @Test + void shouldCreateBucket() { + S3Client s3 = S3Client.builder() + .endpointOverride(URI.create(floci.getEndpoint())) + .region(Region.of(floci.getRegion())) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(floci.getAccessKey(), floci.getSecretKey()))) + .forcePathStyle(true) + .build(); + + s3.createBucket(b -> b.bucket("my-bucket")); + + assertThat(s3.listBuckets().buckets()) + .anyMatch(b -> b.name().equals("my-bucket")); + } +} +``` + +**Spring Boot** — add `spring-boot-testcontainers-floci` and use `@ServiceConnection` for zero-config auto-wiring: + +```java +@SpringBootTest +@Testcontainers +class AppIntegrationTest { + + @Container + @ServiceConnection + static FlociContainer floci = new FlociContainer(); + + @Autowired + S3Client s3; + + @Test + void shouldCreateBucket() { + s3.createBucket(b -> b.bucket("my-bucket")); + assertThat(s3.listBuckets().buckets()) + .anyMatch(b -> b.name().equals("my-bucket")); + } +} +``` + +### Node.js / TypeScript + +```sh +npm install --save-dev @floci/testcontainers +``` + +```ts +import { FlociContainer } from "@floci/testcontainers"; +import { S3Client, CreateBucketCommand, ListBucketsCommand } from "@aws-sdk/client-s3"; + +describe("S3", () => { + let floci: FlociContainer; + + beforeAll(async () => { + floci = await new FlociContainer().start(); + }); + + afterAll(async () => { + await floci.stop(); + }); + + it("should create and list a bucket", async () => { + const s3 = new S3Client({ + endpoint: floci.getEndpoint(), + region: floci.getRegion(), + credentials: { + accessKeyId: floci.getAccessKey(), + secretAccessKey: floci.getSecretKey(), + }, + forcePathStyle: true, + }); + + await s3.send(new CreateBucketCommand({ Bucket: "my-bucket" })); + const { Buckets } = await s3.send(new ListBucketsCommand({})); + expect(Buckets?.some(b => b.Name === "my-bucket")).toBe(true); + }); +}); +``` + +### Python + +```sh +pip install testcontainers-floci +``` + +```python +import boto3 +from testcontainers_floci import FlociContainer + +def test_s3_create_bucket(): + with FlociContainer() as floci: + s3 = boto3.client( + "s3", + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + + s3.create_bucket(Bucket="my-bucket") + buckets = s3.list_buckets()["Buckets"] + assert any(b["Name"] == "my-bucket" for b in buckets) +``` + +Pytest fixture style: + +```python +import pytest +import boto3 +from testcontainers_floci import FlociContainer + +@pytest.fixture(scope="session") +def floci(): + with FlociContainer() as container: + yield container + +def test_s3_create_bucket(floci): + s3 = boto3.client( + "s3", + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + s3.create_bucket(Bucket="my-bucket") + buckets = s3.list_buckets()["Buckets"] + assert any(b["Name"] == "my-bucket" for b in buckets) +``` + +### Go + +Go support is in progress. Track it at [testcontainers-floci-go](https://github.com/floci-io/testcontainers-floci-go). + ## Compatibility Testing > For full compatibility validation against real SDK and client workflows, see the [compatibility-tests](./compatibility-tests/) directory. diff --git a/docs/testcontainers/go.md b/docs/testcontainers/go.md new file mode 100644 index 0000000000..a53785878f --- /dev/null +++ b/docs/testcontainers/go.md @@ -0,0 +1,79 @@ +# Testcontainers — Go + +!!! warning "In progress" + Go support is under active development. Track the work at + [github.com/floci-io/testcontainers-floci-go](https://github.com/floci-io/testcontainers-floci-go). + + The page below shows the planned API. Details may change before the first release. + +## Planned usage + +The module will follow the standard [Testcontainers for Go](https://golang.testcontainers.org/) patterns. + +```go +package myservice_test + +import ( + "context" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + floci "github.com/floci-io/testcontainers-floci-go" +) + +func TestS3CreateBucket(t *testing.T) { + ctx := context.Background() + + container, err := floci.RunContainer(ctx) + if err != nil { + t.Fatal(err) + } + defer container.Terminate(ctx) + + cfg, err := config.LoadDefaultConfig(ctx, + config.WithRegion(container.Region()), + config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider( + container.AccessKey(), container.SecretKey(), "", + )), + config.WithBaseEndpoint(container.Endpoint()), + ) + if err != nil { + t.Fatal(err) + } + + client := s3.NewFromConfig(cfg, func(o *s3.Options) { + o.UsePathStyle = true + }) + + _, err = client.CreateBucket(ctx, &s3.CreateBucketInput{ + Bucket: aws.String("my-bucket"), + }) + if err != nil { + t.Fatal(err) + } + + out, err := client.ListBuckets(ctx, &s3.ListBucketsInput{}) + if err != nil { + t.Fatal(err) + } + + found := false + for _, b := range out.Buckets { + if aws.ToString(b.Name) == "my-bucket" { + found = true + break + } + } + if !found { + t.Error("bucket not found after create") + } +} +``` + +## Contribute + +If you would like to help build the Go module, open an issue or pull request at +[github.com/floci-io/testcontainers-floci-go](https://github.com/floci-io/testcontainers-floci-go). diff --git a/docs/testcontainers/index.md b/docs/testcontainers/index.md new file mode 100644 index 0000000000..5027e93736 --- /dev/null +++ b/docs/testcontainers/index.md @@ -0,0 +1,32 @@ +# Testcontainers + +Floci has first-class Testcontainers modules for every major SDK language. Each module starts a real Floci container before your tests run and tears it down after — no running daemon, no shared state, no port conflicts. + +## Available modules + +| Language | Package | Version | Registry | Source | +|---|---|---|---|---| +| Java | `io.floci:testcontainers-floci` | `1.4.0` | [Maven Central](https://mvnrepository.com/artifact/io.floci/testcontainers-floci) | [GitHub](https://github.com/floci-io/testcontainers-floci) | +| Node.js | `@floci/testcontainers` | `0.1.0` | [npm](https://www.npmjs.com/package/@floci/testcontainers) | [GitHub](https://github.com/floci-io/testcontainers-floci-node) | +| Python | `testcontainers-floci` | `0.1.1` | [PyPI](https://pypi.org/project/testcontainers-floci/) | [GitHub](https://github.com/floci-io/testcontainers-floci-python) | +| Go | — | 🚧 In progress | — | [GitHub](https://github.com/floci-io/testcontainers-floci-go) | + +## How it works + +Every module exposes a `FlociContainer` class that wraps the official `floci/floci:latest` Docker image. When the container starts it waits for port 4566 to be ready, then exposes: + +| Method | Returns | +|---|---| +| `getEndpoint()` | `http://localhost:` | +| `getRegion()` | `us-east-1` (default) | +| `getAccessKey()` | `test` | +| `getSecretKey()` | `test` | + +You pass these values directly into any AWS SDK client — no manual configuration, no environment variables. + +## Language guides + +- [Java](java.md) — JUnit 5, Spring Boot `@ServiceConnection` +- [Node.js / TypeScript](nodejs.md) — Jest, Vitest +- [Python](python.md) — pytest +- [Go](go.md) — in progress diff --git a/docs/testcontainers/java.md b/docs/testcontainers/java.md new file mode 100644 index 0000000000..c8dad0796b --- /dev/null +++ b/docs/testcontainers/java.md @@ -0,0 +1,232 @@ +# Testcontainers — Java + +The `testcontainers-floci` library integrates Floci with [Testcontainers for Java](https://java.testcontainers.org/). It starts a real Floci container before your tests and shuts it down after, with no extra setup. + +Two artifact lines are published to keep in sync with the Testcontainers major version: + +| Testcontainers version | Spring Boot | Artifact version | +|---|---|---| +| 1.x | 3.x | `1.4.0` | +| 2.x | 4.x | `2.5.0` | + +## Installation + +=== "Maven" + + ```xml + + io.floci + testcontainers-floci + 1.4.0 + test + + ``` + +=== "Gradle" + + ```groovy + testImplementation 'io.floci:testcontainers-floci:1.4.0' + ``` + +## Basic usage — JUnit 5 + +Annotate the class with `@Testcontainers` and declare a static `FlociContainer` field with `@Container`. Testcontainers handles the lifecycle automatically. + +```java +import io.floci.testcontainers.FlociContainer; +import org.junit.jupiter.api.Test; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; + +import java.net.URI; + +import static org.assertj.core.api.Assertions.assertThat; + +@Testcontainers +class S3IntegrationTest { + + @Container + static FlociContainer floci = new FlociContainer(); + + @Test + void shouldCreateBucket() { + S3Client s3 = S3Client.builder() + .endpointOverride(URI.create(floci.getEndpoint())) + .region(Region.of(floci.getRegion())) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(floci.getAccessKey(), floci.getSecretKey()))) + .forcePathStyle(true) + .build(); + + s3.createBucket(b -> b.bucket("my-bucket")); + + assertThat(s3.listBuckets().buckets()) + .anyMatch(b -> b.name().equals("my-bucket")); + } +} +``` + +## SQS example + +```java +@Testcontainers +class SqsIntegrationTest { + + @Container + static FlociContainer floci = new FlociContainer(); + + @Test + void shouldSendAndReceiveMessage() { + SqsClient sqs = SqsClient.builder() + .endpointOverride(URI.create(floci.getEndpoint())) + .region(Region.of(floci.getRegion())) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(floci.getAccessKey(), floci.getSecretKey()))) + .build(); + + String queueUrl = sqs.createQueue(b -> b.queueName("orders")).queueUrl(); + sqs.sendMessage(b -> b.queueUrl(queueUrl).messageBody("{\"event\":\"order.placed\"}")); + + var messages = sqs.receiveMessage(b -> b.queueUrl(queueUrl).maxNumberOfMessages(1)).messages(); + assertThat(messages).hasSize(1); + assertThat(messages.get(0).body()).contains("order.placed"); + } +} +``` + +## DynamoDB example + +```java +@Testcontainers +class DynamoDbIntegrationTest { + + @Container + static FlociContainer floci = new FlociContainer(); + + @Test + void shouldCreateTableAndPutItem() { + DynamoDbClient dynamo = DynamoDbClient.builder() + .endpointOverride(URI.create(floci.getEndpoint())) + .region(Region.of(floci.getRegion())) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(floci.getAccessKey(), floci.getSecretKey()))) + .build(); + + dynamo.createTable(b -> b + .tableName("Orders") + .attributeDefinitions(a -> a.attributeName("id").attributeType(ScalarAttributeType.S)) + .keySchema(k -> k.attributeName("id").keyType(KeyType.HASH)) + .billingMode(BillingMode.PAY_PER_REQUEST)); + + dynamo.putItem(b -> b + .tableName("Orders") + .item(Map.of("id", AttributeValue.fromS("order-1"), + "status", AttributeValue.fromS("placed")))); + + var item = dynamo.getItem(b -> b + .tableName("Orders") + .key(Map.of("id", AttributeValue.fromS("order-1")))).item(); + + assertThat(item.get("status").s()).isEqualTo("placed"); + } +} +``` + +## Spring Boot — `@ServiceConnection` + +Add the Spring Boot companion artifact for zero-config auto-wiring. The `@ServiceConnection` annotation registers the container as a `ConnectionDetails` bean and configures all AWS SDK clients automatically. + +=== "Maven" + + ```xml + + io.floci + spring-boot-testcontainers-floci + 1.4.0 + test + + ``` + +=== "Gradle" + + ```groovy + testImplementation 'io.floci:spring-boot-testcontainers-floci:1.4.0' + ``` + +```java +import io.floci.testcontainers.FlociContainer; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import software.amazon.awssdk.services.s3.S3Client; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Testcontainers +class AppIntegrationTest { + + @Container + @ServiceConnection + static FlociContainer floci = new FlociContainer(); + + @Autowired + S3Client s3; + + @Test + void shouldCreateBucket() { + s3.createBucket(b -> b.bucket("my-bucket")); + + assertThat(s3.listBuckets().buckets()) + .anyMatch(b -> b.name().equals("my-bucket")); + } +} +``` + +With `@ServiceConnection`, Spring Boot auto-configures the endpoint URL, region, and credentials for every AWS SDK client bean in the application context — no `application-test.yml` overrides needed. + +## Reusing the container across tests + +Declare the container in a shared base class or a JUnit 5 extension to start it once per test suite rather than once per class: + +```java +abstract class FlociTestBase { + + @Container + static FlociContainer floci = new FlociContainer(); + + static S3Client s3; + + @BeforeAll + static void setUpClients() { + s3 = S3Client.builder() + .endpointOverride(URI.create(floci.getEndpoint())) + .region(Region.of(floci.getRegion())) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(floci.getAccessKey(), floci.getSecretKey()))) + .forcePathStyle(true) + .build(); + } +} + +@Testcontainers +class MyServiceTest extends FlociTestBase { + + @Test + void myTest() { + s3.createBucket(b -> b.bucket("test-bucket")); + // ... + } +} +``` + +## Source and changelog + +[github.com/floci-io/testcontainers-floci](https://github.com/floci-io/testcontainers-floci) diff --git a/docs/testcontainers/nodejs.md b/docs/testcontainers/nodejs.md new file mode 100644 index 0000000000..8a8a666d67 --- /dev/null +++ b/docs/testcontainers/nodejs.md @@ -0,0 +1,270 @@ +# Testcontainers — Node.js / TypeScript + +The `@floci/testcontainers` package integrates Floci with [Testcontainers for Node.js](https://node.testcontainers.org/). It works with any test runner that supports `async`/`await` — Jest, Vitest, Mocha, and others. + +## Installation + +```sh +npm install --save-dev @floci/testcontainers +``` + +```sh +# yarn +yarn add --dev @floci/testcontainers + +# pnpm +pnpm add -D @floci/testcontainers +``` + +## Basic usage — Jest + +```typescript +import { FlociContainer } from "@floci/testcontainers"; +import { S3Client, CreateBucketCommand, ListBucketsCommand } from "@aws-sdk/client-s3"; + +describe("S3", () => { + let floci: FlociContainer; + + beforeAll(async () => { + floci = await new FlociContainer().start(); + }); + + afterAll(async () => { + await floci.stop(); + }); + + it("should create and list a bucket", async () => { + const s3 = new S3Client({ + endpoint: floci.getEndpoint(), + region: floci.getRegion(), + credentials: { + accessKeyId: floci.getAccessKey(), + secretAccessKey: floci.getSecretKey(), + }, + forcePathStyle: true, + }); + + await s3.send(new CreateBucketCommand({ Bucket: "my-bucket" })); + + const { Buckets } = await s3.send(new ListBucketsCommand({})); + expect(Buckets?.some(b => b.Name === "my-bucket")).toBe(true); + }); +}); +``` + +## SQS example + +```typescript +import { FlociContainer } from "@floci/testcontainers"; +import { + SQSClient, + CreateQueueCommand, + SendMessageCommand, + ReceiveMessageCommand, +} from "@aws-sdk/client-sqs"; + +describe("SQS", () => { + let floci: FlociContainer; + let sqs: SQSClient; + + beforeAll(async () => { + floci = await new FlociContainer().start(); + sqs = new SQSClient({ + endpoint: floci.getEndpoint(), + region: floci.getRegion(), + credentials: { + accessKeyId: floci.getAccessKey(), + secretAccessKey: floci.getSecretKey(), + }, + }); + }); + + afterAll(async () => { + await floci.stop(); + }); + + it("should send and receive a message", async () => { + const { QueueUrl } = await sqs.send( + new CreateQueueCommand({ QueueName: "orders" }) + ); + + await sqs.send( + new SendMessageCommand({ + QueueUrl, + MessageBody: JSON.stringify({ event: "order.placed" }), + }) + ); + + const { Messages } = await sqs.send( + new ReceiveMessageCommand({ QueueUrl, MaxNumberOfMessages: 1 }) + ); + + expect(Messages).toHaveLength(1); + expect(JSON.parse(Messages![0].Body!).event).toBe("order.placed"); + }); +}); +``` + +## DynamoDB example + +```typescript +import { FlociContainer } from "@floci/testcontainers"; +import { + DynamoDBClient, + CreateTableCommand, + PutItemCommand, + GetItemCommand, +} from "@aws-sdk/client-dynamodb"; + +describe("DynamoDB", () => { + let floci: FlociContainer; + let dynamo: DynamoDBClient; + + beforeAll(async () => { + floci = await new FlociContainer().start(); + dynamo = new DynamoDBClient({ + endpoint: floci.getEndpoint(), + region: floci.getRegion(), + credentials: { + accessKeyId: floci.getAccessKey(), + secretAccessKey: floci.getSecretKey(), + }, + }); + }); + + afterAll(async () => { + await floci.stop(); + }); + + it("should put and get an item", async () => { + await dynamo.send( + new CreateTableCommand({ + TableName: "Orders", + AttributeDefinitions: [{ AttributeName: "id", AttributeType: "S" }], + KeySchema: [{ AttributeName: "id", KeyType: "HASH" }], + BillingMode: "PAY_PER_REQUEST", + }) + ); + + await dynamo.send( + new PutItemCommand({ + TableName: "Orders", + Item: { + id: { S: "order-1" }, + status: { S: "placed" }, + }, + }) + ); + + const { Item } = await dynamo.send( + new GetItemCommand({ + TableName: "Orders", + Key: { id: { S: "order-1" } }, + }) + ); + + expect(Item?.status?.S).toBe("placed"); + }); +}); +``` + +## Vitest + +The same pattern works with Vitest — replace `describe`/`it`/`expect` with their Vitest equivalents (the API is identical): + +```typescript +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { FlociContainer } from "@floci/testcontainers"; +import { S3Client, CreateBucketCommand, ListBucketsCommand } from "@aws-sdk/client-s3"; + +describe("S3", () => { + let floci: FlociContainer; + + beforeAll(async () => { + floci = await new FlociContainer().start(); + }); + + afterAll(async () => { + await floci.stop(); + }); + + it("should create a bucket", async () => { + const s3 = new S3Client({ + endpoint: floci.getEndpoint(), + region: floci.getRegion(), + credentials: { + accessKeyId: floci.getAccessKey(), + secretAccessKey: floci.getSecretKey(), + }, + forcePathStyle: true, + }); + + await s3.send(new CreateBucketCommand({ Bucket: "vitest-bucket" })); + + const { Buckets } = await s3.send(new ListBucketsCommand({})); + expect(Buckets?.some(b => b.Name === "vitest-bucket")).toBe(true); + }); +}); +``` + +## Reusing the container across test files + +Start the container once in a global setup file and expose the endpoint via an environment variable or a shared module so individual test files don't each start their own container. + +=== "Jest — globalSetup" + + ```typescript + // jest.global-setup.ts + import { FlociContainer } from "@floci/testcontainers"; + + let floci: FlociContainer; + + export async function setup() { + floci = await new FlociContainer().start(); + process.env.FLOCI_ENDPOINT = floci.getEndpoint(); + } + + export async function teardown() { + await floci?.stop(); + } + ``` + + ```json + // jest.config.json + { + "globalSetup": "./jest.global-setup.ts" + } + ``` + +=== "Vitest — globalSetup" + + ```typescript + // vitest.global-setup.ts + import { FlociContainer } from "@floci/testcontainers"; + + let floci: FlociContainer; + + export async function setup() { + floci = await new FlociContainer().start(); + process.env.FLOCI_ENDPOINT = floci.getEndpoint(); + } + + export async function teardown() { + await floci?.stop(); + } + ``` + + ```typescript + // vitest.config.ts + import { defineConfig } from "vitest/config"; + + export default defineConfig({ + test: { + globalSetup: "./vitest.global-setup.ts", + }, + }); + ``` + +## Source and changelog + +[github.com/floci-io/testcontainers-floci-node](https://github.com/floci-io/testcontainers-floci-node) diff --git a/docs/testcontainers/python.md b/docs/testcontainers/python.md new file mode 100644 index 0000000000..cacbdee700 --- /dev/null +++ b/docs/testcontainers/python.md @@ -0,0 +1,229 @@ +# Testcontainers — Python + +The `testcontainers-floci` package integrates Floci with [Testcontainers for Python](https://testcontainers-python.readthedocs.io/). It works as a context manager and integrates naturally with pytest fixtures. + +## Installation + +```sh +pip install testcontainers-floci +``` + +```sh +# poetry +poetry add --group dev testcontainers-floci + +# uv +uv add --dev testcontainers-floci +``` + +## Basic usage — context manager + +```python +import boto3 +from testcontainers_floci import FlociContainer + + +def test_s3_create_bucket(): + with FlociContainer() as floci: + s3 = boto3.client( + "s3", + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + + s3.create_bucket(Bucket="my-bucket") + + buckets = [b["Name"] for b in s3.list_buckets()["Buckets"]] + assert "my-bucket" in buckets +``` + +## Pytest fixture + +Use a session-scoped fixture so the container starts once and is shared across all tests in the suite. + +```python +import pytest +import boto3 +from testcontainers_floci import FlociContainer + + +@pytest.fixture(scope="session") +def floci(): + with FlociContainer() as container: + yield container + + +@pytest.fixture(scope="session") +def s3_client(floci): + return boto3.client( + "s3", + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + + +def test_create_bucket(s3_client): + s3_client.create_bucket(Bucket="my-bucket") + buckets = [b["Name"] for b in s3_client.list_buckets()["Buckets"]] + assert "my-bucket" in buckets + + +def test_upload_object(s3_client): + s3_client.create_bucket(Bucket="uploads") + s3_client.put_object(Bucket="uploads", Key="hello.txt", Body=b"hello floci") + body = s3_client.get_object(Bucket="uploads", Key="hello.txt")["Body"].read() + assert body == b"hello floci" +``` + +## SQS example + +```python +import pytest +import boto3 +import json +from testcontainers_floci import FlociContainer + + +@pytest.fixture(scope="session") +def floci(): + with FlociContainer() as container: + yield container + + +@pytest.fixture(scope="session") +def sqs_client(floci): + return boto3.client( + "sqs", + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + + +def test_send_and_receive_message(sqs_client): + queue_url = sqs_client.create_queue(QueueName="orders")["QueueUrl"] + + sqs_client.send_message( + QueueUrl=queue_url, + MessageBody=json.dumps({"event": "order.placed"}), + ) + + response = sqs_client.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1) + messages = response.get("Messages", []) + + assert len(messages) == 1 + assert json.loads(messages[0]["Body"])["event"] == "order.placed" +``` + +## DynamoDB example + +```python +import pytest +import boto3 +from testcontainers_floci import FlociContainer + + +@pytest.fixture(scope="session") +def floci(): + with FlociContainer() as container: + yield container + + +@pytest.fixture(scope="session") +def dynamo_client(floci): + return boto3.client( + "dynamodb", + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + + +def test_put_and_get_item(dynamo_client): + dynamo_client.create_table( + TableName="Orders", + AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}], + KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST", + ) + + dynamo_client.put_item( + TableName="Orders", + Item={"id": {"S": "order-1"}, "status": {"S": "placed"}}, + ) + + item = dynamo_client.get_item( + TableName="Orders", + Key={"id": {"S": "order-1"}}, + )["Item"] + + assert item["status"]["S"] == "placed" +``` + +## Secrets Manager example + +```python +def test_create_and_get_secret(floci): + sm = boto3.client( + "secretsmanager", + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + + sm.create_secret(Name="db/password", SecretString="supersecret") + value = sm.get_secret_value(SecretId="db/password")["SecretString"] + assert value == "supersecret" +``` + +## conftest.py pattern + +Place shared fixtures in `conftest.py` so every test module picks them up automatically: + +```python +# conftest.py +import pytest +import boto3 +from testcontainers_floci import FlociContainer + + +@pytest.fixture(scope="session") +def floci(): + with FlociContainer() as container: + yield container + + +@pytest.fixture(scope="session") +def aws_clients(floci): + kwargs = dict( + endpoint_url=floci.get_endpoint(), + region_name=floci.get_region(), + aws_access_key_id=floci.get_access_key(), + aws_secret_access_key=floci.get_secret_key(), + ) + return { + "s3": boto3.client("s3", **kwargs), + "sqs": boto3.client("sqs", **kwargs), + "dynamodb": boto3.client("dynamodb", **kwargs), + "secretsmanager": boto3.client("secretsmanager", **kwargs), + } +``` + +```python +# test_my_service.py +def test_something(aws_clients): + s3 = aws_clients["s3"] + s3.create_bucket(Bucket="test") + # ... +``` + +## Source and changelog + +[github.com/floci-io/testcontainers-floci-python](https://github.com/floci-io/testcontainers-floci-python) diff --git a/mkdocs.yml b/mkdocs.yml index 40be9cb39f..05332d5c1c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -100,4 +100,10 @@ nav: - EC2: services/ec2.md - AppConfig: services/appconfig.md - Bedrock Runtime: services/bedrock-runtime.md + - Testcontainers: + - Overview: testcontainers/index.md + - Java: testcontainers/java.md + - Node.js / TypeScript: testcontainers/nodejs.md + - Python: testcontainers/python.md + - Go: testcontainers/go.md - Contributing: contributing.md \ No newline at end of file