简体   繁体   English

如何使用 pytest 模拟 os.environ?

[英]How to mock os.environ using pytest?

I need to mock os.environ in unit tests written using the pytest framework.我需要在使用 pytest 框架编写的单元测试中模拟 os.environ。

Here is a dummy version of the code I want to test, located in getters.py :这是我要测试的代码的虚拟版本,位于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 :这是test_getters.py中的单元测试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?或者其他一些推荐的模拟 os.environ 的方式?

Use monkeypatch.setenv() of Monkeypatching :使用monkeypatch.setenv()的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. monkeypatch.setenv() 和monkeypatch.delenv() 可用于这些补丁。

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 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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