【问题标题】:How to Write Mock Object for tempfile NamedTemporaryFile or a file like object如何为临时文件 NamedTemporaryFile 或类似对象的文件编写模拟对象
【发布时间】:2017-06-23 00:08:21
【问题描述】:

以下是我的代码:并且需要测试 myfunction()。以及如何创建文件的模拟函数。

def myfunction(self):
    with tempfile.NamedTemporaryFile() as tf:
        f.seek(0)
        tf.write(f.read())
        tf.flush()
        ocr_content_dict = self.ocr.ocr_document(tf.name, mimetype) or ''
        ocr_content = ocr_content_dict['content']

【问题讨论】:

标签: python python-2.7 unit-testing mocking


【解决方案1】:

您可以创建一个模拟文件对象,也可以使用BytesIO / StringIO

from io import BytesIO

class MockFileObject(object):
    '''
       write mock functions for any that are needed
       DONE: read
       TODO: write
       TODO: seek
       TODO: fileno
       TODO: flush
       TODO: name

       with context manangement use the dunder enter/exit
       TODO: __enter__
       TODO: __exit__

       ... etc
    '''

    def read(self):
        ''' example mock '''
        return BytesIO('some stuff').read()

用法:

fo = MockFileObject()
with fo as f:
     print(f.read())

输出:

some stuff

【讨论】:

  • 看不懂,能不能说的更具体一些,解释一下如何模拟文件objext
  • @ChetanKabra 所有的 TODO 都是为了完全模拟文件对象而需要编写的函数。这有意义吗?
  • 好的,但是如何在 mock_test 中使用它。因为我不想模拟 tempfile.NamedTemporaryFile() 上下文管理器和 f.read() 函数调用另一个返回文件的函数
猜你喜欢
  • 2016-11-28
  • 1970-01-01
  • 2010-10-01
  • 2019-10-02
  • 1970-01-01
  • 2020-07-13
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多