python - 将 pytest 作为预提交钩子(Hook)运行//没有这样的文件或目录问题

标签 python pytest pre-commit-hook pre-commit pre-commit.com

在我的 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: falsealways_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/

相关文章:

python - 内省(introspection)调用函数的pytest fixture

SVN 预提交问题

git - 预提交 Hook 获取部分提交的文件列表

python - 为我的计算值制作字典

python - 如何修改基于另一个数组的numpy数组的值?

python - 按条件查找dataframe中行和列的所有索引

python - os.environ[] 从 .env 文件访问变量的 KeyError

python - 自定义 pytest junitxml 失败报告

python - 什么时候假设破折号 m 用法并避免 __init__?

git - 与手动运行相比,使用 echo -n 的预提交 Hook 在 git 运行时的行为有所不同