DEV Community

Rich Boniface
Rich Boniface

Posted on

3

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.

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay