Search code examples
pythonunit-testingmockingstringio

Mock stdout in Python


I am new to Python unit testing, and especially Mock. How would I mock an object that I could do the following with? I just need an object that does not make the loop crash, in order to complete the test.

for ln in theMock.stdout.readlines()

I tried creating a mock by doing

Mock(stdout=Mock(readlines= Lambda: []))

and

Mock(stdout=Mock(spec=file, wraps=StringIO())

but it says that a list object has no attribute stdout.


Solution

  • How about this?

    from mock import Mock
    
    readlines = Mock(return_value=[])
    stdout = Mock(readlines=readlines)
    theMock = Mock(stdout=stdout)
    print(theMock.stdout.readlines())
    

    Output:

    []
    

    Your for loop will just skipped, since readlines() will return an empty list.