Travis CI - golang
What is Continuous Integration (CI) ?
Continuous Integration is the practice of merging in small code changes frequently - rather than merging in a large change at the end of a development cycle. The goal is to build healthier software by developing and testing in smaller increments.
简而言之,持续集成(CI)让我们频繁地将小的修改合并到主干分支上,而不是在开发周期结束时进行大的更改。这样能够让我们通过更小的增量开发和测试来构建更健康的软件。
请确保你已经安装并了解了:
-
git相关知识 -
golang编程环境(可以参考我的另一篇博客:服务计算 | Golang 入门与配置)
Git repostiy
- 在 Github 上创建一个仓库 “golang-test”
- 创建后它会告诉你在
$GOPATH/src/github.com/your-git-account-name/repo-name目录下执行下面的命令:(照着一句一句输入即可,可别复制我的!)
echo "# golang-test" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/xxx/golang-test.git
git push -u origin master
- 上面语句的意思就是创建了一个 README.md 并把它 push 到远程仓库即 GitHub 上
Go test
首先我们先看看如何编写一个 golang 测试用例:(在 golang-test 下即上面的目录)
- 创建 hello.go,并编写以下代码:
package test
func SayHello1(user string) string {
return "Hello, " + user
}
func SayHello2(user string) string {
return "Hello," + user
}
- 创建 hello_test.go,并编写以下测试用例函数:
package test
import "testing"
func TestSayHello1(t *testing.T) {
user := "777"
if str := SayHello1(user); str != "Hello, 777" {
t.Error("SayHello1 is failed!")
} else {
t.Log("SayHello1 is ok!")
}
}
func TestSayHello2(t *testing.T) {
user := "777"
if str := SayHello2(user); str != "Hello, 777" {
t.Error("SayHello2 is failed!")
} else {
t.Log("SayHello2 is ok!")
}
}
- 在项目目录下执行
go test -v,你会得到如下信息:
Sandra-MBP:test sandra$ go test -v
=== RUN TestSayHello1
--- PASS: TestSayHello1 (0.00s)
hello_test.go:10: SayHello1 is ok!
=== RUN TestSayHello2
--- FAIL: TestSayHello2 (0.00s)
hello_test.go:17: SayHello2 is failed!
FAIL
exit status 1
FAIL github.com/7cthunder/test 0.005s
可以看到,SayHello2函数因为少了一个空格,所以失败了!
Travis CI
还记得一开始说的 CI 吗,即便已经有了 gotest 这么好用测试工具,但是我们还是希望能够让开发过程更具自动化!
As a continuous integration platform, Travis CI supports your development process by automatically building and testing code changes, providing immediate feedback on the success of the change. Travis CI can also automate other parts of your development process by managing deployments and notifications.
Travis CI 可以帮到我们,下面看看如何实现:
- 打开 https://www.travis-ci.org,使用你的 Github 账号登录后它会同步你的仓库
- 找到你的 golang-test 仓库并**它
- 在仓库的根目录添加
.travis.yml文件,如下:
language: go
go:
- master # get the latest version from source
- 使用
git提交修改 - 接着点击 travis 上 golang-test,可以查看触发的构建过程:
- 还记得上面使用
go test -v失败时编写的用例吗?我们没有修改所以必定是 FAIL 啦!让我们回想一下做了什么?只是编写了一个.travis.yml,然后就自动触发了 travis 的构建,是不是意味着我们每次提交都要重写一个呢,非也,触发 travis 的是仓库的变动!所以下面我们试试将 hello.go 中的SayHello2修改正确并提交,看看会发生什么:
- 事实上,Travis CI 就是用一个 Linux 容器来构建我们的项目,然后运行我们的测试脚本
小结
以上就是我们使用 Travis CI 来达成自动化持续集成测试的实例啦!
更多关于构建脚本 .travis.yml 的配置还请移步 Building a Go Project