2

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']
jmunsch
  • 22,771
  • 11
  • 93
  • 114
Chetan Kabra
  • 353
  • 5
  • 10
  • Does this answer your question? [Python: Mocking a context manager](https://stackoverflow.com/questions/28850070/python-mocking-a-context-manager) – gerrit Apr 22 '20 at 15:27

1 Answers1

-2

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
jmunsch
  • 22,771
  • 11
  • 93
  • 114
  • not able to understand, can you be more specific and expalin how to mock the file objext – Chetan Kabra Jun 26 '17 at 18:07
  • @ChetanKabra all of the TODOs are functions that would need to be written in order to fully mock a file object. does this make sense? – jmunsch Jun 26 '17 at 18:18
  • ok got it but how to use this in mock_test. because I dont want to mock the tempfile.NamedTemporaryFile() context manager and f.read() function calls another function which return file – Chetan Kabra Jun 27 '17 at 00:05