2017-04-23 31 views
1

我知道也有類似的帖子,但我沒有找到這樣一個東西模擬文件輸入。的Python:用於測試功能

我有蟒蛇接收要讀取和處理,並返回東西文件名作爲輸入的功能,我想如果輸出爲我的功能進行測試。例如:

#main function 
def myfunction(filename): 
    f=open(filename) 

    for line in f: 
     # process data 
     pass 
    f.close() 

    return # something 

#test function for the main function 
def test_myfunction(): 
    mockfile = #mymockfile 
    assert myfunction(mockfile) == #something 

如何創建一個模擬文件來測試此功能而無需編寫讀取文件?

這是我發現模仿我需要什麼(http://www.voidspace.org.uk/python/mock/helpers.html#mock-open

回答

0

同樣的問題已經掙扎最接近的,請在下面找到我的答案。這其中大部分來自: http://omiron.ro/post/python/how_to_mock_open_file/。 我使用的Python 3.6和Py.test通過在Eclipse中的PyDev插件。

import unittest.mock as mock 
from unittest.mock import mock_open 

#main function 
def myfunction(filename): 
    f=open(filename) 
    maximum = 0 
    for line in f: 
     if maximum < len(line): 
      maximum = len(line) 
     pass 
    f.close() 
    return maximum 

#test function for the main function 
@mock.patch('builtins.open', new_callable=mock_open, create=True) 
def test_myfunction(mock_open): 
    mock_open.return_value.__enter__ = mock_open 
    mock_open.return_value.__iter__ = mock.Mock(
     return_value = iter(['12characters', '13_characters'])) 
    answer = myfunction('foo') 
    assert not answer == 12 
    assert answer == 13