How to pass environment variables to pytest

后端 未结 8 709
小鲜肉
小鲜肉 2020-12-05 01:48

Before I start executing the tests in my Python project, I read some environment variables and set some variables with these values read. My tests will run on the desired en

相关标签:
8条回答
  • 2020-12-05 01:54

    Run export inside a subshell (enclosing parenthesis) not to mess up local environment. Supply export with parameters from .env file.

    (export $(xargs < .env); pytest -svvvx api)

    0 讨论(0)
  • 2020-12-05 01:56

    Following the idea provided by @tutuDajuju using pytest-env - an alternative would be to write a custom plugin leveraging pytest_load_initial_conftests. Might be useful especially when you don't want or can't install external dependencies.

    Here's a quick example:

    Project structure

    .
    ├── __init__.py
    ├── pytest.ini
    ├── script.py
    └── tests
        ├── __init__.py
        ├── plugins
        │   ├── __init__.py
        │   └── env_vars.py
        └── test_script.py
    

    script.py

    import os
    
    FOOBAR = os.environ.get("FOOBAR")
    
    
    def foobar():
        return FOOBAR
    

    test_script.py

    from script import foobar
    
    
    def test_foobar():
        assert foobar() == "foobar"
    

    pytest.ini

    [pytest]
    addopts = -p tests.plugins.env_vars
    

    env_vars.py

    import os
    
    import pytest
    
    
    @pytest.hookimpl(tryfirst=True)
    def pytest_load_initial_conftests(args, early_config, parser):
        os.environ["FOOBAR"] = "foobar"
    

    Example run:

    $ python -m pytest tests -v
    ========= test session starts =========
    platform darwin -- Python 3.8.1, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 -- 
    rootdir: /Users/user/pytest_plugins, inifile: pytest.ini
    collected 1 item
    
    tests/test_script.py::test_foobar PASSED                                                                                               [100%]
    
    ========= 1 passed in 0.01s =========
    
    0 讨论(0)
  • 2020-12-05 01:58

    In addition to other answers. There is an option to overwrite pytest_generate_tests in conftest.py and set ENV variables there.

    For example, add following into conftest.py:

    import os
    
    def pytest_generate_tests(metafunc):
        os.environ['TEST_NAME'] = 'My super test name| Python version {}'.format(python_version)
    

    This code will allow you to grab TEST_NAME ENV variable in your tests application. Also you could make a fixture:

    import os
    import pytest
    
    @pytest.fixture
    def the_name():
        return os.environ.get('TEST_NAME')
    

    Also, this ENV variable will be available in your application.

    0 讨论(0)
  • 2020-12-05 02:03

    I needed to create a pytest.ini file and pass the environment variables to the pytest command. E.g:

    In the pytest.ini file I set an empty value because it is overwritten by whatever you pass to the command line command:

    [pytest]
    MY_ENV_VAR=
    

    Command line, with the actual value set:

    $ MY_ENV_VAR=something pytest -c pytest.ini -s tests/**
    

    I don't know why does it work like this. I just found out that it works as a result of mere trial and error, because the other answers didn't help me.

    0 讨论(0)
  • 2020-12-05 02:14
    1. I use monkey patch when I don't load environment variable variable outside function.
    import os
    
    # success.py
    def hello_world():
        return os.environ["HELLO"]
    
    # fail.py
    global_ref = os.environ["HELLO"] # KeyError occurs this line because getting environment variable before monkeypatching
    
    def hello_world():
        return global_ref
    
    # test.py
    def test_hello_world(monkeypatch):
        # Setup
        envs = {
            'HELLO': 'world'
        }
        monkeypatch.setattr(os, 'environ', envs)
    
        # Test
        result = hello_world()
    
        # Verify
        assert(result == 'world')
    
    1. If you use PyCharm you can set environment variables, [Run] -> [Edit Configuration] -> [Defaults] -> [py.tests] -> [Environment Variables]

    enter image description here

    0 讨论(0)
  • 2020-12-05 02:18

    Another alternative is to use the pytest-env plugin. It can be configured like so:

    [pytest]
    env = 
        HOME=~/tmp
        D:RUN_ENV=test
    

    the D: prefix allows setting a default value, and not override existing variables passed to py.test.

    Note: you can explicitly run pytest with a custom config, if you only sometimes need to run a specialized environment set up:

    pytest -c custom_pytest.ini
    

    If you use PyCharm vs pytest-dotenv, this may be helpful

    0 讨论(0)
提交回复
热议问题