作为预先提交的钩子运行pytest //没有此类文件或目录问题

时间:2020-09-22 13:55:46

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

在我的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命令。

谢谢!

最好, 阿列克谢

1 个答案:

答案 0 :(得分:4)

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

表示,您可能要使用always_run: truepass_filenames: false -而且您的entry是伪造的,不需要将内容包装在bash中,只需直接调用可执行文件即可。将所有内容放在一起:

  - repo: local
    hooks:
      - id: pytest-check
        name: pytest-check
        entry: pytest
        language: system
        pass_filenames: false
        always_run: true

免责声明:我是预先提交的作者

相关问题