go test 命令详解
文章目录
- 1.简介
- 2.test flag
- 3.test/binary flags
- 4.常用选项
- 5.示例
- 参考文献
1.简介
go test 是 Go 用来执行测试函数(test function)、基准函数(benchmark function)和示例函数(example function)的命令。
执行 go test 命令,它会在*_test.go
文件中寻找 test、benchmark 和 example 函数来执行。测试函数名必须以 TestXXX 开头,基准函数名必须以 BenchmarkXXX 开头,示例函数必须以 ExampleXXX 开头。
// test 测试函数
func TestXXX(t *testing.T) { ... }// benchmark 基准函数
func BenchmarkXXX(b *testing.B) { ... }// examples 示例函数,其相关命名方式可以查看第一篇文章
func ExamplePrintln() {Println("The output of\nthis example.")// Output: The output of// this example.
}
关于更多测试函数的信息请查看go help testfunc
。
命令格式如下:
go test [build/test flags] [packages] [build/test flags & test binary flags]
go test 自动测试指定的包。它以以下格式打印测试结果摘要:
ok archive/tar 0.011s
FAIL archive/zip 0.022s
ok compress/gzip 0.033s
...
然后是每个失败包的详细输出。
go test 重新编译每个包中后缀为_test.go
的文件。这些文件可以包含测试函数、基准函数和示例函数。有关更多信息,请参阅“go help testfunc”。每个列出的包都会导致执行一个单独的测试二进制文件。注意名称以_
或.
开头的文件即使后缀是_test.go
将被忽略。
测试文件中如果声明的包后缀为_test
将被作为单独的包来编译,然后与主测试二进制文件链接并运行。
go test 命令还会忽略 testdata 目录,该目录用来保存测试需要用到的辅助数据。
go test 有两种运行模式:
(1)本地目录模式,在没有包参数(如 go test 或 go test -v)调用时发生。在此模式下,go test 编译当前目录中找到的包和测试,然后运行测试二进制文件。在这种模式下,caching 是禁用的。在包测试完成后,go test 打印一个概要行,显示测试状态、包名和运行时间。
(2)包列表模式,在使用显示包参数调用 go test 时发生(例如 go test math,go test ./… 甚至是 go test .)。在此模式下,go 测试编译并测试在命令上列出的每个包。如果一个包测试通过,go test 只打印最终的 ok 总结行。如果一个包测试失败,go test 将输出完整的测试输出。如果使用 -bench 或 -v 选项,则 go test 会输出完整的输出,甚至是通过包测试,以显示所请求的基准测试结果或详细日志记录。
注意: 描述软件包列表时,命令使用三个点作为通配符。如测试当前目录及其子目录中的所有软件包。
go test ./...
仅在包列表模式下,go test 会缓存成功的包测试结果,以避免不必要的重复运行测试。当测试结果可以从缓存中恢复时,go tes t将重新显示以前的输出,而不是再次运行测试二进制文件。发生这种情况时,go test 打印 “(cached)” 以代替摘要行中的已用时间。
缓存中匹配的规则是,运行涉及相同的测试二进制文件,命令行上的选项完全来自一组受限的“可缓存”测试选项,定义为 -benchtime、-cpu、-list、-parallel、-run、-short 和 -v。如果运行 go test 时任何测试选项或非测试选项在此集合之外,则不会缓存结果。要禁用缓存,请使用除可缓存选项之外的任何测试选项或参数。明确禁用测试缓存的惯用方法是使用 -count=1。测试在包的根目录(通常为 $GOPATH)打开的文件和依赖的环境变量,只有不发生变化时才能匹配缓存。
被缓存的测试结果将被视为立即执行,因此无论 -timeout 如何设置,成功的包测试结果都将被缓存和重用。
2.test flag
除 build 选项外,go test 本身处理的选项包括:
-argsPass the remainder of the command line (everything after -args)to the test binary, uninterpreted and unchanged.Because this flag consumes the remainder of the command line,the package list (if present) must appear before this flag.-cCompile the test binary to pkg.test but do not run it(where pkg is the last element of the package's import path).The file name can be changed with the -o flag.-exec xprogRun the test binary using xprog. The behavior is the same asin 'go run'. See 'go help run' for details.-iInstall packages that are dependencies of the test.Do not run the test.The -i flag is deprecated. Compiled packages are cached automatically.-jsonConvert test output to JSON suitable for automated processing.See 'go doc test2json' for the encoding details.-o fileCompile the test binary to the named file.The test still runs (unless -c or -i is specified).
有关构建选项的更多信息,请参阅“go help build”。有关指定软件包的更多信息,请参阅“go help packages”。
3.test/binary flags
以下选项同时支持测试二进制文件和 go test 命令。
主要分为两类,一类控制测试行为,一类用于状态分析。
控制测试行为选项:
-bench regexpRun only those benchmarks matching a regular expression.By default, no benchmarks are run.To run all benchmarks, use '-bench .' or '-bench=.'.The regular expression is split by unbracketed slash (/)characters into a sequence of regular expressions, and eachpart of a benchmark's identifier must match the correspondingelement in the sequence, if any. Possible parents of matchesare run with b.N=1 to identify sub-benchmarks. For example,given -bench=X/Y, top-level benchmarks matching X are runwith b.N=1 to find any sub-benchmarks matching Y, which arethen run in full.-benchtime tRun enough iterations of each benchmark to take t, specifiedas a time.Duration (for example, -benchtime 1h30s).The default is 1 second (1s).The special syntax Nx means to run the benchmark N times(for example, -benchtime 100x).-count nRun each test and benchmark n times (default 1).If -cpu is set, run n times for each GOMAXPROCS value.Examples are always run once.-coverEnable coverage analysis.Note that because coverage works by annotating the sourcecode before compilation, compilation and test failures withcoverage enabled may report line numbers that don't correspondto the original sources.-covermode set,count,atomicSet the mode for coverage analysis for the package[s]being tested. The default is "set" unless -race is enabled,in which case it is "atomic".The values:set: bool: does this statement run?count: int: how many times does this statement run?atomic: int: count, but correct in multithreaded tests;significantly more expensive.Sets -cover.-coverpkg pattern1,pattern2,pattern3Apply coverage analysis in each test to packages matching the patterns.The default is for each test to analyze only the package being tested.See 'go help packages' for a description of package patterns.Sets -cover.-cpu 1,2,4Specify a list of GOMAXPROCS values for which the tests orbenchmarks should be executed. The default is the current valueof GOMAXPROCS.-failfastDo not start new tests after the first test failure.-list regexpList tests, benchmarks, or examples matching the regular expression.No tests, benchmarks or examples will be run. This will onlylist top-level tests. No subtest or subbenchmarks will be shown.-parallel nAllow parallel execution of test functions that call t.Parallel.The value of this flag is the maximum number of tests to runsimultaneously; by default, it is set to the value of GOMAXPROCS.Note that -parallel only applies within a single test binary.The 'go test' command may run tests for different packagesin parallel as well, according to the setting of the -p flag(see 'go help build').-run regexpRun only those tests and examples matching the regular expression.For tests, the regular expression is split by unbracketed slash (/)characters into a sequence of regular expressions, and each partof a test's identifier must match the corresponding element inthe sequence, if any. Note that possible parents of matches arerun too, so that -run=X/Y matches and runs and reports the resultof all tests matching X, even those without sub-tests matching Y,because it must run them to look for those sub-tests.-shortTell long-running tests to shorten their run time.It is off by default but set during all.bash so that installingthe Go tree can run a sanity check but not spend time runningexhaustive tests.-shuffle off,on,NRandomize the execution order of tests and benchmarks.It is off by default. If -shuffle is set to on, then it will seedthe randomizer using the system clock. If -shuffle is set to aninteger N, then N will be used as the seed value. In both cases,the seed will be reported for reproducibility.-timeout dIf a test binary runs longer than duration d, panic.If d is 0, the timeout is disabled.The default is 10 minutes (10m).-vVerbose output: log all tests as they are run. Also print alltext from Log and Logf calls even if the test succeeds.-vet listConfigure the invocation of "go vet" during "go test"to use the comma-separated list of vet checks.If list is empty, "go test" runs "go vet" with a curated list ofchecks believed to be always worth addressing.If list is "off", "go test" does not run "go vet" at all.
状态分析选项:
-benchmemPrint memory allocation statistics for benchmarks.-blockprofile block.outWrite a goroutine blocking profile to the specified filewhen all tests are complete.Writes test binary as -c would.-blockprofilerate nControl the detail provided in goroutine blocking profiles bycalling runtime.SetBlockProfileRate with n.See 'go doc runtime.SetBlockProfileRate'.The profiler aims to sample, on average, one blocking event everyn nanoseconds the program spends blocked. By default,if -test.blockprofile is set without this flag, all blocking eventsare recorded, equivalent to -test.blockprofilerate=1.-coverprofile cover.outWrite a coverage profile to the file after all tests have passed.Sets -cover.-cpuprofile cpu.outWrite a CPU profile to the specified file before exiting.Writes test binary as -c would.-memprofile mem.outWrite an allocation profile to the file after all tests have passed.Writes test binary as -c would.-memprofilerate nEnable more precise (and expensive) memory allocation profiles bysetting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'.To profile all memory allocations, use -test.memprofilerate=1.-mutexprofile mutex.outWrite a mutex contention profile to the specified filewhen all tests are complete.Writes test binary as -c would.-mutexprofilefraction nSample 1 in n stack traces of goroutines holding acontended mutex.-outputdir directoryPlace output files from profiling in the specified directory,by default the directory in which "go test" is running.-trace trace.outWrite an execution trace to the specified file before exiting.
4.常用选项
-bench regexp只执行匹配对应正则表达式的 benchmark 函数,如执行所有性能测试 "-bench ." 或 "-bench=."
-benchtime t对每个 benchmark 函数运行指定时间。如 -benchtime 1h30,默认值为 1s。特殊语法 Nx 表示运行基准测试 N 次(如 -benchtime 100x)
-run regexp只运行匹配对应正则表达式的 test 和 example 函数,例如 "-run Array" 那么就执行函数名包含 Array 的单测函数
-cover开启测试覆盖率
-v显示测试的详细命令
5.示例
假设在文件 add.go 有一个被测试函数
package hellofunc Add(a, b int) int {return a + b
}
- 测试函数(test function)
在测试文件 add_test.go 添加一个单元测试函数 TestAdd:
package hellofunc TestAdd(t *testing.T) {sum := Add(5, 5)if sum == 10 {t.Log("the result is ok")} else {t.Fatal("the result is wrong")}
}
比如使用 -run 来运行指定单元测试函数,发现只运行了 TestAdd 测试函数。
go test -v -run TestAdd main/hello
=== RUN TestAddadd_test.go:16: the result is ok
--- PASS: TestAdd (0.00s)
PASS
ok main/hello 0.170s
- 基准函数(benchmark function)
添加一个性能测试函数 BenchmarkAdd:
package hellofunc BenchmarkAdd(b *testing.B) {for n := 0; n < b.N; n++ {Add(1, 2)}
}
运行指定基准函数:
go test -bench BenchmarkAdd main/hello
goos: windows
goarch: amd64
pkg: main/contain
cpu: Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz
BenchmarkAdd-8 1000000000 0.2333 ns/op
PASS
ok main/contain 0.586s
- 示例函数(example function)
package hellofunc ExampleAdd() {fmt.Println(Add(1, 2))// Output: 3
}
运行指定示例函数:
go test -v -run ExampleAdd main/contain
=== RUN ExampleAdd
--- PASS: ExampleAdd (0.00s)
PASS
ok main/contain (cached)
注意: 示例函数类似于测试函数,但不是使用 *testing.T 来报告成功或失败,而是将输出打印到 os.Stdout。如果示例函数中的最后一条注释以“Output:”开头,则将输出与注释进行精确比较(参见上面的示例)。如果最后一条注释以“Unordered output:”开头,则将输出与注释进行比较,但忽略行的顺序。编译了一个没有此类注释的示例函数,会被编译但不会被执行。如果在“Output:”之后没有文本,示例函数仍会被编译并执行,并且预期不会产生任何输出。
- 获取每个函数的单测覆盖率。
如果您想查找没有被测试覆盖的函数,可以使用 -coverprofile 选项将覆盖率报告输出到文件中。
go test -coverprofile cover.out ./...
然后使用内置的 go tool cover 命令来查看单测覆盖率报告。
go tool cover -func cover.out
上面使用 -func 选项可以输出每个函数的单测覆盖率概要信息。
github.com/dablelv/cyan/cmp/cmp.go:21: Cmp 100.0%
github.com/dablelv/cyan/cmp/cmp.go:35: Compare 95.5%
github.com/dablelv/cyan/cmp/cmp.go:85: CompareLT 0.0%
...
- 查看具体代码行的覆盖情况。
如果想查看代码行的单测覆盖情况,可以使用内置的 go tool cover 命令将覆盖率报告转换为 HTML 文件。然后通过浏览器打开查看。
go tool cover -html=coverage.out -o coverage.html
参考文献
Command Documentation
go command documentation
相关文章:

go test 命令详解
文章目录 1.简介2.test flag3.test/binary flags4.常用选项5.示例参考文献 1.简介 go test 是 Go 用来执行测试函数(test function)、基准函数(benchmark function)和示例函数(example function)的命令。 …...

【Mysql学习笔记】1 - Mysql入门
一、Mysql5.7安装配置 下载后会得到zip 安装文件解压的路径最好不要有中文和空格这里我解压到 D:\hspmysql\mysql-5.7.19-winx64 目录下 【根据自己的情况来指定目录,尽量选择空间大的盘】 添加环境变量 : 电脑-属性-高级系统设置-环境变量,在Path 环境变量增加mysq…...

sentinel 网关
网关简介 大家都都知道在微服务架构中,一个系统会被拆分为很多个微服务。那么作为客户端要如何去调用这么多的微服务呢?如果没有网关的存在,我们只能在客户端记录每个微服务的地址,然后分别去调用。 这样的架构,会存在…...

常见面试题-MySQL的Explain执行计划
了解 Explain 执行计划吗? 答: explain 语句可以帮助我们查看查询语句的具体执行计划。 explain 查出来的各列含义如下: id:在一个大的查询语句中,每个 select 关键字都对应一个唯一的 id select_type:…...

SpringBoot静态资源配置
项目中 SSM中配置 第一种:配置文件中 <mvc:resources mapping"/js/**" location"/js/"/> <mvc:resources mapping"/css/**" location"/css/"/> <mvc:resources mapping"/html/**" location&q…...

Java拼图
第一步是创建项目 项目名自拟 第二部创建个包名 来规范class 然后是创建类 创建一个代码类 和一个运行类 代码如下: package heima;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import jav…...

Linux 怎样通过win 远程桌面连接链接Linux后台服务器的可视化图形界面
目的概述:因不想后台直接操作(操作不便),所以想到能否基于xrdp协议服务利用 win自带的远程桌面服务,链接到后台,类似于vnc的使用方式,涉及操作系统版本:win11 、 CentOS 7.4 、CentO…...

Java 实现随机图形
要求 定义4个类,MyShape、MyLine、MyRectangle和MyOval,其中MyShape是其他三个类的父类。MyShape为抽象类,包括图形位置的四个坐标;一个无参的构造方法,将所有的坐标设置为0;一个带参的构造函数࿰…...

java 读写文件的代码。
java 读写文件的代码。 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStr…...

如何使用贝锐花生壳内网穿透远程访问JupyterNotebook?
在数据科学领域,Jupyter Notebook 已成为处理数据的必备工具。 其用途包括数据清理和探索、可视化、机器学习和大数据分析。Jupyter Notebook的安装非常简单,如果你是小白,那么建议你通过安装Anaconda来解决Jupyter Notebook的安装问题&#…...

文本向量化
文本向量化表示的输出比较 import timeimport torch from transformers import AutoTokenizer, AutoModelForMaskedLM, AutoModel# simcse相似度分数 def get_model_output(model, tokenizer, text_str):"""验证文本向量化表示的输出:param model: 模型的…...

java--贪吃蛇
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random;public class Snake extends JFrame implements KeyListener, ActionListener, MouseListener {int slong 2;//蛇当前长度//蛇坐标int[] Snakex new int[100];int[] Snakey new…...

录制第一个jmeter性能测试脚本2(http协议)
我们手工编写了一个测试计划,现在我们通过录制的方式来实现那个测试计划。也就是说‘’测试计划目标和上一节类似:让5个用户在2s内登录webtour,然后进入 页面进行查看。 目录 一.性能测试脚本录制的原理 二、性能测试脚本录制的实操&#…...

pip命令大全
pip命令手册 原版 Usage: pip <command> [options]Commands:install Install packages.download Download packages.uninstall Uninstall packages.freeze Output installed packages…...

Redis篇---第二篇
系列文章目录 文章目录 系列文章目录前言一、为什么 使用 Redis 而不是用 Memcache 呢?二、为什么 Redis 单线程模型效率也能那么高?三、说说 Redis 的线程模型前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这…...

【LeetCode刷题日志】232.用栈实现队列
🎈个人主页:库库的里昂 🎐C/C领域新星创作者 🎉欢迎 👍点赞✍评论⭐收藏✨收录专栏:LeetCode 刷题日志🤝希望作者的文章能对你有所帮助,有不足的地方请在评论区留言指正,…...

单元测试实战(二)Service 的测试
为鼓励单元测试,特分门别类示例各种组件的测试代码并进行解说,供开发人员参考。 本文中的测试均基于JUnit5。 单元测试实战(一)Controller 的测试 单元测试实战(二)Service 的测试 单元测试实战&#x…...

LabVIEW和NIUSRP硬件加快了认知无线电开发
LabVIEW和NIUSRP硬件加快了认知无线电开发 对于电视频谱,主用户传输有两种类型:广播电视和节目制作和特殊事件(PMSE)设备。广播塔的位置已知,且覆盖电视传输塔(复用器)附近的某个特定地理区域(称为排除区域…...

嵌入式软件工程师面试题——2025校招社招通用(十六)
说明: 面试群,群号: 228447240面试题来源于网络书籍,公司题目以及博主原创或修改(题目大部分来源于各种公司);文中很多题目,或许大家直接编译器写完,1分钟就出结果了。但…...

白盒测试之测试用例设计方法
白盒测试之测试用例设计方法 什么是白盒测试白盒测试的特点白盒测试的设计方法静态设计方法动态设计方法语句覆盖分支(判定)覆盖条件覆盖判定条件覆盖组合覆盖路径覆盖总结 什么是白盒测试 按照测试方法分类,测试可以分为白盒测试和黑盒测试两种。 白盒测试也称结构…...

在CentOS 7上关闭SELinux
要在CentOS 7上关闭SELinux,可以按照以下步骤进行操作: 临时关闭SELinux(不建议使用): setenforce 0但是这种方式只对当前启动有效,重启系统后会失效。 2. 永久关闭SELinux: vi /etc/selinux…...

基于单片机温湿度PM2.5报警系统
**单片机设计介绍, 基于单片机温湿度PM2.5报警设置系统 文章目录 一 概要二、功能设计设计思路 三、 软件设计原理图 五、 程序六、 文章目录 一 概要 单片机温湿度PM2.5报警设置系统是一种智能化的环境检测与报警系统。它主要由单片机、传感器、液晶显示屏、蜂鸣器…...

OpenHarmony系统编译环境
1. 推荐系统Ubuntu 2204 2. 必须安装的软件 apt-get install curl build-essential gcc g make ninja-build cmake libffi-dev e2fsprogs pkg-config flex bison perl bc openssl libssl-dev libelf-dev binutils binutils-dev libdwarf-dev u-boot-tools mtd-utils cpio de…...

二十三种设计模式全面解析-职责链模式(Chain of Responsibility Pattern):解放代码责任链,提升灵活性与可维护性
在软件开发中,我们经常面临处理请求或事件的情况。有时候,我们需要将请求或事件依次传递给多个对象进行处理,但又不确定哪个对象最终会处理它。这时候,职责链模式(Chain of Responsibility Pattern)就能派上…...

通过制作llama_cpp的docker镜像在内网离线部署运行大模型
对于机器在内网,无法连接互联网的服务器来说,想要部署体验开源的大模型,需要拷贝各种依赖文件进行环境搭建难度较大,本文介绍如何通过制作docker镜像的方式,通过llama.cpp实现量化大模型的快速内网部署体验。 一、llam…...

JavaScript 异步编程
异步的概念 异步(Asynchronous, async)是与同步(Synchronous, sync)相对的概念。 在我们学习的传统单线程编程中,程序的运行是同步的(同步不意味着所有步骤同时运行,而是指步骤在一个控制流序…...

linux课程第一课------命令的简单的介绍
作者前言 🎂 ✨✨✨✨✨✨🍧🍧🍧🍧🍧🍧🍧🎂 🎂 作者介绍: 🎂🎂 🎂 🎉🎉🎉…...

XLua热更新框架原理和代码实战
安装插件 下载Xlua插件:https://github.com/Tencent/xLua 下载完成后,把Asset文件夹下的文件拖入自己的工程Asset中,看到Unity编辑器上多了个Xlua菜单,说明插件导入成功 Lua启动代码 新建一个空场景,场景中什么都不…...

Hive客户端hive与beeline的区别
hive与beeline简介 1、背景2、hive3、beeline4、hive与beeline的关系 1、背景 Hive的hive与beeline命令都可以为客户端提供Hive的控制台连接。两者之间有什么区别或联系吗? Hive-cli(hive)是Hive连接hiveserver2的命令行工具,从Hive出生就一直存在&…...

<MySQL> 什么是数据库索引?数据库索引的底层结构是什么?
目录 一、什么是数据库索引? 1.1 索引的概念 1.2 索引的特点 1.3 索引的适用场景 1.4 索引的使用 1.4.1 创建索引 1.4.2 查看索引 1.4.3 删除索引 二、数据库索引的底层结构是什么? 2.1 数据库中的 B树 长啥样? 2.2 B树为什么适合做数据库索…...