如何为临时文件NamedTemporaryFile或类似对象的文件编写模拟对象

时间:2017-06-23 00:08:22

标签: python python-2.7 unit-testing mocking

以下是我的代码:并且需要测试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']

1 个答案:

答案 0 :(得分:0)

您可以创建模拟文件对象,也可以使用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