DEV Community

Rich Boniface
Rich Boniface

Posted on

How to skip a pytest test when running in Github Actions

You're automatically running your project's pytest suite in Github Actions? That's great! But what if there's a test in your code that will NEVER work when it runs in Github Actions? Maybe it depends on some local resource that you have during development. Maybe it's a long running test that you don't want to chew up Github Actions time with. Whatever. You have your reasons. The point is this: You want to skip this particular test only when the test suite runs in Github Actions.

NO PROBLEM.

Github Actions has a boatload of default environment variables that we can use to check and see if we're running in Github. Here's one that looks perfect for this:

GITHUB_ACTIONS - Always set to "true" when GitHub Actions is running the workflow. You can use this variable to differentiate when tests are being run locally or by GitHub Actions.

So we just check that variable and use the handy @pytest.mark.skipif() decorator, and here's how we might skip a problematic test in Github Actions:

# test_example.py

import os
import pytest

IN_GITHUB_ACTIONS = os.getenv("GITHUB_ACTIONS") == "true"

@pytest.mark.skipif(IN_GITHUB_ACTIONS, reason="Test doesn't work in Github Actions.")
def test_example():
   # This passes locally, but not in Github Actions
   assert os.getenv('GITHUB_URL') is None
Enter fullscreen mode Exit fullscreen mode

And there you have it! It will run with your local tests, but not on Github Actions, and you don't have to think about it again.

Top comments (0)