Mocking open(file_name) in unit tests

前端 未结 8 1812
慢半拍i
慢半拍i 2020-12-05 00:37

I have a source code that opens a csv file and sets up a header to value association. The source code is given below:

def ParseCsvFile(source): 
  \"\"\"Pa         


        
相关标签:
8条回答
  • 2020-12-05 01:10

    Hi I was having a similar problem, and was tearing my hair out flipping between different mocking libraries. I finally found a solution that I am happy with, and maybe it might help you? In the end I went with the Mocker library http://labix.org/mocker and here is the code for mocking open:

    from mocker import Mocker
    from StringIO import StringIO
    import __builtin__
    mocker = Mocker()
    sourceFile = 'myTestFile.txt'
    __builtin__.open = mocker.mock()
    __builtin__.open(sourceFile)
    mocker.result(StringIO('this,is,a,test,file'))
    
    <the rest of your test setup goes here>
    
    mocker.replay()
    
    ParseCsvFile(sourceFile)
    
    mocker.restore()
    mocker.verify()
    

    Incidentaly the reason I went with Mocker is because I was testing a function which used open to read a file, and then used open again to overwrite the same file with new data. What I needed to be able to do was test the case where the initial file didn't exist, so set up a mock, that threw an IOError the first time, and then worked the second time. The setup for which looked like this:

    from mocker import Mocker
    import __builtin__
    
    mocker = Mocker()
    
    mockFileObject = mocker.mock()
    __builtin__.open = mocker.mock()
    
    __builtin__.open('previousState.pkl', 'r') 
    mocker.throw(IOError('Boom'))
    
    __builtin__.open('previousState.pkl','w') 
    mocker.result(mockFileObject)
    
    <rest of test setup >
    
    mocker.replay()
    
    <test>
    
    mocker.restore() #required to restore the open method
    mocker.verify()
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-05 01:16
    >>> class A(object):
    ...     def __init__(self):
    ...         self.x = open('test.py')
    ... 
    >>> old_open = open
    >>> def open(s):
    ...     return "test\n"
    ... 
    >>> a = A()
    >>> a.x
    'test\n'
    >>> open = old_open
    >>> a = A()
    >>> a.x
    <open file 'test.py', mode 'r' at 0xb7736230>
    
    0 讨论(0)
提交回复
热议问题