如何使用docker-compose快速还原新数据库以进行集成测试? [英] How to use docker-compose to restore fresh databases quickly for integration tests?

查看:167
本文介绍了如何使用docker-compose快速还原新数据库以进行集成测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用每次运行时处于已知状态的数据库运行集成和端到端测试,以使测试独立且可重复。一种简单的方法是使用docker-compose创建一个数据库容器,该容器每次都从转储文件中加载方案和数据。但是,这对于每次测试都还原数据库来说太慢了。

I would like to run integration and end-to-end tests with a database in a known state for each run, to make the tests independent and repeatable. An easy way of doing this is to use docker-compose to create a database container which loads the scheme and data from a dump file each time. However, this is far too slow to restore the database for every test.

一种更好的方法似乎是在docker容器或卷中还原一次数据库,然后将容器/卷数据库文件夹复制(装入?)到测试将要使用的数据库容器中,并让每个测试重新复制/装入容器/卷,使其新鲜。

A better way seems to be to restore the database once in a docker container or volume, and then copy (mount?) the container/volume database folder into the database container that the test will use, and have each test re-copy/mount the container/volume so that it is fresh.

但是,我不确定用docker-compose做到这一点的最佳方法是什么。谁能提供一个最小的例子或解释如何做到这一点?

However, I am not sure what the best way to do this with docker-compose is. Could anyone provide a minimal example or explanation as to how to do this?

推荐答案

您可以使用以下主机目录启动数据库:其基础数据存储。如果这样做,则可以创建该目录的tar文件,并在每次测试运行时重新解压缩该文件。

You can start the database using a host directory for its underlying data store. If you do this, then you can create a tar file of the directory, and untar it anew for each test run.

mkdir mysql
docker run -d -p 3306:3306 -v ./mysql:/var/lib/mysql --name mysql mysql
mysql -h 127.0.0.1 < dump.sql
docker stop mysql
docker rm mysql
tar czf mysql.tar.gz mysql



rm -rf mysql
tar xzf mysql.tar.gz
docker run -d -p 3306:3306 -v ./mysql:/var/lib/mysql --name mysql mysql
MYSQL_HOST=127.0.0.1 ./integration_test
docker stop mysql
docker rm mysql

您必须分别分发数据转储(如果您另外使用AWS,则S3存储桶是一个不错的选择),但由于您始终可以从数据库转储中重新创建测试数据,因此它并不是特别珍贵,并且不需要跟踪其版本历史记录或尝试将其保留在源代码管理中。

You'd have to distribute the data dump separately (if you otherwise use AWS, an S3 bucket is a good place for it) but since it's "just" test data that you can always recreate from a database dump, it's not especially precious and you don't need to track its version history or attempt to keep it in source control.

这篇关于如何使用docker-compose快速还原新数据库以进行集成测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