2013-11-23 126 views
0

我想測試這種方法的變量,不過,我想需要模擬可變dirContent嘲諷使用MOX

def imageFilePaths(paths): 
    imagesWithPath = [] 
    for _path in paths: 
     try: 
      dirContent = os.listdir(_path) 
     except OSError: 
      raise OSError("Provided path '%s' doesn't exists." % _path) 

     for each in dirContent: 
      selFile = os.path.join(_path, each) 
      if os.path.isfile(selFile) and isExtensionSupported(selFile): 
       imagesWithPath.append(selFile) 
    return list(set(imagesWithPath)) 

我怎麼只使用MOX嘲笑一個變量? 這是我已經嘗試過不過來嘲笑os.listdir

def setUp(self): 
    self._filePaths = ["/test/file/path"] 
    self.mox = mox.Mox() 

def test_imageFilePaths(self): 
    filePaths = self._filePaths[0] 
    self.mox.StubOutWithMock(os,'listdir') 
    dirContent = os.listdir(filePaths).AndReturn(['file1.jpg','file2.PNG','file3.png']) 

    self.mox.ReplayAll() 

    utils.imageFilePaths(filePaths) 
    self.mox.VerifyAll() 

也試過這樣

def test_imageFilePaths(self): 
    filePaths = self._filePaths 
    os = self.mox.CreateMock('os') 
    os.listdir = self.mox.CreateMock(os) 
    dirContent = os.listdir(filePaths).AndReturn(['file1.jpg','file2.PNG','file3.png']) 
    self.mox.ReplayAll() 
    lst = utils.imageFilePaths(filePaths) 
    # self.assertEquals('/test/file/path/file1.jpg', lst[0]) 
    self.mox.VerifyAll() 

但調用方法進行測試不認識的嘲笑discontent

回答

0

通常你會不是模擬一個變量,而是模擬函數調用用於設置該變量的值。例如,在你的例子中,你會剔除os.listdir,並讓它返回一個模擬值。

# Your test file 
import os 

class YourTest(...): 

    def setUp(self): 
     self.mox = mox.Mox() 


    def tearDown(self): 
     self.mox.UnsetStubs() 

    # Your test 
    def testFoo(self): 
     self.mox.StubOutWithMock(os, 'listdir') 

     # the calls you expect to listdir, and what they should return 
     os.listdir("some path").AndReturn([...]) 

     self.mox.ReplayAll() 
     # ... the rest of your test 
+0

多數民衆贊成正是我試過,但得到了這個錯誤'UnexpectedMethodCallError:意外的方法調用。意外: - 預期:+ - Stub for <內置函數listdir> .__ call __('/') - > None + Stub for <內置函數listdir> .__ call __('/ test/file/path') - > ['file1.jpg','file2.PNG','file3.png']' –

+0

如果我把整個列表而不是'self._filePaths [0]',那麼我得到這個錯誤'UnexpectedMethodCallError:意外的方法調用。意外: - 預期:+ - Stub for <內置函數listdir> .__調用__('/ test/file/path') - >無 + Stub for <內置函數listdir> .__ call __(['/ test/file/path','test2/file/path']) - > ['file1.jpg','file2.PNG','file3.png']' –