2017-01-11 52 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