GO语言静态代码测试---应用于区块链构建性测试 - Go语言中文社区

GO语言静态代码测试---应用于区块链构建性测试


背景

随着区块链的这2年的快速发展,Go语言和针对GO语言测试工具也越来越完善,特别是Go语言的静态代码扫描工具完善,使GO语言和JAVA语言一样可以静态代码自动扫描测试。说GO语言静态代码测试之前先说说静态代码测试。

静态代码测试

静态代码测试在不执行计算机程序的条件下,对源代码进行分析,找出代码缺陷。

  • 静态代码测试检测类型:死锁,空指针,资源泄露,缓冲区溢出,安全漏洞,竞态条件。
  • 静态代码测试优点:
    1、能够检测所有的代码级别的可执行路径组合,快速,准确。
    2、直接面向源码,分析多种问题
    3、在研发阶段开始找到并修复多种问题,节省大量时间/人力成本
  • 静态代码测试缺点
    1、高误报率:目前静态分析产品的误报率普遍在30%以上。
    2、缺陷种类较少,找到的问题级别不高:多数为代码规范或低级缺陷,3、非实际Bug – 如命名规范、类定义规范,最佳实践.....

GO语言静态扫描测试工具

目前Go语言主流静态代码扫描测试工具主要是GoReporte和sonar集成的sonar-golang插件

GoReporte: 一个用于执行静态分析,单元测试,代码审查并生成代码质量报告的Golang工具,这是一个运行一整套静态代码扫描测试流程工具类似于lint静态扫描分析工具,并将其输出标准化为报表的工具。

Sonar-golang:它在SonarQube仪表板中集成了GoMetaLinter报告。 用户必须使用checkstyle格式为其代码生成GoMetaLinter报告。 该报告因此使用Sonar-golang集成到SonarQube中。

SonarQube原理

从上图中可以知道SonarQube可以做持续集成静态代码扫描分析也可以和IDE Integrotion工具集成实现程序员边写代码边进行静态代码分析,提高程序代码质量。

sonar-golang集成GoMetaLinter工具介绍

GoMetaLinter此工具基本集成目前GO语言所有的检测工具,然后可以并发的帮你静态分析你的代码。详细情况看https://github.com/alecthomas/gometalinter常用功能介绍如下:

  • go vet -工具可以帮我们静态分析我们的源码存在的各种问题,例如多余的代码,提前return的逻辑,struct的tag是否符合标准等。
  • go tool vet --shadow -用来检查作用域里面设置的局部变量名和全局变量名设置一样导致全局变量设置无效的问题
  • gotype -类型检测用来检测传递过来的变量和预期变量类型一致
  • gotype -x -在外部的测试包里进行语法和语义分析
  • deadcode -会告诉你哪些代码片段根本没用
  • gocyclo -用来检查函数的复杂度
  • golint -是类似javascript中的jslint的工具,主要功能就是检测代码中不规范的地方变量名规范,变量的声明,像var str string = “test”,会有警告,应该var str = “test”,大小写问题,大写导出包的要有注释x += 1 应该 x++
  • varcheck -发现未使用的全局变量和常量
  • structcheck -发现未使用的 struct 字段
  • maligned - 那些struct 结构体的字段没有排序,排好序的话,占的内存少
  • errcheck -检查是否使用了错误返回值
  • megacheck - 这个写代码的时候idea 就提示了
  • gosimple -提供信息,帮助你了解哪些代码可以简化
  • Dupl-检查是否有重复的代码
  • ineffassign -检测不使用变量
  • Interfacer -建议可以使用更细的接口。
  • unconvert -检测冗余类型转换
  • goconst -会查找重复的字符串,这些字符串可以抽取成常量。
  • gas - 用来扫描安全性问题 (Go的AST注入)
  • safesql -Golang静态分析工具,防止SQL注入
    GoMetaLinter默认是没有打开的功能有testify、test、gofmt -s、goimports 、gosimple 、lll、misspell 、nakedret 、unparam 、unused、safesql 、staticcheck要是打开下面功能需要用参数--enable=<linter>方式。

sonar-golang集成go test单元测试

在进行GO单元测试前,必须了解go语言单元测试规则和编译方式方可进行单元测试,只有遵循这些单元规则才能把报告集成到sonar里面

规则

  • 文件名必须是_test.go结尾的,这样在执行go test的时候才会执行到相应的代码
  • 你必须import testing这个包
  • 所有的测试用例函数必须是Test开头
  • 测试用例会按照源代码中写的顺序依次执行
  • 测试函数TestXxx()的参数是testing.T,我们可以使用该类型来记录错误或者是测试状态
  • 测试格式:func TestXxx (t *testing.T),Xxx部分可以为任意的字母数字的组合,但是首字母不能是小写字母[a-z],例如Testintdiv是错误的函数名。
  • 函数中通过调用testing.T的Error, Errorf, FailNow, Fatal, FatalIf方法,说明测试不通过,调用Log方法用来记录测试的信息。

