Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an environment variable in command line to pytest to test a function

Tags:

python

pytest

I have a script using os.environ.get() to get variable from command line something like JENKINS_HOST="xx" JENKINS_AUTH="xx" JENKINS_TOKEN="xx" python script.py

In script.py has a function it likes this:

def init_auth():
    login_mode = True
    JENKINS_HOST = os.environ.get("JENKINS_HOST")
    JENKINS_AUTH = os.environ.get("JENKINS_AUTH")
    JENKINS_TOKEN = os.environ.get("JENKINS_TOKEN")

when I use pytest to test the function init_auth(), how could I transfer the cli environment to this function?

like image 480
Saluton Avatar asked Sep 11 '25 16:09

Saluton


1 Answers

I'm not sure I quite understood your question.. basically, instead of retrieving values from the environment, you want to retrieve them from the CLI?

If so, one way I did that was by creating a conftest.py file in the same directory as the test and use the pytest_addoption and pytest_generate_tests hooks.

conftest.py:

def pytest_addoption(parser):
    """
    Add CLI options to `pytest` to pass those options to the test cases.
    These options are used in `pytest_generate_tests`.
    """
    parser.addoption('--jenkins-host')
    parser.addoption('--jenkins-auth')
    parser.addoption('--jenkins-token')

def pytest_generate_tests(metafunc):
    metafunc.parametrize(
        'jenkins_host, jenkins_auth, jenkins_token',
        [(
            metafunc.config.getoption('jenkins_host'),
            metafunc.config.getoption('jenkins_auth'),
            metafunc.config.getoption('jenkins_token')
        )]
    )

TestFile.py

class TestThis:
    def test_my_thing(jenkins_host, jenkins_auth, jenkins_token):
        # Do tests here

CLI

pytest TestFile.py --jenkins-host "http://my-jenkinshost.com" --jenkins-auth whatever --jenkins-token THE_TOKEN

The arguments in the test case are parametrized (the equivalent of adding the annotation @pytest.mark.parametrize(...) in pytest_generate_tests.

This works well and it's fully supported by pytest. It's a basic example as there's a lot more you can do. See here more info on how these and other hooks work.

like image 100
Joao Coelho Avatar answered Sep 13 '25 07:09

Joao Coelho