This website collects cookies to deliver better user experience
Testing Environment variable in pytest
Testing Environment variable in pytest
Suppose, we have a method that uses environment variables.
import os
defget_env_vars(): user = os.environ['USER'] token = os.environ['TOKEN']return user, token
We need to test this method. We will see 3 ways to test this method.
Using monkeypatch
deftest_get_env_vars_with_monkeypatch(monkeypatch): monkeypatch.setenv('USER','hasan') monkeypatch.setenv('TOKEN','xxx') u, t = get_env_vars()assert u =='hasan'assert t =='xxx'
Using unittest.mock module
from unittest import mock
deftest_get_env_vars_with_mock_module():with mock.patch.dict(os.environ,{'USER':'hasan','TOKEN':'xxx'}): u, t = get_env_vars()assert u =='hasan'assert t =='xxx'
Using pytest-env plugin
We can use this plugin to set environment variables that don't really matter to the function implementations.
Install pytest-env plugin using pip install pytest-env.
Add the following portion to pytest.ini, setup.cfg etc files:
[pytest]env=USER=hasanTOKEN=xxx
Then write test as following:
deftest_get_env_vars_with_pytest_env_plugin(): u, t = get_env_vars()assert u =='hasan'assert t =='xxx'