python模拟:如何多次返回os.popen类型

问题描述 投票:0回答:1

下面是我从主要代码中提取的样本

output = os.popen(". oraenv; echo $PATH; echo $ORACLE_BASE; echo $ORACLE_HOME").read()
print output
output1 = os.popen("some other command").read()
print output1

我正在上面编写模拟代码,因为使用了read()函数,因此返回值应为os.popen类型,如下所示

@patch('os.popen', return_value=(os.popen('ls -la')))
def test_main_code(self, popen)
    some code......

由于os.popen使用了两次,如何修改我的模拟代码以使output1也使用return_value。截至目前,output1变为空白。我已经尝试过side_effect来遍历值,但是值不是字符串,而是os.popen类型。

popen.side_effect = ["os.popen('ls -la')","os.popen('ls -la')"]
python mocking popen
1个回答
0
投票

副作用选项是您需要的,但诀窍是每次调用它时,都使用原始的popen生成有效的输出:

from os import popen

with mock.patch("os.popen", side_effect=lambda x: popen("ls -la")) as p:                                   
    output = os.popen(". oraenv; echo $PATH; echo $ORACLE_BASE; echo $ORACLE_HOME").read()
    print(output)
    output1 = os.popen("some other command").read()
    print(output1)
© www.soinside.com 2019 - 2024. All rights reserved.