首页 > 解决方案 > 运行 pytest 作为预提交钩子 // 没有这样的文件或目录问题

问题描述

在我的 Python 项目中,我将pytest其用作pre-commit挂钩。一些测试创建和删除临时文件,当我运行pytest <test directory>. 但是,当我运行git commitpre-commit挂钩触发器时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 命令。

谢谢!

最好的,阿列克谢

标签: pythonpytestpre-commit-hookpre-commitpre-commit.com

解决方案


显示你的输出,否则我们只能猜测问题

也就是说,您可能想要使用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 的作者


推荐阅读