栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用两个不同的文件在类中的Python模拟内置“打开”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用两个不同的文件在类中的Python模拟内置“打开”

您必须使用

side_effect
修补
open
对象(
mock_open
)的属性,并且不要忘记设置
return_value
for
__exit__
方法。

@patch('__builtin__.open', spec=open)def test_interface_mapping(self, mock_open):    handle1 = MagicMock()    handle1.__enter__.return_value.__iter__.return_value = ('aa', 'bb')    handle1.__exit__.return_value=False    handle2 = MagicMock()    handle2.__enter__.return_value.__iter__.return_value = ('AA', 'BB')    handle2.__exit__.return_value=False    mock_open.side_effect = (handle1, handle2)    with open("ppp") as f:        self.assertListEqual(["aa","bb"],[x for x in f])    with open("ppp") as f:        self.assertListEqual(["AA","BB"],[x for x in f])

[编辑]当在contextlib中使用时,
我发现一种更为优雅的方法来[模拟内置的“打开”功能

所以你可以重写测试像

@patch('__builtin__.open', new_callable=mock_open, read_data="aanbb")def test_interface_mapping_new(self, mo):    handlers = (mo.return_value,mock_open(read_data="AAnBB").return_value,)    mo.side_effect = handlers    with open("ppp") as f:        self.assertEqual("aanbb",f.read())    with open("ppp") as f:        self.assertEqual("AAnBB",f.read())

从python 3.4开始,您还可以使用readline(),readlines()而不模拟其他任何东西。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610892.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号