本方法是基于pytest写的测试
一、新建脚本
创建脚本setup-pre-push.sh在项目目录下,脚本内容是:
#!/bin/bash
# 设置 pre-push 文件路径和内容
PRE_PUSH_FILE=".git/hooks/pre-push"
PRE_PUSH_CONTENT='#!/bin/bash\n\n# 添加 src 目录到 Python 模块搜索路径\nexport PYTHONPATH=/path/to/src:$PYTHONPATH\n\n# 运行 pytest 测试\npytest\n\n# 检查 pytest 结果\nif [ $? -ne 0 ]; then\n echo "Tests failed. Aborting push!"\n exit 1\nfi\n\nexit 0'
# 创建 pre-push 文件并写入内容
echo -e "$PRE_PUSH_CONTENT" > "$PRE_PUSH_FILE"
# 赋予 pre-push 文件执行权限
chmod +x "$PRE_PUSH_FILE"
echo "pre-push file has been set up successfully!"
之后运行脚本: bash setup-pre-push.sh
会在项目目录下的.git/hooks 下发现脚本创建的pre-push文件,文件内容为:
#!/bin/bash
# 添加 src 目录到 Python 模块搜索路径
export PYTHONPATH=/path/to/src:$PYTHONPATH
# 运行 pytest 测试
pytest
# 检查 pytest 结果
if [ $? -ne 0 ]; then
echo "Tests failed. Aborting push!"
exit 1
fi
exit 0
二、进行测试
git push
之后会发现:
说明设置成功。