”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 通过 testcontainers-go 和 docker-compose 来利用您的测试套件

通过 testcontainers-go 和 docker-compose 来利用您的测试套件

发布于2024-11-02
浏览:251

Leverage Your Test Suite With testcontainers-go & docker-compose

Welcome back, folks! Today, we will cover the end-to-end tests in an intriguing blog post. If you've never written these kinds of tests or if you strive to improve them, keep reading as I'll walk you through this exciting journey. By the end of the article, you'll know how to empower the usage of the testcontainers-go package to let your test suite shine.

The Premise ?

Before moving ahead, let's set the boundaries for this blog post since we will cover several concepts, tools, and techniques.

The Survival List ?️

Since we'll touch on several topics throughout the rest of the blog post, I feel it's a good idea to put them together here.

The tools I present throughout this blog post are a mix of tools I know well and some I used for the first time. Try not to use these tools without thinking, but evaluate them based on your scenario.

We're going to rely on:

  • The Go programming language
  • Docker
  • The testcontainers-go package with the compose module
  • The ginkgo testing framework and the gomega assertion package

To avoid bloating the reading, I won't cover every aspect and facet of the topics presented here. I will put the relevant documentation URLs where needed.

The Scenario ?

Let's assume we need to write end-to-end tests on a project we don't own. In my case, I want to write end-to-end tests on a project written with the Java programming language. Since I didn't know how to code in Java, my testing option was only end-to-end tests. The service I had to test was a set of REST APIs. The solution has been obvious: exercise the endpoints by issuing HTTP requests.

It allows testing the exposed features like a black box. We only have to deal with the public surface: what we send to the server and what we get back from it. Nothing more, nothing less.

We care about the api/accounts endpoint that lists the bank accounts in our database (a MySQL instance). We're going to issue these two requests:

HTTP Method Address Expected Status Code
GET api/accounts?iban=IT10474608000005006107XXXXX 200 StatusOK
GET api/accounts?iban=abc 400 StatusBadRequest

Now, you should have a clearer idea of our goal. So, let's jump into the test code.

Let's Have Fun ?

In this section, I present all the relevant code we need to write for the dreaded end-to-end tests.

The docker-compose.yml file

Since we don't bother with the source code, the starting point is the docker-compose.yml file. The relevant code is:


services:
  mysqldb:
    image: "mysql:8.0"
    container_name: mysqldb
    restart: always
    ports:
      - 3307:3306
    networks:
      - springapimysql-net
    environment:
      MYSQL_DATABASE: transfers_db
      MYSQL_USER: bulk_user
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s

  api_service:
    build: .
    container_name: api_service
    restart: always
    ports:
      - 8080:8080
    networks:
      - springapimysql-net
    environment:
      - spring.datasource.url=jdbc:mysql://mysqldb:3306/transfers_db
      - spring.datasource.username=bulk_user
      - spring.datasource.password=root
    depends_on:
      mysqldb:
        condition: service_healthy
    volumes:
      - .m2:/root/.m2

networks:
  springapimysql-net:



The file content is pretty straightforward. We can summarize the things defined in the following list:

  • The mysqldb service doesn't deserve any further explanations
  • The api_service service is the system we're testing
  • The springapimysql-net network hosts the two services defined above

For further Docker Compose reference, you may have a look here. Now, let's see the end-to-end test code.

The ginkgo Testing Framework

