Mocking open(file_name) in unit tests

前端 未结 8 1832
慢半拍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'))
    
    
    
    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)
    
    
    
    mocker.replay()
    
    
    
    mocker.restore() #required to restore the open method
    mocker.verify()
    

    Hope this helps!

提交回复
热议问题