How to pass environment variables to pytest

后端 未结 8 730
小鲜肉
小鲜肉 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 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

提交回复
热议问题