The ginkgo testing framework helps us in building the test suite. It's entirely written in Go. Furthermore, it provides a CLI utility to set up and run the tests. Since we will use it later, let's download it from here. You can download it in two ways:

  1. By using the go install command (if you've installed Go on your system)
  2. By downloading the compiled binary (useful if you don't have Go installed on your system)

To check whether you have a working utility on your machine, you can run the command ginkgo version (at the time of writing, I have the version 2.20.2).

Please note that the ginkgo command is not mandatory to run the tests. You can still run the tests without this utility by sticking to the go test command.

However, I strongly suggest downloading it since we will use it to generate some boilerplate code.

Lay the Foundation with Ginkgo

Located in the root directory, let's create a folder called end2end to host our tests. Within that folder, initialize a Go module by issuing the command go mod init path/to/your/module.

Now, it's time to run the command ginkgo bootstrap. It should generate a new file called end2end_suite_test.go. This file triggers the test suite we'll define in a bit.

This approach is similar to the one with the testify/suite package. It enforces the code modularity and robustness since the definition and running phases are separated.

Now, let's add the tests to our suite. To generate the file where our tests will live, run another ginkgo command: ginkgo generate accounts. This time, the file accounts_test.go pops out. For now, let's leave it as is and switch to the terminal. We fix the missing packages by running the Go command go mod tidy to download the missing dependencies locally on our machine.

The end2end_suite_test.go file

Let's start with the entry point of the test suite. The content of the file looks neat:


//go:build integration

package end2end

import (
 "testing"

 . "github.com/onsi/ginkgo/v2"
 . "github.com/onsi/gomega"
)

func TestEnd2End(t *testing.T) {
 RegisterFailHandler(Fail)
 RunSpecs(t, "End2End Suite")
}



The only unusual thing might be the dot-import within the import section. You can read more about it in the documentation here.

Whoop! A wild testcontainers appears ?

At some points, we need some magic to get to the next testing level. It happened to be testcontainers-go. For the sake of this demo, we use the compose module (for further reference, please refer to here).

This tool can run the compose file we saw earlier and execute the end-to-end tests against the running containers.

This is an extract of the testcontainers-go capabilities. If you want to learn more, please refer to the doc or reach out. I'll be happy to walk you through its stunning features.

This package allows running the end-to-end suite with a single command. It's a more consistent and atomic way to run these tests. It allows me to:

  1. Start the containers before the suite
  2. Run the tests relying on these containers
  3. Teardown of containers after the suite and cleanup of the resources used

Having the code written this way can help you avoid the hassle of dealing with docker cli commands and makefiles.

The accounts_test.go file

Now, let's look at the code where our tests live.


//go:build integration

package end2end

import (
 "context"
 "net/http"
 "os"

 . "github.com/onsi/ginkgo/v2"
 . "github.com/onsi/gomega"
 tc "github.com/testcontainers/testcontainers-go/modules/compose"
 "github.com/testcontainers/testcontainers-go/wait"
)

var _ = Describe("accounts", Ordered, func() {
 BeforeAll(func() {
 os.Setenv("TESTCONTAINERS_RYUK_DISABLED", "true")
 composeReq, err := tc.NewDockerComposeWith(tc.WithStackFiles("../docker-compose.yml"))
  Expect(err).Should(BeNil())
  DeferCleanup(func() {
   Expect(composeReq.Down(context.Background(), tc.RemoveOrphans(true), tc.RemoveImagesLocal)).Should(BeNil())
  })
 ctx, cancel := context.WithCancel(context.Background())
  DeferCleanup(cancel)
 composeErr := composeReq.
   WaitForService("api_service", wait.ForListeningPort("8080/tcp")).
   Up(ctx, tc.Wait(true))
  Expect(composeErr).Should(BeNil())
 })

 Describe("retrieving accounts", func() {
  Context("HTTP request is valid", func() {
   It("return accounts", func() {
 client := http.Client{}
 r, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/accounts?iban=IT10474608000005006107XXXXX", nil)
 res, err := client.Do(r)
    Expect(err).Should(BeNil())
    Expect(res).To(HaveHTTPStatus(http.StatusOK))
   })
  })

  Context("HTTP request is NOT valid", func() {
   It("err with invalid IBAN", func() {
 client := http.Client{}
 r, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/accounts?iban=abcd", nil)
    Expect(err).Should(BeNil())
 res, err := client.Do(r)
    Expect(err).Should(BeNil())
    Expect(res).To(HaveHTTPStatus(http.StatusBadRequest))
   })
  })
 })
})



At first glimpse, it might seem hard to digest. To keep things easier, let's break it down into smaller parts.

The Describe container node

The Describe container node is nothing but a wrapper to hold the relevant code for our suite. Everything must live within it. It's part of the scaffolded code: var _ = Describe("accounts", Ordered, func() {}. Within the {}, you should put all of the relevant code. To enforce the usage of setup nodes (like BeforeAll), we must define the Describe container as Ordered.

Do not worry if you forgot to add it since the Go compiler will complain.

Let's move on.

The BeforeAll setup node

This node allows us to extract the common setup logic. This code portion executes once and before the tests within the suite. Let's recap what's doing:

  • Set the environment variable TESTCONTAINERS_RYUK_DISABLED to true. You can learn about the configuration here. If you're curious about Ryuk, you may want to look at this
  • Create a *tc.DockerCompose variable based on the docker-compose.yml file we provided
  • Defer the function invocation to terminate containers and cleanup of the resources
  • Start the compose stack and wait for the container called api_service to be up and ready to listen on the 8080/tcp port

I simplified the test code since I don't want to make this blog post even longer ?.

Finally, the tests! ?

The test functions live within a Describe Container Node. You can find out how ginkgo handles the test specifications by referring to here. The Describe node allows you to group and organize tests based on their scope. You can nest this node inside other Describe ones.

The more you nest the Describe node, the more you narrow the test scope.

Then, we have the Context Container Node that qualifies the parent Describe. It qualifies the circumstances under which the tests are valid. Finally, we have the It section, the Spec Subject. It's the actual test we're performing and is the leaf level of the hierarchy tree. The test code is self-explanatory, so I'll jump to the section where we run the tests.

3, 2, 1... ?

Congrats ? We managed to get here. Now, we only miss the test-running operations. In the blink of an eye, we'll get our test execution report printed onto the terminal.

Let's switch to the terminal and run the command ginkgo --tags=integration -v. After a while, you'll see the output printed on the terminal.

Closing Notes ?

I know there are a lot of things condensed into this blog post. My goal has been to provide insights and approaches on how to write a good testing suite. You may want to adapt the presented tools, packages, and techniques to other kinds of tests or use cases.

Before leaving, I'd like to underline another beauty of the compose module of the testcontainers-go package.

If you stick to the configuration I provided, you're sure to use the latest Docker images, and you can avoid hours of troubleshooting due to outdated image usage. It's analogous to the command docker compose build --no-cache && docker compose up. You'll thank me ?

Thanks for the attention, folks! If you've got any questions, doubts, feedback, or comments, I'm available to listen and speak together. If you want me to cover some specific concepts, please reach me. Until the next time, take care and see you ?

版本声明 本文转载于:https://dev.to/ossan/leverage-your-test-suite-with-testcontainers-go-docker-compose-502e?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 何时将成功回调函数与 jQuery Ajax 调用分离?
    何时将成功回调函数与 jQuery Ajax 调用分离?
    从 jQuery Ajax 调用解耦成功回调函数使用 jQuery ajax 从服务器检索数据时,通常的做法是定义成功.ajax() 块中的回调函数。这将回调处理与 AJAX 调用紧密结合在一起,限制了灵活性和可重用性。要在 .ajax() 块之外定义成功回调,通常需要声明一个用于存储返回数据的变量...
    编程 发布于2024-11-03
  • 极简设计初学者指南
    极简设计初学者指南
    我一直是干净和简单的倡导者——这是我的思维最清晰的方式。然而,就像生活中的大多数任务一样,不同的工作有不同的工具,设计也是如此。在这篇文章中,我将分享我发现的极简设计实践,这些实践有助于创建干净简单的网站、模板和图形——在有限的空间内传达必要的内容。 简单可能比复杂更难:你必须努力让你的思维清晰,使...
    编程 发布于2024-11-03
  • 了解 React 应用程序中的渲染和重新渲染:它们如何工作以及如何优化它们
    了解 React 应用程序中的渲染和重新渲染:它们如何工作以及如何优化它们
    当我们在 React 中创建应用程序时,我们经常会遇到术语渲染和重新渲染组件。虽然乍一看这似乎很简单,但当涉及不同的状态管理系统(如 useState、Redux)或当我们插入生命周期钩子(如 useEffect)时,事情会变得有趣。如果您希望您的应用程序快速高效,那么了解这些流程是关键。 ...
    编程 发布于2024-11-03
  • 如何在 Node.js 中将 JSON 文件读入服务器内存?
    如何在 Node.js 中将 JSON 文件读入服务器内存?
    在 Node.js 中将 JSON 文件读入服务器内存为了增强服务器端代码性能,您可能需要读取 JSON 对象从文件到内存以便快速访问。以下是在 Node.js 中实现此目的的方法:同步方法:对于同步文件读取,请利用 fs(文件系统)中的 readFileSync() 方法模块。此方法将文件内容作为...
    编程 发布于2024-11-03
  • 人工智能可以提供帮助
    人工智能可以提供帮助
    我刚刚意识到人工智能对开发人员有很大帮助。它不会很快接管我们的工作,因为它仍然很愚蠢,但是,如果你像我一样正在学习编程,可以用作一个很好的工具。 我要求 ChatGpt 为我准备 50 个项目来帮助我掌握 JavaScript,它带来了令人惊叹的项目,我相信当我完成这些项目时,这些项目将使我成为 J...
    编程 发布于2024-11-03
  • Shadcn UI 套件 - 管理仪表板和网站模板
    Shadcn UI 套件 - 管理仪表板和网站模板
    Shadcn UI 套件是预先设计的多功能仪表板、网站模板和组件的综合集合。它超越了 Shadcn 的标准产品,为那些不仅仅需要基础知识的人提供更先进的设计和功能。 独特的仪表板模板 Shadcn UI Kit 提供了各种精心制作的仪表板模板。目前,有 7 个仪表板模板可用,随着时间...
    编程 发布于2024-11-03
  • 如何使用正则表达式捕获多行文本块?
    如何使用正则表达式捕获多行文本块?
    匹配多行文本块的正则表达式匹配跨多行的文本可能会给正则表达式构造带来挑战。考虑以下示例文本:some Varying TEXT DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF [more of the above, ending with a newline] [yep, t...
    编程 发布于2024-11-03
  • 软件开发中结构良好的日志的力量
    软件开发中结构良好的日志的力量
    日志是了解应用程序底层发生的情况的关键。 简单地使用 console.log 打印所有值并不是最有效的日志记录方法。日志的用途不仅仅是显示数据,它们还可以帮助您诊断问题、跟踪系统行为以及了解与外部 API 或服务的交互。在您的应用程序在没有用户界面的情况下运行的情况下,例如在系统之间处理和传输数据的...
    编程 发布于2024-11-03
  • 如何在单个命令行命令中执行多行Python语句?
    如何在单个命令行命令中执行多行Python语句?
    在单个命令行命令中执行多行Python语句Python -c 选项允许单行循环执行,但在命令中导入模块可能会导致语法错误。要解决此问题,请考虑以下解决方案:使用 Echo 和管道:echo -e "import sys\nfor r in range(10): print 'rob'&qu...
    编程 发布于2024-11-03
  • 查找数组/列表中的重复元素
    查找数组/列表中的重复元素
    给定一个整数数组,找到所有重复的元素。 例子: 输入:[1,2,3,4,3,2,5] 输出:[2, 3] 暗示: 您可以使用 HashSet 来跟踪您已经看到的元素。如果某个元素已在集合中,则它是重复的。为了保留顺序,请使用 LinkedHashSet 来存储重复项。 使用 HashSet 的 Ja...
    编程 发布于2024-11-03
  • JavaScript 回调何时异步?
    JavaScript 回调何时异步?
    JavaScript 回调:是否异步?JavaScript 回调并非普遍异步。在某些场景下,例如您提供的 addOne 和 simpleMap 函数的示例,代码会同步运行。浏览器中的异步 JavaScript基于回调的 AJAX 函数jQuery 中通常是异步的,因为它们涉及 XHR (XMLHtt...
    编程 发布于2024-11-03
  • 以下是根据您提供的文章内容生成的英文问答类标题:

Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?
    以下是根据您提供的文章内容生成的英文问答类标题: Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?
    char、signed char 和 unsigned char 之间的行为差​​异下面的代码可以成功编译,但 char 的行为与整数类型不同。cout << getIsTrue< isX<int8>::ikIsX >() << endl; cou...
    编程 发布于2024-11-03
  • 如何在动态生成的下拉框中设置默认选择?
    如何在动态生成的下拉框中设置默认选择?
    确定下拉框中选定的项目使用 标签创建下拉列表时,您可以可能会遇到需要将特定选项设置为默认选择的情况。这在预填写表单或允许用户编辑其设置时特别有用。在您呈现的场景中, 标记是使用 PHP 动态生成的,并且您希望根据值存储在数据库中。实现此目的的方法如下:设置选定的属性要在下拉框中设置选定的项目,您需...
    编程 发布于2024-11-03
  • Tailwind CSS:自定义配置
    Tailwind CSS:自定义配置
    介绍 Tailwind CSS 是一种流行的开源 CSS 框架,近年来在 Web 开发人员中广受欢迎。它提供了一种独特的可定制方法来创建美观且现代的用户界面。 Tailwind CSS 区别于其他 CSS 框架的关键功能之一是它的可定制配置。在这篇文章中,我们将讨论 Tailwin...
    编程 发布于2024-11-03
  • 使用 jQuery
    使用 jQuery
    什么是 jQuery? jQuery 是一个快速的 Javascript 库,其功能齐全,旨在简化 HTML 文档遍历、操作、事件处理和动画等任务。 “少写多做” MDN 状态: jQuery使得编写多行代码和tsk变得更加简洁,甚至一行代码.. 使用 jQuery 处理事件 jQuery 的另一个...
    编程 发布于2024-11-03

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3