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

:私は、Python 2.7を使用してい

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

。私はこの上に私の髪を裂いている。イテレータを使用しようとしていることを忘れて私の唯一の解決策である(実際のファイルは、私がそうすることを回避しようとしている理由である、非常に大きくなることができますか?)

答えて

0

これは働いている:bash-shell.net

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 

感謝を

関連する問題