简体   繁体   中英

How to mock os.environ using pytest?

I need to mock os.environ in unit tests written using the pytest framework.

Here is a dummy version of the code I want to test, located in getters.py :

import os

username = os.environ['MY_USER']
password = os.environ['MY_PASS']

def get_data(...):

    access_token = request_access_token(username, password)
    ...
    return data

and here is an example of a unit test in test_getters.py :

import pytest
import src.getters

class TestGetData(object):


    def test_something(self):

        data = src.getters.get_data(...)

        assert ...

Test collection fails with the following error:

=========================== short test summary info ============================
ERROR tests/test_getters.py - KeyError: 'MY_USER'
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.68s ===============================

I would like to be able to mock once for the whole test class if possible.

Is there some kind of a decorator I can use? Or some other recommended way of mocking os.environ?

Use monkeypatch.setenv() of Monkeypatching :

Docs:

Modifying environment variables for a test eg to test program behavior if an environment variable is missing, or to set multiple values to a known variable. monkeypatch.setenv() and monkeypatch.delenv() can be used for these patches.

Code:

import pytest
import src.getters

class TestGetData(object):


    def test_something(self):
        monkeypatch.setenv('MY_USER', 'Nanna')
        monkeypatch.setenv('MY_PASS', 'P@ssw0rd')
        data = src.getters.get_data(...)

        assert ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM