当我尝试模拟 open 方法时,我遇到了问题。请找到示例代码:
import glob
import re
#from __builtin__ import open
class DiskManager:
def __init__(self):
print("Called init method")
def __get_xyz_from_serial(self, serial):
for host in glob.glob("dir/*/host"):
for target in glob.glob(host + "/target*/*/filename"):
try:
with open(target) as f:
serial_num = f.read().strip()
except:
print("Failed to read : %s " % target)
continue
serial_num = (unicode(("".join(i for i in serial_num if (32 < ord(i) < 127 )))
.encode("utf8")))
if(serial == serial_num):
host_num = re.split(r"(\d+)", host)[1]
return host_num
print("No host detected")
return None
测试方法 :
# - *- coding: utf- 8 - *-i
from mox import Mox, IgnoreArg, Func, Comparator, StrContains
from mock import patch, Mock, mock_open
import unittest
#import disk_manager as disk_mgr
from disk_manager import DiskManager
import __builtin__
import glob
import StringIO
class DiskManagerTest(unittest.TestCase):
def setUp(self):
self.mox = Mox()
def tearDown(self):
self.mox.UnsetStubs()
self.mox.ResetAll()
def test_hba_serial_using_mox(self):
my_text = "¥C010"
disk_mgr = DiskManager()
#self.mox.StubOutClassWithMocks(disk_mgr,"DiskManager")
#self.mox.StubOutWithMock(disk_mgr, "_DiskManager__get_xyz_from_serial")
self.mox.StubOutWithMock(glob,"glob")
directory_list = ['dir1','dir2']
glob.glob("dir/*/host").AndReturn(directory_list)
file_list = ['file3','file2']
#glob.glob(directory_list[0]+ "/target*/*/filename").AndReturn('file1')
#glob.glob(directory_list[1]+ "/target*/*/filename").AndReturn('file2')
file3 = glob.glob(directory_list[0]+ "/target*/*/filename").AndReturn(file_list)
file4 = glob.glob(directory_list[1]+ "/target*/*/filename").AndReturn(file_list)
print(file3)
my_text = "AAAAAA"
self.mox.ReplayAll()
self.assertEqual(disk_mgr._DiskManager__get_xyz_from_serial("AAAAAA"), 'file3')
self.mox.VerifyAll()
对于模拟开放方法,我尝试过:
self.mox.StubOutWithMock(__builtin__, 'open')
但这并没有解决问题。我收到此错误:
File "/usr/lib64/python2.7/linecache.py", line 127, in updatecache
with open(fullname, 'rU') as fp:
有人可以指导我模拟文件打开的正确过程。我试过这些组合:
self.mox.StubOutWithMock(__builtin__, 'open')
#self.mox.StubOutWithMock(fl, "close")
# f1 = self.mox.CreateMockAnything(file)
# self.mox.StubOutWithMock(fl, "read")
#__builtin__.__call__(IgnoreArg()).AndReturn(f1)
#open(file_path).AndReturn("")
#__builtin__.open('file3', 'r').AndReturn(f1)
# f1.read().AndReturn("C010")
#op.open('file1', 'a').AndReturn(f1)
# fl.__enter__().AndReturn("010")
# f1.read().AndReturn("C010")
# fl.__exit__(IgnoreArg(), IgnoreArg(), IgnoreArg())
# f1.close()
#open('file1', 'r').AndReturn(StringIO("fake file content"))
#open('file2', 'r').AndReturn(StringIO("fake file content"))
#open('file3', 'r').AndReturn(StringIO("C010"))
任何见解/解决方案将不胜感激。