git 小技巧: 通过pre-commit hook 来防止程序员把其它测试用例给禁用了


公司今天例会上说, 有一个PR几天前合进去, 结果导致CI上的测试用例都没有执行. 仔细一看, 原来是PR中不小心把 .only 提交了. 在 NodeJS的测试框架中, 我们开发的时候本地代码加上 describe.only 或者 it.only 来只运行我们关心的几个测试用例:

1
2
3
4
5
describe.only("我只关心这些测试用例, 其它的不要跑", function() {
   it("就这个", function() {
      expect(1).to.equal(1);
   });
});
describe.only("我只关心这些测试用例, 其它的不要跑", function() {
   it("就这个", function() {
      expect(1).to.equal(1);
   });
});

很有可能, 在提交的时候忘记把这些代码回退了, 更糟糕的是, 很有可能在代码审核的时候也顺利通过了, 那么CI持续集成测试的时候就只跑这些测试用例, 导致了其它的测试用例一个都没跑, 还好这次发现的及时.

我们可以通过 git 的 pre-commit 挂勾来在提交前进行一次检查, 我们可以把下面的脚本存在 代码仓库的根目录下的 ./git/hooks, 文件名为 pre-commit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Redirect output to stderr.
exec 1>&2
 
# prevent it.only or describe.only commited
if [ "$allowonlytests" != "true" ] &&
    test $(git diff --cached | grep -E "\b(it|describe).only\("  | wc -l) != 0
then
    cat <<\EOF
Error: Attempt to add it.only or describe.only - which may disable all other tests
 
If you know what you are doing you can disable this check using:
 
    git config hooks.allowonlytests true
EOF
    exit 1
fi
 
exit 0
# Redirect output to stderr.
exec 1>&2
 
# prevent it.only or describe.only commited
if [ "$allowonlytests" != "true" ] &&
    test $(git diff --cached | grep -E "\b(it|describe).only\("  | wc -l) != 0
then
    cat <<\EOF
Error: Attempt to add it.only or describe.only - which may disable all other tests
 
If you know what you are doing you can disable this check using:
 
    git config hooks.allowonlytests true
EOF
    exit 1
fi
 
exit 0

这样在 commit 的时候就会把改动的代码进行检查, 通过 grep 和正则表达式, 如果发现 it.only 或者 describe.only, 就会输出一个警告, 并且退出码设置为1这样commit 就不成功了. 这个正则表达式会忽略 行注释, 所以 //it.only 或者 //describe.only 则不会触发警告.

我们还可以通过以下设置来关闭这个检查.

1
git config hooks.allowonlytests true
git config hooks.allowonlytests true
git-pre-commit-hook git 小技巧: 通过pre-commit hook 来防止程序员把其它测试用例给禁用了 git I.T. 小技巧 程序员

git-pre-commit-hook

当然, 你还可以使用下面的 eslint 插件来防止不小心提交了不应该提交的代码:
https://www.npmjs.com/package/eslint-plugin-no-only-tests

Git 还有其它的 Hooks 检查, 比如: git 小技巧: 如何通过pre-push hooks避免向主分支提交代码?

英文: The Git Pre-Commit Hook to Avoid Pushing Only Unit Tests In NodeJs

GD Star Rating
loading...
本文一共 391 个汉字, 你数一下对不对.
git 小技巧: 通过pre-commit hook 来防止程序员把其它测试用例给禁用了. (AMP 移动加速版本)
上一篇: 英国TESCO超市有偿回收瓶子
下一篇: 英国的房屋税 Council Tax 是啥?

扫描二维码,分享本文到微信朋友圈
4fa16ecc184c4a0f7438b0d187b920e4 git 小技巧: 通过pre-commit hook 来防止程序员把其它测试用例给禁用了 git I.T. 小技巧 程序员

评论