'pytest –version' works, but 'pytest tests' command not recognized with Bash in Github Actions

Question:

For my Python package ‘imfp’, I am doing my building and testing via ‘Github Actions’ using ‘poetry’ and pytest in a virtual environment. I’ve got the Github Actions script working successfully until the very step, when I run the tests using pytest.

Weirdly, the ‘pytest –version’ command works just fine, printing ‘pytest 7.2.2’. However, ‘pytest tests’ returns the error, ‘pytest: command not found’.

Per suggestions found in other threads on Substack, I have also tried:

py.test tests
py.test: command not found

python -m pytest tests
No module named pytest

py -m pytest tests
No module named pytest

python3 -m pytest tests
No module named pytest

Here is my Github Actions script:

name: build-test

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        python-version: ["3.11"]
        poetry-version: [latest]
        os: [windows-latest]
    defaults:
      run:
        shell: bash
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install and configure Poetry
        uses: snok/install-poetry@v1
      - name: Configure Poetry
        run: |
          poetry config virtualenvs.in-project true
      - name: Install project
        run: |
          poetry install --no-interaction
      - name: Activate venv windows
        run: |
          source .venv/scripts/activate
          pytest --version
        if: runner.os == 'Windows'
      - name: Activate venv other
        run: |
          source .venv/bin/activate
          pytest --version
        if: runner.os != 'Windows'
      - name: Run tests
        run: |
          python3 -m pytest tests/

Note that as far as I can tell, this question is not a duplicate. Most of the similar threads involve a failure of ‘pytest –version’, but that command is working in this case.

workflow logs: https://github.com/chriscarrollsmith/imfp/actions/workflows/actions.yml

Answers:

According to jobs.<job_id>.steps[*].run:

Each run keyword represents a new process and shell in the runner environment.

So, venv activated in a previous step does not remain activated in the next one.

You need to activate it again before running tests.

Answered By: Azeem

Activating a virtual environment is not always necessary. One can also directly call the binaries in the virtual environment’s binaries directory instead (Scripts on Windows and bin anywhere else). So for example: .venv/Scripts/python -m pytest.

Alternatively, since Poetry is used, one can also call poetry run python -m pytest (which is probably the best solution, stick to poetry run as long as you use Poetry).

Answered By: sinoroc