golang 测试工具的go test的使用 go语言单元测试的编写

mudssky · · 363 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

​ 当我们写好一段代码,就要进行测试,以保证代码的正确性,如果我们不写测试,而是每次把整个项目运行一遍,一方面,运行消耗的资源会更大.另一方面,项目的主要部分可能还没有完成,你本来就要单独写一个文件来进行测试. 总不能几千行代码全部写完再运行看效果.

​ 比如说我现在,写一个视频网站爬虫类的项目,需要把解析下载地址,和视频信息的部分抽象出来, 然后主函数要写命令行解析部分的代码,还有就是多线程下载器部分的代码.首先写的是视频解析部分的代码, 基本上是顺序式执行的代码,首先就是把json解析成结构体,这步做完就要检查一下解析的对不对,因为这步解析错了不修改过来的话,后面也是跟着错.

​ 说下面一行代码,实际上是对bilibili番剧页面返回的json信息进行解析,在golang里面只需要把结构体定义好,调用Unmarshal方法就能把json字符串里的数据解析到结构体,其中遇到解析错误的时候, 比如说json中带双引号""的是字符串类型,但是我们定义结构体的时候定义成int类型,就会发生解析错误,后面的内容就不会继续解析下去了

package bilibili
func getBugumiDataJSON(bugumiHTML string) (data bangumiData, err error) {
    dataString := utils.MatchOneOf(bugumiHTML, `window.__INITIAL_STATE__=(.+?);\(function`)[1]
    err = config.JSON.Unmarshal([]byte(dataString), &data)
    return
}

​ 编写测试的时候我们只需要在同一目录下创建 包名_test.go 的文件,然后里面以Test_开头的函数是对下划线后面的函数的测试函数.

​ 另外还有两种前缀 Benchmark和Example 这里先不讨论.

​ 我们对那个函数编写测试,测试函数需要传入一个*testing.T类型的参数,里面有很多错误输出和其他测试相关的代码,用这个错误输出就能被go test 工具解析到了.

package bilibili
func TestGetBangumiDataJSON(t *testing.T) {
    url := "https://www.bilibili.com/bangumi/play/ep341211"
    res, err := req.Get(url, reqHeader)
    if err != nil {
        t.Error("请求页面失败", url, err)
    }
    data, err := getBangumiDataJSON(res.String())
    if err != nil {
        t.Errorf("解析结构体出错%s \n", err)
    }
    t.Logf("%+v", data)
}

在当前目录下命令行执行 go test -v 即可看到运行结果,

Test_包名的函数是主函数,可以等整个包完成后在这个函数里写最后的测试内容.

可以-run+正则表达式字符串匹配运行的测试函数.

下面翻译go test工具的帮助文档(go help test):

usage: go test [build/test flags] [packages] [build/test flags & test binary flags]

​ go test 重新编译每个包文件名符合*_test.go的go文件

​ 这些额外的文件包含了测试函数,benchmark函数还有example函数, 运行go help testfunc 查看更多消息

​ 每个包都会执行独立的测试文件,即包名_test.go,以_.开头的文件将被忽略掉

​ test后缀的包将作为一个独立的包被编译,和 main test函数一起运行

​ test工具会忽略文件名为 testdata的文件夹,如果你有一些辅助文件建议放到这个文件夹里

​ 当编译test的二进制文件的时候会使用go vet定位问题,如果发现错误,go test 会报告错误,并且停止运行这个测试,只有部分高可靠性的包会被go vet使用 That subset is: 'atomic', 'bool', 'buildtags', 'errorsas','ifaceassert', 'nilfunc', 'printf', and 'stringintconv'.

你可以查看相关帮助文档 运行go doc cmd/vet

​ 所有测试输出和总结会被打印到go 标准输出, 因为标准错误流会被用于打印编译测试文件时的错误.

