# testing-with-docker **Repository Path**: joil-z/testing-with-docker ## Basic Information - **Project Name**: testing-with-docker - **Description**: 在go项目中使用docker运行测试的工具 - **Primary Language**: Go - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2023-02-03 - **Last Updated**: 2023-03-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # testing-with-docker #### 介绍 方便在go项目中使用Docker运行测试。可以使用本地Docker,也可以使用远程Docker。 #### 安装教程 1. 拉取项目 ```bash git clone https://gitee.com/joil-z/testing-with-docker.git ``` #### 使用说明 1. 更新依赖、拉取模块 ```bash cd testing-with-docker go mod tidy ``` 2. 修改配置文件 配置文件示例: ./configs/testing_config.go ```go package configs const ( // DaemonURL ssh://@ URL requires Docker 18.09 or later on the remote host. // If DaemonURL != "ssh://..." use local Docker DaemonURL = "ssh://joil@192.168.1.2" // 使用本地Docker设为空字符串即可 DefaultMysqlDNS = "root:123456@tcp(192.168.1.2:13306)/%s?charset=utf8mb4&parseTime=True&loc=Local" // 携带测试数据的mysql的地址 DefaultRedisDNS = "192.168.1.2:16379" // 携带测试数据的redis地址 DefaultMongoURI = "mongodb://root:123456@192.168.1.2:27018" // 携带测试数据的mongodb的地址 ) ``` 3. 在测试代码中 在测试代码(`xx_test.go`)中添加`TestMain()`函数。关于该函数的作用可以自行查询。 mongo: ```go import mongotesting "testing-with-docker/mongo/testing" func TestMain(m *testing.M) { os.Exit(mongotesting.RunWithMongoInDocker(m)) } ``` mysql: ```go import mysqltesting "testing-with-docker/mysql/testing" func TestMain(m *testing.M) { os.Exit(mysqltesting.RunWithMysqlInDocker(m, databaseName)) // 这里可以改写成在配置文件中固定databaseName } ``` redis: ```go import redistesting "testing-with-docker/redis/testing" func TestMain(m *testing.M) { os.Exit(redistesting.RunWithRedisInDocker(m)) } ``` 4. 运行测试 ```bash cd testing-with-docker go test -v ./examples/mongo # 运行mongo测试示例 go test -v ./examples/mysql # 运行mysql测试示例 go test -v ./examples/redis # 运行redis测试示例 ``` #### 注意 ##### 1. 使用远程Docker 如果要连接远程的Docker: 1. 开放`22`端口 2. 配置ssh免密钥登录 3. Docker的版本 >= 18.09 ###### 1.1 配置ssh免密钥登录例子(在Linux上) 1. 生成公钥、私钥 ```bash #生成id_rsa id_rsa.pub 一个公钥一个私钥 ssh-keygen -t rsa -b 4096 # 设置密码默认为空,再次输入也为空 ``` 2. 将PC端的公钥文件`id_rsa.pub`的内容上传到目标服务器`~/.ssh/authorized_keys`中 ```bash # 写入 cat id_rsa.pub >> ~/.ssh/authorized_keys ``` 服务器如果报错不存在`~/.ssh/authorized_keys`,新建一个`.ssh`文件夹即可。 ```bash mkdir ~/.ssh ``` 3. 设置权限 ```bash chmod 600 ~/.ssh/authorized_keys ``` ###### 1.2 填写配置 在配置文件中填写`DaemonURL`。格式为: ```go DaemonURL = "ssh://@" // "ssh://joil@192.168.1.2" // DaemonURL = "" // 使用本地docker设为空字符串即可 ```