2017-01-11 53 views
0

我需要測試對gzip.open的調用,但我需要它提供一個實際測試文件,其中包含測試數據以供讀取。我見過幾個非常類似的問題,但沒有一個按預期工作。Python:模擬打開文件,返回實際文件

這是代碼我測試:由於代碼會將文件當作一個迭代器,但沒有討論的解決方法已經爲工作

with gzip.open(local_file_path,'r') as content: 
    for line in content: 
     try: 
      if line.startswith('#'): 
       continue 
      line_data = line.split('\t') 
      request_key = line_data[LINE_FORMAT['date']] 
      request_key += '-' + line_data[LINE_FORMAT['time']][:-3] 
      request_key += '-' + line_data[LINE_FORMAT['source_ip']] 
      if request_key in result.keys(): 
       result[request_key] += 1 
      else: 
       result[request_key] = 1 
      num_requests += 1 

     except Exception, e: 
      print ("[get_outstanding_requesters] \t\tError to process line: %s"%line) 

我認爲這個問題是有關問題的討論here我。

我試過這個變化:

test_data = open('test_access_log').read() 
m = mock.mock_open(read_data=test_data) 
m.return_value.__iter__ = lambda self:self 
m.return_value.__next__ = lambda self: self.readline() 
with mock.patch('gzip.open', m): 
    with gzip.open('asdf') as f: 
     for i in f: 
     print i 

,這導致:

TypeError: iter() returned non-iterator of type 'MagicMock'

我使用Python 2.7。我正在爲這件事撕掉頭髮。是我忘了嘗試使用迭代器唯一的解決方案(實際的文件可能會非常大,這就是爲什麼我想避免這樣做?)

回答

0

這是工作:

import unittest 
import mock 

test_data = open('test_access_log').read() 
m = mock.mock_open(read_data=test_data) 
m.return_value.__iter__.return_value = test_data.splitlines() 
with mock.patch('gzip.open', m): 
    with gzip.open('test_access_log') as f: 
    for i in f: 
     print i 

感謝bash-shell.net