Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest skip test condition depending on environment

In my scripts using pytest framework and in conftest.py I have a parser that gets the environment value from command line so the tests know in which environment it needs to run.

def pytest_addoption(parser): # obtiene el valor de CLI    
parser.addoption("--env")

--

@pytest.fixture()
def environment(env):
if env == 'DEV':
    entorno = 'DEV'
elif env == 'TE':
    entorno = 'TE'
elif env == 'PROD':
    entorno = 'PROD'
else:
    entorno = 'UAT'
return entorno

I have some tests that should never run in PROD, is there a way to make a mark or a skip condition with pytest that checks if env variable is "PROD" shouldn't run? I was wondering if it's possible to get the environment value before the test start running so I could add a @pytest.mark.skipif(env=="PROD") at the top of the tests. The only way I found is to add an if condition inside the tests like this but I don't this it's the best way:

@pytest.mark.parametrize('policy_number', policy_list)
def test_fnol_vida_fast(self, setUp, environment, request, policy_number):
    try:
        if self.entorno != 'PROD':
            ###################
            Script Script Script
            ###################
        else:
            pytest.skip('Scripts FNOL don't run in PROD')
    except Exception as e:
        self.logger.error("******************* test_fnol_vida_fast (" + str(policy_number) + ") FAILED *******************")
        self.commons.take_screenshot(request.node.name)
        raise e
    finally:
        self.driver.close()
        self.driver.quit()
like image 413
JulianC Avatar asked Mar 22 '26 22:03

JulianC


1 Answers

Try something like that:

import os
import pytest


def requires_env(*envs):
    env = os.environ.get(
        'ENVIRONMENT', 'test'
    )

    return pytest.mark.skipif(
        env not in list(envs),
        reason=f"Not suitable envrionment {env} for current test"
    )

and use like that:

@requires_env("test", "stag")
def test_1():
   assert 1 == 1

works for me perfectly

btw you can removed step with converting string to list and compare environments like env == env

like image 190
Vova Avatar answered Mar 24 '26 12:03

Vova



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!