Python mock Patch os.environ and return value

前端 未结 4 1161
孤独总比滥情好
孤独总比滥情好 2020-12-05 12:46

Unit testing conn() using mock:

app.py

import mysql.connector
import os, urlparse


def conn():
    if "DAT         


        
相关标签:
4条回答
  • 2020-12-05 13:12

    You can also use something like the modified_environ context manager describe in this question to set/restore the environment variables.

    with modified_environ(DATABASE_URL='mytemp'):
        func()
    
    0 讨论(0)
  • 2020-12-05 13:17

    You can try this solution. Just call conn with a dummy argument:

    import mysql.connector
    import os, urlparse
    
    
    @mock.patch.dict(os.environ, {"DATABASE_URL": "mytemp"})
    def conn(mock_A):
        print os.environ["mytemp"]
        if "DATABASE_URL" in os.environ:
            url = urlparse(os.environ["DATABASE_URL"])
            g.db = mysql.connector.connect(
                user=url.username,
                password=url.password,
                host=url.hostname,
                database=url.path[1:],
            )
        else:
            return "Error"
    

    Or if you don't want to modify your original function try this solution:

    def func():
        print os.environ["mytemp"]
    
    
    def test_func():
        k = mock.patch.dict(os.environ, {"mytemp": "mytemp"})
        k.start()
        func()
        k.stop()
    
    
    test_func()
    
    0 讨论(0)
  • 2020-12-05 13:25

    For this, I find that pytest's monkeypatch fixture leads to better code when you need to set environment variables:

    def test_conn(monkeypatch):
        monkeypatch.setenv('DATABASE_URL', '<URL WITH CREDENTIAL PARAMETERS>')
        with patch(app.mysql.connector) as mock_mysql:
            conn()
        mock_mysql.connect.assert_called_with(<CREDENTIAL PARAMETERS>)
    
    0 讨论(0)
  • 2020-12-05 13:29

    The accepted answer is correct. Here's a decorator @mockenv to do the same.

    def mockenv(**envvars):
        return mock.patch.dict(os.environ, envvars)
    
    
    @mockenv(DATABASE_URL="foo", EMAIL="bar@gmail.com")
    def test_something():
        assert os.getenv("DATABASE_URL") == "foo"
    
    
    0 讨论(0)
提交回复
热议问题