简介:Sharness 是一个用 Shell 脚本来编写测试用例的测试框架。本文将详细介绍 Sharness 的结构及测试用例的编写格式,以及语法规范和技巧,教大家如何使用 Sharness 编写测试用例,同时还分享了 Sharness 的扩展功能和项目实战。

参与过 Git 项目的测试用例开发,为其测试框架的简洁、高效而折服。曾经尝试将 Git 测试用例用于其他项目:《复用 git.git 测试框架》[1]。不过从 Git 项目中剥离测试用例框架还是挺费事的。
一次偶然的机会发现已经有人(Christian Couder:Gitlab 工程师,Git项目的领导委员会成员之一)已经将 Git 的测试用例框架剥离出来, 成为独立的开源项目 Sharness。
有了 Sharness,写测试用例不再是苦差事。
一 Sharness 是什么?
- Sharness 是一个用 Shell 脚本来编写测试用例的测试框架。
- 可以在 Linux、macOS 平台运行测试用例。
- 测试输出符合 TAP(test anything protocol),因此可以用 sharness 自身工具或 prove 等 TAP 兼容测试夹具(harness)运行。
- 是由Junio在2005年为Git项目开发的测试框架,由 Christian Couder (chriscool) 从 Git 中剥离为独立测试框架。
- 地址:https://github.com/chriscool/sharness
二 Sharness 测试框架的优点
简洁
如果要在测试用例中创建/初始化一个文件(内容为 “Hello, world.”), 看看 sharness 实现起来有多么简单:
cat >expect <<-EOF
Hello, world.
EOF
如果要对某应用(hello-world)的输出和预期的 expect 文件进行比较, 相同则测试用例通过,不同则展示差异。测试用例编写如下:
test_expect_success “app output test” ‘
cat >expect <<-EOF &&
Hello, world.
EOF
hello-world >actual &&
test_cmp expect actual
‘
调试方便
每个测试用例脚本可以单独执行。使用 -v 参数,可以显示详细输出。使用 -d 参数,运行结束后保留用例的临时目录。
可以在要调试的test case后面增加 test_pause 语句,例如:
test_expect_success “name” ‘
<Script…>
‘
test_pause
test_done
然后使用 -v 参数运行该脚本,会在 test_pause 语句处中断,进入一个包含 sharness 环境变量的子 Shell 中,目录会切换到测试用例单独的工作区。调试完毕退出 Shell 即返回。
三 Git 项目的测试框架结构
Sharness 源自于 Git 项目的测试用例框架。我们先来看看 Git 项目测试框架的结构。

Git 项目测试相关文件
- 待测应用放在项目的根目录。例如 Git 项目的待测应用: git 和 git-receive-pack 等。
- 测试框架修改 PATH 环境变量,使得测试用例在调用待测应用(如 git 命令)的时候,优先使用项目根目录下的待测应用。
- 测试脚本命名为 tNNNN-.sh,即以字母 t 和四位数字开头的脚本文件。
- 每一个测试用例在执行时会创建一个独立的临时目录,例如 trash directory.t5323-pack-redundant。测试用例执行成功,则该目录会被删除。
相关代码参见[2]。
四 Git 测试脚本的格式
以如下测试脚本为例[3]:
(1)在文件头,定义 test_description 变量,提供测试用例的简单说明,通常使用一行文本。本测试用例较为复杂,使用了多行文本进行描述。
#!/bin/sh
#
# Copyright (c) 2018 Jiang Xin
#
test_description='Test git pack-redundant
In order to test git-pack-redundant, we will create a number of objects and
packs in the repository `master.git`. The relationship between packs (P1-P8)
and objects (T, A-R) is showed in the following chart. Objects of a pack will
be marked with letter x, while objects of redundant packs will be marked with
exclamation point, and redundant pack itself will be marked with asterisk.
| T A B C D E F G H I J K L M N O P Q R
----+--------------------------------------
P1 | x x x x x x x x
P2* | ! ! ! ! ! ! !
P3 | x x x x x x
P4* | ! ! ! ! !
P5 | x x x x
P6* | ! ! !
P7 |

本文深入解析Sharness,一种用于Shell脚本测试的框架,介绍了其结构、语法规范、技巧及实战应用,适合Linux和macOS平台,输出符合TAP标准。
最低0.47元/天 解锁文章
4048





