Below is my code : and need to test myfunction(). and how to create mock function of file.
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']
You can create a mock file object, or you could also use 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()
Usage:
fo = MockFileObject()
with fo as f:
print(f.read())
output:
some stuff
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.