7

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()
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
JulianC
  • 101
  • 1
  • 10
  • 2
    take a look at https://stackoverflow.com/questions/28179026/how-to-skip-a-pytest-using-an-external-fixture – apr_1985 Apr 06 '21 at 14:42
  • This totally works, thanks. Not sure how to select your reply as the solution for my question – JulianC Apr 06 '21 at 15:04
  • Sadly comments cant be selected as answers. But as I only pointed to another post then upvote the answer you used on that thread :) – apr_1985 Apr 06 '21 at 15:24

2 Answers2

13

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

Vova
  • 3,117
  • 2
  • 15
  • 23
3
@pytest.mark.skipif(
    os.getenv("ENVIRONMENT") == None,
    reason="No way of currently test this locally",
)
cogito
  • 31
  • 1