Setup environment for pre-commit
Asked Answered
T

2

11

How can I source a bash script that contains exports for environment variables?

env.sh

...
export VARIABLE=test
...

test_file.py

...
os.environ['VARIABLE'] # Throws KeyError
...

How can I use pre-commit to run env.sh to setup an environment that the following pytest hook can use?

-   repo: local
    hooks:
    -   id: tests
        name: run tests
        entry: pytest -v
        language: system
        types: [python]
Terret answered 14/6, 2019 at 17:54 Comment(6)
entry: source env.sh && pytest -v?Muimuir
@Muimuir Fails: Executable 'source' not foundTerret
What about entry: . env.sh && pytest -v?Muimuir
@Muimuir Same as before, and if I do entry: sh env.sh && pytest -v the commit passes but no tests runTerret
I don't know what the underlying system is (and what tool is the configuration from), but another wild guess - entry: sh -c ". env.sh && pytest -v"Muimuir
pre-commit itself doesn't use shells at all, but you can use entry: bash -c '...' or entry: sh -c '...' -- another option is to look at pytest-envBrilliance
T
1

pre-commit-config

  • change language to python (optional, but it's so that pre-commit creates a venv)
  • entry - we will invoke a bash script instead of invoking pytest directly

Ex.

 - repo: local
   hooks:
   - id: tests
     name: run tests
     entry: bash tests.sh
     language: python

tests.sh

source env.sh
pytest -v .
Trichocyst answered 5/9, 2022 at 16:3 Comment(0)
Z
0

You shouldn't use pre-commit for pytest due to:

  • tests are often slow, committing should be fast
  • It would have to be a system / script hook since you'd need repository specific dependencies.

Source: https://github.com/pre-commit/pre-commit-hooks/issues/291

I think this will solve your problem: How to pass environment variables to pytest

Zebrawood answered 1/6, 2022 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.