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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With