Skip to content

Instantly share code, notes, and snippets.

@tombasche
Last active August 18, 2021 16:24
Show Gist options
  • Save tombasche/92d4db5bd13cfb6383b187957f6c3905 to your computer and use it in GitHub Desktop.
Save tombasche/92d4db5bd13cfb6383b187957f6c3905 to your computer and use it in GitHub Desktop.
Sample test using localstack + testcontainers in Spring
package com.myapplication.email
import arrow.core.Either
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.testcontainers.containers.localstack.LocalStackContainer
import org.testcontainers.utility.DockerImageName
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.ses.SesClient
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class EmailClientTests {
val email: Email = Email(
to = "[email protected]",
subject = "Hi there!",
body = "This is an email about some stuff",
from = "[email protected]"
)
@Test
fun `send an email`() {
when (EmailClient(awsTestSesClient()).send(email)) {
is Either.Left -> fail("Email failed to send")
is Either.Right -> return
}
}
@Test
fun `an email sending failure is handled`() {
when (EmailClient(unauthenticatedAwsSesClient()).send(email)) {
is Either.Left -> return
is Either.Right -> fail("Email should not have been sent")
}
}
fun awsTestSesClient(): SesClient = SesClient
.builder()
.endpointOverride(localstack.getEndpointOverride(LocalStackContainer.Service.S3))
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create(
localstack.accessKey, localstack.secretKey
)
)
)
.region(Region.of(localstack.region))
.build()
fun unauthenticatedAwsSesClient(): SesClient = SesClient
.builder()
.region(Region.of(localstack.region))
.build()
companion object {
private val localstack = LocalStackContainer(DockerImageName.parse("localstack/localstack:0.11.3"))
.withServices(LocalStackContainer.Service.SES)
.withEnv("AWS_ACCESS_KEY_ID", "accesskey")
.withEnv("AWS_SECRET_ACCESS_KEY", "secretkey")
init {
localstack.start()
verifyEmail()
}
private fun verifyEmail() {
val command = "aws ses verify-email-identity --email-address [email protected] --region us-east-1 --endpoint-url http://localhost:4566"
val result = localstack.execInContainer(*command.split(" ").toTypedArray())
if (result.exitCode != 0) {
throw Exception(result.stderr)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment