简体   繁体   English

预提交钩子单元测试

[英]Pre-Commit Hook Unit Test

I am trying to run a pre-commit hook that prevents me from committing if my unit tests don't run.我正在尝试运行一个预提交钩子,如果我的单元测试没有运行,它会阻止我提交。 Right now I have a shell script that runs the tests and my terminal tells me that they have failed, which is good.现在我有一个运行测试的 shell 脚本,我的终端告诉我它们失败了,这很好。 But I am not sure what to put in my Shell Script to actually stop my commit once my terminal detects that I have failing tests.但是,一旦我的终端检测到我的测试失败,我不确定在我的 Shell 脚本中放入什么才能真正停止我的提交。 Like this:像这样: 在此处输入图片说明

I am inclined to think that all I am missing is a simple if statement which checks if the tests fail then stop the commit and if the tests pass then complete the commit.我倾向于认为我缺少的只是一个简单的 if 语句,它检查测试是否失败然后停止提交,如果测试通过则完成提交。 But I could be completely wrong about that, and this is my first time working with shell scripts so I am not really sure how to go about doing that.但我可能完全错了,这是我第一次使用 shell 脚本,所以我不确定如何去做。 Thanks.谢谢。

You need to make sure your script exits with a non-zero exit code when the tests fail.当测试失败时,您需要确保您的脚本以非零退出代码退出。

From the Git docs:来自 Git 文档:

Exiting with a non-zero status from this script causes the git commit command to abort before creating a commit.从此脚本以非零状态退出会导致 git commit 命令在创建提交之前中止。

https://git-scm.com/docs/githooks https://git-scm.com/docs/githooks

Basically, do exit 1 if the tests fail and exit 0 otherwise.基本上,如果测试失败,则exit 1 ,否则exit 0 Right now, you're probably doing exit 0 (or just letting the script end) in all cases.现在,您可能在所有情况下都在执行exit 0 (或只是让脚本结束)。

Most likely, your unit tests are already returning a valid exit code, which you can use to determine the exit code for your script.最有可能的是,您的单元测试已经返回了一个有效的退出代码,您可以使用它来确定脚本的退出代码。

A simple way to do this is something like:一个简单的方法是这样的:

<run unit tests>
EXIT_CODE=$?
...
exit EXIT_CODE

This simple shell script in .git/hooks/pre-commit worked for me. .git/hooks/pre-commit 中的这个简单的 shell 脚本对我有用

#!/bin/sh
npm run test || exit 1

If the npm run test fails it passes the control to exit which fails with positive error code to terminate the program.如果 npm run 测试失败,它会通过控制退出退出,退出失败并显示正错误代码以终止程序。 If it passes the exit statement is never executed.如果它通过,则永远不会执行退出语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM