Mock返回Mock对象而不是返回值

2024-05-14 14:05:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我嘲笑了以下函数操作系统获取环境,但模拟对象本身将返回,而不是获取我指定的返回值。我做错什么了?你知道吗

    @staticmethod
def setup_api_key():
    load_dotenv()  # loading apikey and secret into PATH Variables
    api = os.getenv('APIKEY')
    secret = os.getenv('SECRET')
    return api, secret

测试如下所示:

    def test_setup_api_key(self):
    with patch('os.getenv') as mocked_getenv:
        mocked_getenv = Mock()
        mocked_getenv.return_value = '2222'
        result = Configuration.setup_api_key()
        self.assertEqual(('2222', '3333'), result)

Tags: 对象key函数selfapisecretreturn环境
1条回答
网友
1楼 · 发布于 2024-05-14 14:05:21

当您以上下文管理器的方式使用patch时,您得到的对象(mocked_getenv)已经是Mock对象,因此您不必重新创建它:

def test_setup_api_key(self):
    with patch('os.getenv') as mocked_getenv:
        mocked_getenv.return_value = '2222'
        result = Configuration.setup_api_key()
        self.assertEqual(('2222', '3333'), result)

通过在创建上下文管理器时直接提供返回值,可以简化此代码:

def test_setup_api_key(self):
    with patch('os.getenv', return_value='2222') as mocked_getenv:
        result = Configuration.setup_api_key()
        self.assertEqual(('2222', '3333'), result)

相关问题 更多 >

    热门问题