编译方式

  • go test .编译当前文件夹所有test测试用例(注意go test 后面的点)
  • go test -p 编译这个包测试
  • go test -v 打印测试信息(默认不打印测试通过信息)
    如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("除法函数测试没通过") // 如果不是如预期的那么就报错
    } 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.") // 如果不是如预期的那
    么就报错
    } else {
    t.Log("one test passed.", e) //记录一些你期望记录的信息
    }
    }

sonar-golang相关集成工具安装和使用

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
准备Sonar数据库(sonar不支持MySQL5.5,所以如果看日志出现以上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
执行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设置为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规则(目前版本只支持58条规则)
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配置规则是? 匹配单个字符 ,** 匹配0个或多个文件夹 ,* 匹配0个或多个字符.
配置sonar-scanner环境变量
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语言静态代码扫描工具已经全部安装完,只要运行相关命令不报错,接下来进入你写的GO工程目录运行你写的代码就知道相关代码质量

案例说明

上面既然说明工具已经安装完,下面就简单运行一个示例看看效果
1、准备示例代码test.go
package gotest
import (
"errors"
)
func Division(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("除数不能为0")
}
return a / b, nil
}
2、准备测试代码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("除法函数测试没通过") // 如果不是如预期的那么就报错 //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.") // 如果不是如预期的那
么就报错
} else {
t.Log("one test passed.", e) //记录一些你期望记录的信息
}
}
3、在此工程目录下运行下面命令
使用gometalinter进行代码风格检查和代码质量检测,命令如下:
gometalinter.v2 --checkstyle ./... > report.xml
gometalinter.v2 ./... > reportquality.xml
使用coverage进行单元测试覆盖率检查,要是go的1.9以下的版本必须用公go test ./... -coverprofile=...也可以用gocov test ./... | gocov-xml > coverage.xml 这样的命令执行,命令如下:
go test -coverprofile=cover.out
gocov convert cover.out | gocov-xml > coverage.xml
go-junit-report工具生成单元测试报告执行下面命令:
go test -v ./... | go-junit-report > test.xml
SonarQube Scanner(扫描器)进行加载SonarQube相关规则和GO 语言插件定义的规则进行工程目录下层层检测,只要不错检测就成功了,要是检测报错可以看扫描器的日志和SonarQube日志执行命令如下
sonar-scanner
要是检测目录有多级目录可以写一个脚步自动执行,脚步如下:

#!/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 出来的报告


总述图

从上面图可以看到工程总体质量正常,单元测试覆盖率100%,目前有3个轻微的BUG


BUG图

从上图可以看到目前工程存在的BUG
指标图

根据图上的指标维度去分析代码质量


代码质量描述.png

这张图阐述代码质量,特别适合代码评审使用
gometalinter扫描结果图

此图是利用gometalinter.v2 ./... > reportquality.xml扫描出来的结果,这里可以分析出很问题,帮助程序员提高代码能力。

IDE 的Intelij IDEA集成

安装sonarLint、sonarQube community plugin
1、Settings->Plugins->Browse Repositories 搜索sonarLint、sonarQube community plugin点击安装。
2、配置关联sonar服务
全局设置:Settings->Other Settings->SonarLint General Settings 添加sonar服务http://10.10.144.27:9000
项目设置:Settings->Other Settings->SonarLint Project Settings 选择刚才配置的sonar服务,关联到本项目
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/下载最新版本,解压后配置环境变量
SONAR_SCANNER_HOME=Sonar Scanner根目录
修改系统变量path,新增%SONAR_SCANNER_HOME%bin(不新建SONAR_SCANNER_HOME直接新增path亦可)
打开cmd面板,输入sonar-scanner -version,不出错,则表示环境变量设置成功
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设置 Settings->Tools->ExternalTools如下图 ![gometalinter.v2设置](https://upload-images.jianshu.io/upload_images/4852683-d78b6191aaf29865.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![sonar-scanner设置](https://upload-images.jianshu.io/upload_images/4852683-fc4470497176b0df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 运行小程序 ![image.png](https://upload-images.jianshu.io/upload_images/4852683-3dfc8bef3f8a1074.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 将下面脚本写个批处理放到ExternalTools中执行也可以手工执行 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
如何执行下面命令安装
go get -v github.com/axw/gocov/...
错误信息如下:
D:workspacegotestgosrcuchainsapibccsp>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查看日志详细信息
请在.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
https://www.jianshu.com/p/711c1536f9f3
https://blog.csdn.net/u012500848/article/details/72963587
https://www.jianshu.com/p/8f2a3020af94 Pipeline工具使用

版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/aa44d4a822d0
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-07 22:12:17
  • 阅读 ( 1724 )
  • 分类:区块链

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