​ go test运行在两种不同的模式上.

  1. 第一种 本地文件夹模式,当go test 没有pakage参数的情况下运行(for example, 'go test' or 'go
    test -v'),此时 go test 会从当前文件夹下找测试文件运行.在这个模式下 caching不能使用,在package tese 结束之后,go test打印一行总结,表明测试结果 ok 或者fail, 包名,和经过的时间

  2. 第二种 package list 模式,当go test 在特定包参数下运行(for example 'go test math', 'go
    test ./...', and even 'go test .') 在这种模式下,go test会去找匹配的包列表,当测试通过的时候,只打印一行ok ,但是当测试失败的时候,会打印所有测试输出

    如果以-bench 带有-v启动,go test会打印所有输出,即使通过了测试.为了显示需求的benchmark结果和verbose 详细的日志信息. 当列表里的包的package test都结束,输出也被打印,如果有package出现失败信息,最后会打印一个 FAIL.

    只有在包列表模式下,go test 会缓存成功的包测试结果,避免不必要的重复测试,当测试结果能从缓存中恢复时,go test会重新显示一遍之前的输出,而不是重新进行测试文件的编译,当缓存调用发生的时候,go test 会打印(cached) 取代执行时间.

    缓存匹配的规则是调用了相同的test文件,并且命令行参数是一些可以缓存的参数 包括 -cpu, -list,
    -parallel, -run, -short, and -v, 如果出现这些以外的参数,结果不会被缓存,如果你不想使用缓存,建议使用一些不可缓存的参数,最通用的取消缓存的做法是使用-count=1参数,test在根目录打开文件,或者查询环境变量的情况,只有这些参数没有发生变化的时候会被缓存匹配.

    一个缓存的测试结果会被当成执行时间为0,所以一个成功的包测试结果会重复使用 无视-timeout参数

'Go test' recompiles each package along with any files with names matching
the file pattern "*_test.go".
These additional files can contain test functions, benchmark functions, and
example functions. See 'go help testfunc' for more.
Each listed package causes the execution of a separate test binary.
Files whose names begin with "_" (including "_test.go") or "." are ignored.

Test files that declare a package with the suffix "_test" will be compiled as a
separate package, and then linked and run with the main test binary.

The go tool will ignore a directory named "testdata", making it available
to hold ancillary data needed by the tests.

As part of building a test binary, go test runs go vet on the package
and its test source files to identify significant problems. If go vet
finds any problems, go test reports those and does not run the test
binary. Only a high-confidence subset of the default go vet checks are
used. That subset is: 'atomic', 'bool', 'buildtags', 'errorsas',
'ifaceassert', 'nilfunc', 'printf', and 'stringintconv'. You can see
the documentation for these and other vet tests via "go doc cmd/vet".
To disable the running of go vet, use the -vet=off flag.

All test output and summary lines are printed to the go command's
standard output, even if the test printed them to its own standard
error. (The go command's standard error is reserved for printing
errors building the tests.)

Go test runs in two different modes:

The first, called local directory mode, occurs when go test is
invoked with no package arguments (for example, 'go test' or 'go
test -v'). In this mode, go test compiles the package sources and
tests found in the current directory and then runs the resulting
test binary. In this mode, caching (discussed below) is disabled.
After the package test finishes, go test prints a summary line
showing the test status ('ok' or 'FAIL'), package name, and elapsed
time.

The second, called package list mode, occurs when go test is invoked
with explicit package arguments (for example 'go test math', 'go
test ./...', and even 'go test .'). In this mode, go test compiles
and tests each of the packages listed on the command line. If a
package test passes, go test prints only the final 'ok' summary
line. If a package test fails, go test prints the full test output.
If invoked with the -bench or -v flag, go test prints the full
output even for passing package tests, in order to display the
requested benchmark results or verbose logging. After the package
tests for all of the listed packages finish, and their output is
printed, go test prints a final 'FAIL' status if any package test
has failed.

In package list mode only, go test caches successful package test
results to avoid unnecessary repeated running of tests. When the
result of a test can be recovered from the cache, go test will
redisplay the previous output instead of running the test binary
again. When this happens, go test prints '(cached)' in place of the
elapsed time in the summary line.

The rule for a match in the cache is that the run involves the same
test binary and the flags on the command line come entirely from a
restricted set of 'cacheable' test flags, defined as -cpu, -list,
-parallel, -run, -short, and -v. If a run of go test has any test
or non-test flags outside this set, the result is not cached. To
disable test caching, use any test flag or argument other than the
cacheable flags. The idiomatic way to disable test caching explicitly
is to use -count=1. Tests that open files within the package's source
root (usually $GOPATH) or that consult environment variables only
match future runs in which the files and environment variables are unchanged.
A cached test result is treated as executing in no time at all,
so a successful package test result will be cached and reused
regardless of -timeout setting.

In addition to the build flags, the flags handled by 'go test' itself are:

        -args
            Pass 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.

        -c
            Compile 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 xprog
            Run the test binary using xprog. The behavior is the same as
            in 'go run'. See 'go help run' for details.

        -i
            Install packages that are dependencies of the test.
            Do not run the test.

        -json
            Convert test output to JSON suitable for automated processing.
            See 'go doc test2json' for the encoding details.

        -o file
            Compile the test binary to the named file.
            The test still runs (unless -c or -i is specified).

The test binary also accepts flags that control execution of the test; these
flags are also accessible by 'go test'. See 'go help testflag' for details.

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:mudssky

查看原文:golang 测试工具的go test的使用 go语言单元测试的编写

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077

363 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传