什么是持续集成?(continuous integration)
In software engineering, continuous integration (CI) is the practice of merging all developer working copies to a shared mainline several times a day
持续集成指的是,频繁地(一天多次)将代码集成到主干。
它的好处主要有两个。
(1)快速发现错误。每完成一点更新,就集成到主干,可以快速发现错误,定位错误也比较容易。
(2)防止分支大幅偏离主干。如果不是经常集成,主干又在不断更新,会导致以后集成的难度变大,甚至难以集成。
持续集成的目的,就是让产品可以快速迭代,同时还能保持高质量。它的核心措施是,代码集成到主干之前,必须通过自动化测试。只要有一个测试用例失败,就不能集成。
Martin Fowler说过,“持续集成并不能消除Bug,而是让它们非常容易发现和改正。”
以上内容来源于:http://www.ruanyifeng.com/blog/2015/09/continuous-integration.html
Travis CI集成化工具使用
Travis CI提供持续集成服务,它绑定Github上面的项目,只要有新的代码提交(push/pull request)就会自动抓取,然后提供运行运行环境,执行测试,完成构建。
创建仓库
在我们的Github中,创建一个名为TravisCI
的仓库,然后clone
到本地,添加如下代码:
- hello文件夹
// hello.go
package hello
func helloGolang() string {
return "helloGolang"
}
// hello_test.go
package hello
import (
"testing"
)
func TestHelloGolang(t *testing.T) {
if helloGolang() == "HelloGolang" {
t.Log("测试通过")
} else {
t.Error("测试失败")
}
}
- .travis.yml
language: go
branches:
only:
- master #指定监听的分支
上述代码中,我们书写了一个简单的hello包,并为其添加了测试程序,此时我们既可以在TravisCI
项目中执行go test -v ./...
来运行测试helloGolang
的正确性:
PS E:\mygo\src\github.com\liuyh73\TravisCI> go test -v ./...
=== RUN TestHelloGolang
--- FAIL: TestHelloGolang (0.00s)
hello_test.go:11: 测试失败
FAIL
FAIL github.com/liuyh73/TravisCI/hello 0.174s
监听仓库
- 首先,我们访问Travis CI官方网站。使用Github账号登录。然后Travis会自行列出我们Github上的所有仓库,以及我们所属于的组织。
- 然后,我们可以点击进入
TravisCI
,点击Activate repository
即可激活该仓库,此时Travis可以监听该仓库的所有变化。
- 上述过程中,我已经监听了该仓库并做了一定的提交。
提交该仓库
执行git命令将该仓库推送到远程仓库,此时,Travis CI工具检测到仓库变化,然后查找到.travis.yml
文件,之后根据.travis.yml
配置文件来进行检测。
- 正在构建
- 持续集成发生错误
- go test测试失败
由上图可知,该持续集成工具对包内的所有_test.go
都进行了测试,并且,我们的此次提交go test
并未通过。 - 修改hello_test.go
func TestHelloGolang(t *testing.T) {
if helloGolang() == "helloGolang" {
t.Log("测试通过")
} else {
t.Error("测试失败")
}
}
- 再次将修改提交到远程仓库
由此可知,此次集成成功,并未引发测试错误。
.travis.yml相关配置说明
install 字段:安装依赖
install: ./install-dependencies.sh # 运行脚本安装
install:
- command1 # 上面代码中,如果command1失败了,整个构建就会停下来,不再往下进行。
- command2
install: true #如果不需要安装,即跳过安装阶段,就直接设为true。
script 字段:用来指定构建或测试脚本
script: command
# 如果有多个脚本,可以写成下面的形式。
script:
- command1 # 注意,script与install不一样,如果command1失败,command2会继续执行。但是,整个构建阶段的状态是失败。
- command2
# 如果command2只有在command1成功后才能执行,就要写成下面这样。
script: command1 && command2
Travis 的7个钩子:
before_install:install 阶段之前执行
before_script:script 阶段之前执行
after_failure:script 阶段失败时执行
after_success:script 阶段成功时执行
before_deploy:deploy 步骤之前执行
after_deploy:deploy 步骤之后执行
after_script:script 阶段之后执行
Travis CI完整的生命周期,执行顺序由上到下:
before_install
install
before_script
script
aftersuccess or afterfailure
[OPTIONAL] before_deploy
[OPTIONAL] deploy
[OPTIONAL] after_deploy
after_script