在我的 Python 项目中,我使用 pytest
作为 pre-commit
钩。一些测试创建和删除临时文件,当我运行时一切正常 pytest <test directory>
.但是,当我运行 git commit
时和 pre-commit
Hook 触发器 pytest
, 一些测试失败是因为 FileNotFoundError: [Errno 2] No such file or directory: '<file name>'
.我的印象是,当许多文件已更改且位于暂存区域时,会发生这种情况(对于 1-2 个文件,我没有观察到此问题)。这是我的 pytest
部分来自 .pre-commit-config.yaml
:
- repo: local
hooks:
- id: pytest-check
name: pytest-check
entry: bash -c 'pytest'
language: system
输出如下所示:pytest-check.............................................................Failed
- hook id: pytest-check
- exit code: 1
tests/utils/test_application.py F [ 91%]
tests/utils/test_image_io.py .FFF......... [100%]
==================================== ERRORS ====================================
_ ERROR at teardown of test_calling_with_nonexisting_parameter[--non_existing 1337-hm] _
def teardown_module() -> None:
> os.remove(OUTPUT_FILE)
E FileNotFoundError: [Errno 2] No such file or directory: 'output.png'
tests/bdd/step_defs/test_runner_steps.py:98: FileNotFoundError
当我从控制台运行 pytest 时不会发生这种情况。与
pass_filenames: false
和 always_run: true
错误不再出现: - repo: local
hooks:
- id: pytest-check
name: pytest-check
entry: pytest
language: system
pass_filenames: false
always_run: true
关于用 bash 包装东西,我仍在为 pylint
做这件事: - repo: local
hooks:
- id: pylint-check
name: pylint-check
entry: bash -c 'find . -name "*.py" | xargs pylint'
language: system
types: [python]
pass_filenames: false
always_run: true
有没有更好的解决方案? pylint
不支持无限深度的递归,因此我需要一个 bash 命令。谢谢!
最好的事物,
阿列克谢
最佳答案
显示您的输出,否则我们只能猜测问题
也就是说,您可能想使用 always_run: true
和 pass_filenames: false
-- 还有你的 entry
是假的,不需要用 bash 包装东西,直接调用可执行文件即可。把所有这些放在一起:
- repo: local
hooks:
- id: pytest-check
name: pytest-check
entry: pytest
language: system
pass_filenames: false
always_run: true
免责声明:我是 pre-commit 的作者
关于python - 将 pytest 作为预提交钩子(Hook)运行//没有这样的文件或目录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64011304/