【问题标题】:Python: Mock Opening File, return Actual FilePython:模拟打开文件,返回实际文件
【发布时间】:2017-01-11 01:09:24
【问题描述】:

我需要测试对 gzip.open 的调用,但我需要它为它提供一个实际的测试文件,其中包含要读取的测试数据。我见过几个非常相似的问题,但没有一个能按预期工作。

这是我正在测试的代码:

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() 返回了 'MagicMock' 类型的非迭代器

我使用的是 Python 2.7。我正在为此撕毁我的头发。是我忘记尝试使用迭代器的唯一解决方案吗(实际文件可能非常大,这就是我试图避免这样做的原因?)

【问题讨论】:

    标签: python-2.7 unit-testing


    【解决方案1】:

    这是有效的:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 2015-07-26
      • 2012-04-20
      • 2023-03-09
      • 2016-02-03
      • 1970-01-01
      相关资源
      最近更新 更多