背景
隨著區(qū)塊鏈的這2年的快速發(fā)展,Go語言和針對GO語言測試工具也越來越完善,特別是Go語言的靜態(tài)代碼掃描工具完善,使GO語言和JAVA語言一樣可以靜態(tài)代碼自動掃描測試。說GO語言靜態(tài)代碼測試之前先說說靜態(tài)代碼測試。
靜態(tài)代碼測試
靜態(tài)代碼測試在不執(zhí)行計算機(jī)程序的條件下,對源代碼進(jìn)行分析,找出代碼缺陷。
- 靜態(tài)代碼測試檢測類型:死鎖,空指針,資源泄露,緩沖區(qū)溢出,安全漏洞,競態(tài)條件。
- 靜態(tài)代碼測試優(yōu)點:
1、能夠檢測所有的代碼級別的可執(zhí)行路徑組合,快速,準(zhǔn)確。
2、直接面向源碼,分析多種問題
3、在研發(fā)階段開始找到并修復(fù)多種問題,節(jié)省大量時間/人力成本 - 靜態(tài)代碼測試缺點
1、高誤報率:目前靜態(tài)分析產(chǎn)品的誤報率普遍在30%以上。
2、缺陷種類較少,找到的問題級別不高:多數(shù)為代碼規(guī)范或低級缺陷,3、非實際Bug – 如命名規(guī)范、類定義規(guī)范,最佳實踐.....
GO語言靜態(tài)掃描測試工具
目前Go語言主流靜態(tài)代碼掃描測試工具主要是GoReporte和sonar集成的sonar-golang插件
GoReporte: 一個用于執(zhí)行靜態(tài)分析,單元測試,代碼審查并生成代碼質(zhì)量報告的Golang工具,這是一個運行一整套靜態(tài)代碼掃描測試流程工具類似于lint靜態(tài)掃描分析工具,并將其輸出標(biāo)準(zhǔn)化為報表的工具。
- github:https://github.com/360EntSecGroup-Skylar/goreporter
- urlreport:http://fiisio.me/pages/goreporter-report.html
Sonar-golang:它在SonarQube儀表板中集成了GoMetaLinter報告。 用戶必須使用checkstyle格式為其代碼生成GoMetaLinter報告。 該報告因此使用Sonar-golang集成到SonarQube中。
SonarQube原理
從上圖中可以知道SonarQube可以做持續(xù)集成靜態(tài)代碼掃描分析也可以和IDE Integrotion工具集成實現(xiàn)程序員邊寫代碼邊進(jìn)行靜態(tài)代碼分析,提高程序代碼質(zhì)量。
sonar-golang集成GoMetaLinter工具介紹
GoMetaLinter此工具基本集成目前GO語言所有的檢測工具,然后可以并發(fā)的幫你靜態(tài)分析你的代碼。詳細(xì)情況看https://github.com/alecthomas/gometalinter常用功能介紹如下:
- go vet -工具可以幫我們靜態(tài)分析我們的源碼存在的各種問題,例如多余的代碼,提前return的邏輯,struct的tag是否符合標(biāo)準(zhǔn)等。
- go tool vet --shadow -用來檢查作用域里面設(shè)置的局部變量名和全局變量名設(shè)置一樣導(dǎo)致全局變量設(shè)置無效的問題
- gotype -類型檢測用來檢測傳遞過來的變量和預(yù)期變量類型一致
- gotype -x -在外部的測試包里進(jìn)行語法和語義分析
- deadcode -會告訴你哪些代碼片段根本沒用
- gocyclo -用來檢查函數(shù)的復(fù)雜度
- golint -是類似javascript中的jslint的工具,主要功能就是檢測代碼中不規(guī)范的地方變量名規(guī)范,變量的聲明,像var str string = “test”,會有警告,應(yīng)該var str = “test”,大小寫問題,大寫導(dǎo)出包的要有注釋x += 1 應(yīng)該 x++
- varcheck -發(fā)現(xiàn)未使用的全局變量和常量
- structcheck -發(fā)現(xiàn)未使用的 struct 字段
- maligned - 那些struct 結(jié)構(gòu)體的字段沒有排序,排好序的話,占的內(nèi)存少
- errcheck -檢查是否使用了錯誤返回值
- megacheck - 這個寫代碼的時候idea 就提示了
- gosimple -提供信息,幫助你了解哪些代碼可以簡化
- Dupl-檢查是否有重復(fù)的代碼
- ineffassign -檢測不使用變量
- Interfacer -建議可以使用更細(xì)的接口。
- unconvert -檢測冗余類型轉(zhuǎn)換
- goconst -會查找重復(fù)的字符串,這些字符串可以抽取成常量。
- gas - 用來掃描安全性問題 (Go的AST注入)
- safesql -Golang靜態(tài)分析工具,防止SQL注入
GoMetaLinter默認(rèn)是沒有打開的功能有testify、test、gofmt -s、goimports 、gosimple 、lll、misspell 、nakedret 、unparam 、unused、safesql 、staticcheck要是打開下面功能需要用參數(shù)--enable=<linter>方式。
sonar-golang集成go test單元測試
在進(jìn)行GO單元測試前,必須了解go語言單元測試規(guī)則和編譯方式方可進(jìn)行單元測試,只有遵循這些單元規(guī)則才能把報告集成到sonar里面
規(guī)則
- 文件名必須是_test.go結(jié)尾的,這樣在執(zhí)行g(shù)o test的時候才會執(zhí)行到相應(yīng)的代碼
- 你必須import testing這個包
- 所有的測試用例函數(shù)必須是Test開頭
- 測試用例會按照源代碼中寫的順序依次執(zhí)行
- 測試函數(shù)TestXxx()的參數(shù)是testing.T,我們可以使用該類型來記錄錯誤或者是測試狀態(tài)
- 測試格式:func TestXxx (t *testing.T),Xxx部分可以為任意的字母數(shù)字的組合,但是首字母不能是小寫字母[a-z],例如Testintdiv是錯誤的函數(shù)名。
- 函數(shù)中通過調(diào)用testing.T的Error, Errorf, FailNow, Fatal, FatalIf方法,說明測試不通過,調(diào)用Log方法用來記錄測試的信息。
編譯方式
- go test .編譯當(dāng)前文件夾所有test測試用例(注意go test 后面的點)
- go test -p 編譯這個包測試
- go test -v 打印測試信息(默認(rèn)不打印測試通過信息)
如Test_test.go
package gotest
import (
"testing"
)
func Test_Division_1(t *testing.T) {
if i, e := Division(6, 2); i != 3 || e != nil { //try a unit test on function
t.Error("除法函數(shù)測試沒通過") // 如果不是如預(yù)期的那么就報錯
} else {
t.Log("第一個測試通過了") //記錄一些你期望記錄的信息
}
}
//func Test_Division_2(t *testing.T) {
// t.Error("就是不通過")
//}
func Test_Division_2(t *testing.T) {
if _, e := Division(6, 0); e == nil { //try a unit test on function
t.Error("Division did not work as expected.") // 如果不是如預(yù)期的那
么就報錯
} else {
t.Log("one test passed.", e) //記錄一些你期望記錄的信息
}
}
sonar-golang相關(guān)集成工具安裝和使用
Golang安裝
安裝步驟
1、wget [https://dl.google.com/go/go1.10.linux-amd64.tar.gz]
2、tar -xf go1.10.linux-amd64.tar.gz
3、mv go /usr/local/go1.10.linux-amd64
4、cd go/src
5、./all.bash
6、vim /etc/profile
export GOROOT=/usr/local/go
export GOBIN=GOROOT/bin export GOPATH=/home/mpsp/gowork export PATH=PATH:GOPATH:GOBIN:$GOPATH
source /etc/profile
go version
Sonarqube安裝
安裝要求
Java1.8+mysql5.6以上的版本+sonarqube(Checkstyle Chinese Pack PMD Web )+sonar-scanner
安裝步驟
1、yum install -y java-1.8.0
2、wget https://sonarsource.bintray.com/Distribution/sonarqube/sonarqube-5.6.zip
3、unzip sonarqube-7.0.zip
4、ln -s sonarqube-7.0 sonarqube
準(zhǔn)備Sonar數(shù)據(jù)庫(sonar不支持MySQL5.5,所以如果看日志出現(xiàn)以上error 請安裝mysql5.6 或者更高版)
5、wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm
6、 rpm -ivh mysql-community-release-el7-5.noarch.rpm
7、yum install mysql-community-server mariadb mariadb-server
8、systemctl start mysqld.service
9、mysql -uroot
mysql>update mysql.user set authentication_string=password('123456') where user='root';
mysql>flush privileges;
10、mysql -uroot -p123456
執(zhí)行sql語句
mysql> CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;
mysql> GRANT ALL ON sonar.* TO 'sonar'@'localhost' IDENTIFIED BY 'sonar@pw';
mysql> GRANT ALL ON sonar.* TO 'sonar'@'%' IDENTIFIED BY 'sonar@pw';
mysql> FLUSH PRIVILEGES;
11、修改/etc/my.cnf文件:
max_allowed_packet=128M
innodb_buffer_pool_size=512M
innodb_log_file_size=128M
innodb_log_buffer_size=1M
12、systemctl stop mysqld
13、systemctl start mysqld
配置Sonar
14、cd ~/sonarqube/conf/
15、vi sonar.properties
sonar.jdbc.username=sonar
sonar.jdbc.password=sonar@pw
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
sonar.web.host=0.0.0.0
sonar.web.port=9000
13、~/sonarqube/bin/linux-x86-64/sonar.sh start
14、http://ip:9000/admin/marketplace admin登入安裝插件 Checkstyle Chinese Pack PMD Web
15、打開sonarqube的控制臺,使用admin登錄后 ,在配置->SCM->菜單中,將Disabled the SCM Sensor設(shè)置為true否則使用會報錯
安裝go語言插件--sonar-golang
1、cd ~/sonarqube/extensions
2、wget https://github.com/uartois/sonar-golang/releases/download/v1.2.11/sonar-golang-plugin-1.2.11.jar
3、cd ~/sonarqube/bin/linux-x86-64&sonar.sh restart
以admin用戶登入編輯GO規(guī)則(目前版本只支持58條規(guī)則)
4、點擊Quality Profiles 頁面---點擊"Create" 按鈕---點擊Restore Built-In Profiles選擇language (Go)點擊保存
SonarQube Scanner(掃描器)安裝
1、wget https://sonarsource.bintray.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-3.0.3.778-linux.zip
2、unzip sonar-scanner-cli-3.0.3.778-linux.zip
3、ln -s sonar-scanner-3.0.3.778-linux sonar-scanner
4、cd ~/sonar-scanner/conf
5、vi sonar-scanner.properties
sonar.host.url=http://localhost:9000
sonar.sourceEncoding=UTF-8
sonar.login=admin
sonar.password=admin
sonar.projectKey=uchains
sonar.projectName=uchains
sonar.projectVersion=1.0
sonar.golint.reportPath=report.xml
sonar.coverage.reportPath=coverage.xml
sonar.coverage.dtdVerification=false
sonar.test.reportPath=test.xml
sonar.sources=./
sonar.sources.inclusions=** /** .go
sonar.sources.exclusions=** /** _test.go,** /vendor/ * .com/ ** ,** /vendor/* .org/** ,** /vendor/**
sonar.tests=./
sonar.test.inclusions=** /** _test.go
sonar.test.exclusions=** /vendor/* .com/** ,** /vendor/* .org/** ,** /vendor/**
sonar.exclusions配置規(guī)則是? 匹配單個字符 ,** 匹配0個或多個文件夾 ,* 匹配0個或多個字符.
配置sonar-scanner環(huán)境變量
6、vi /etc/profile
PATH=$PATH:~/sonar-scanner/bin
export PATH
7、source .bashrc
GoMetaLinter 工具安裝
1、yum -y install git
2、go get -u gopkg.in/alecthomas/gometalinter.v1
3、gometalinter.v1 --install --update
4、gometalinter.v1 --install --debug
5、go get -u gopkg.in/alecthomas/gometalinter.v2
6、gometalinter.v2 --install --update
7、gometalinter.v2 --version
Coverage (since release 1.1) 安裝(用來檢測單元測試覆蓋率報告)
1、go get github.com/axw/gocov/...
2、go get github.com/AlekSi/gocov-xml
3、gocov (運行命令不報錯)
Tests (since release 1.1) 安裝(用來單元測試出報告)
1、go get -u github.com/jstemmer/go-junit-report
2、go test -v ./... | go-junit-report > test.xml
到此為止涉及到有GO語言靜態(tài)代碼掃描工具已經(jīng)全部安裝完,只要運行相關(guān)命令不報錯,接下來進(jìn)入你寫的GO工程目錄運行你寫的代碼就知道相關(guān)代碼質(zhì)量
案例說明
上面既然說明工具已經(jīng)安裝完,下面就簡單運行一個示例看看效果
1、準(zhǔn)備示例代碼test.go
package gotest
import (
"errors"
)
func Division(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("除數(shù)不能為0")
}
return a / b, nil
}
2、準(zhǔn)備測試代碼Test_test.go
package gotest
import (
"testing"
)
func Test_Division_1(t *testing.T) {
if i, e := Division(6, 2); i != 3 || e != nil {
t.Error("除法函數(shù)測試沒通過") // 如果不是如預(yù)期的那么就報錯 //try a unit test on function
} else {
t.Log("第一個測試通過了") //記錄一些你期望記錄的信息
}}
//func Test_Division_2(t *testing.T) {
// t.Error("就是不通過")
//}
func Test_Division_2(t *testing.T) {
if _, e := Division(6, 0); e == nil { //try a unit test on function
t.Error("Division did not work as expected.") // 如果不是如預(yù)期的那
么就報錯
} else {
t.Log("one test passed.", e) //記錄一些你期望記錄的信息
}
}
3、在此工程目錄下運行下面命令
使用gometalinter進(jìn)行代碼風(fēng)格檢查和代碼質(zhì)量檢測,命令如下:
gometalinter.v2 --checkstyle ./... > report.xml
gometalinter.v2 ./... > reportquality.xml
使用coverage進(jìn)行單元測試覆蓋率檢查,要是go的1.9以下的版本必須用公go test ./... -coverprofile=...也可以用gocov test ./... | gocov-xml > coverage.xml 這樣的命令執(zhí)行,命令如下:
go test -coverprofile=cover.out
gocov convert cover.out | gocov-xml > coverage.xml
go-junit-report工具生成單元測試報告執(zhí)行下面命令:
go test -v ./... | go-junit-report > test.xml
SonarQube Scanner(掃描器)進(jìn)行加載SonarQube相關(guān)規(guī)則和GO 語言插件定義的規(guī)則進(jìn)行工程目錄下層層檢測,只要不錯檢測就成功了,要是檢測報錯可以看掃描器的日志和SonarQube日志執(zhí)行命令如下
sonar-scanner
要是檢測目錄有多級目錄可以寫一個腳步自動執(zhí)行,腳步如下:
#!/bin/bash
BASE=~/workgo/src/uchains
for D in `find . -type d‘
do
if [[ $D == ./.git/* ]]; then
continue
elif [[ $D == .. ]]; then
continue
elif [[ $D == . ]]; then
continue
elif [[ $D == ./vendor/* ]]; then
continue
elif [[ $D == ./vendor ]]; then
continue
elif [[ $D == ./.svn/* ]]; then
continue
elif [[ $D == ./.svn ]]; then
continue
elif [[ $D == ./.idea ]]; then
continue
elif [[ $D == ./.idea/* ]]; then
continue
fi
echo $D
cd $D
rm -rf coverage.xml test.xml report.xml cover.out reportquality.xml
gometalinter.v2 ./... > reportquality.xml
go test -coverprofile=cover.out
gocov convert cover.out | gocov-xml > coverage.xml
cd $BASE
done
gometalinter.v2 --checkstyle ./... > report.xml
gometalinter.v2 ./... > reportquality.xml
go test -v ./... | go-junit-report > test.xml
sonar-scanner
4、掃描成功后,下面就看看SonarQube 出來的報告
從上面圖可以看到工程總體質(zhì)量正常,單元測試覆蓋率100%,目前有3個輕微的BUG
從上圖可以看到目前工程存在的BUG
根據(jù)圖上的指標(biāo)維度去分析代碼質(zhì)量
這張圖闡述代碼質(zhì)量,特別適合代碼評審使用
此圖是利用gometalinter.v2 ./... > reportquality.xml掃描出來的結(jié)果,這里可以分析出很問題,幫助程序員提高代碼能力。
IDE 的Intelij IDEA集成
安裝sonarLint、sonarQube community plugin
1、Settings->Plugins->Browse Repositories 搜索sonarLint、sonarQube community plugin點擊安裝。
2、配置關(guān)聯(lián)sonar服務(wù)
全局設(shè)置:Settings->Other Settings->SonarLint General Settings 添加sonar服務(wù)http://10.10.144.27:9000
項目設(shè)置:Settings->Other Settings->SonarLint Project Settings 選擇剛才配置的sonar服務(wù),關(guān)聯(lián)到本項目
3、安裝分析的插件
go get -u gopkg.in/alecthomas/gometalinter.v2
gometalinter.v2 --install --update
go get github.com/axw/gocov
go get github.com/AlekSi/gocov-xml
go get -u github.com/jstemmer/go-junit-report
4、SonarQube Scanner的安裝和配置
在https://sonarsource.bintray.com/Distribution/sonar-scanner-cli/下載最新版本,解壓后配置環(huán)境變量
SONAR_SCANNER_HOME=Sonar Scanner根目錄
修改系統(tǒng)變量path,新增%SONAR_SCANNER_HOME%\bin(不新建SONAR_SCANNER_HOME直接新增path亦可)
打開cmd面板,輸入sonar-scanner -version,不出錯,則表示環(huán)境變量設(shè)置成功
sonar-scanner.properties配置
#----- Default source code encoding
sonar.sourceEncoding=UTF-8
sonar.login=admin
sonar.password=admin
#sonar.scm.disabled=true
#uchains
sonar.projectKey=uchains
sonar.projectName=uchains
sonar.projectVersion=1.0
sonar.golint.reportPath=report.xml
sonar.coverage.reportPath=coverage.xml
sonar.coverage.dtdVerification=false
sonar.test.reportPath=test.xml
sonar.showProfiling=true
sonar.log.level=DEBUG
#sonar.userHome={basedir}/.sonar sonar.verbose=true sonar.coverage.exclusions=vendor/** sonar.sources=./ sonar.sources.inclusions=** /** .go sonar.sources.exclusions=** /** _ test.go,** /vendor/* .com/ ** , ** /vendor/* .org/** ,** /vendor/** sonar.tests=./ sonar.test.inclusions=** /** _test.go sonar.test.exclusions=** /vendor/* .com/** ,** /vendor/* .org/** ,** /vendor/** 5、Intelij IDEA設(shè)置 Settings->Tools->ExternalTools如下圖   運行小程序  將下面腳本寫個批處理放到ExternalTools中執(zhí)行也可以手工執(zhí)行 del coverage.xml test.xml report.xml cover.out reportquality.xml gometalinter.v2 ./... > reportquality.xml gometalinter.v2 --checkstyle ./... > report.xml go test -coverprofile=cover.out gocov convert cover.out | gocov-xml > coverage.xml go test -v ./... | go-junit-report > test.xml 安裝報錯信息如下:用下面方式解決 mkdir -pGOPATH/src/golang.org/x
cd $GOPATH/src/golang.org/x
git clone https://github.com/golang/net.git
git clone https://github.com/golang/tools.git
如何執(zhí)行下面命令安裝
go get -v github.com/axw/gocov/...
錯誤信息如下:
D:\workspacego\testgo\src\uchains\api\bccsp>go get -v github.com/axw/gocov/...
Fetching https://golang.org/x/tools/cover?go-get=1
https fetch failed: Get https://golang.org/x/tools/cover?go-get=1: dial tcp 216.
239.37.1:443: connectex: A connection attempt failed because the connected party
did not properly respond after a period of time, or established connection fail
ed because connected host has failed to respond.
package golang.org/x/tools/cover: unrecognized import path "golang.org/x/tools/c
over" (https fetch: Get https://golang.org/x/tools/cover?go-get=1: dial tcp 216.
239.37.1:443: connectex: A connection attempt failed because the connected party
did not properly respond after a period of time, or established connection fail
ed because connected host has failed to respond.)
要想查看IDEA查看日志詳細(xì)信息
請在.idea目錄下的sonarlint.xml文件增加下面類容
<option name="verboseEnabled" value="true" />
<option name="analysisLogsEnabled" value="true" />
參考url:https://www.cnblogs.com/wintersun/p/5674903.html
https://github.com/gojp/goreportcard
https://github.com/360EntSecGroup-Skylar/goreporter 3.0版本
http://fiisio.me/pages/go_codereview_ana.html
https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
https://github.com/alecthomas/gometalinter
https://blog.csdn.net/YID_152/article/details/53514036
http://www.lxweimin.com/p/711c1536f9f3
https://blog.csdn.net/u012500848/article/details/72963587
http://www.lxweimin.com/p/8f2a3020af94 Pipeline工具使用