Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: mock file input for testing function

Tags:

I know there are similar posts, but I did not find anything like this one.

I have a function in python that receives as input the filename to be read and process and return something, and I want to test if the output for my function. Example:

#main function
def myfunction(filename):
    f=open(filename)

    for line in f:
        # process data
        pass
    f.close()

    return # something

#test function for the main function
def test_myfunction():
    mockfile = #mymockfile
    assert myfunction(mockfile) == #something

How could I create a mock file to test this function without having to write a read file?

This was the closest I found to emulate what i need (http://www.voidspace.org.uk/python/mock/helpers.html#mock-open)

like image 364
user3780518 Avatar asked Apr 23 '17 05:04

user3780518


People also ask

Can we use mock with Pytest?

Advanced: Mocking in Unit Test In pytest , mocking can replace the return value of a function within a function. This is useful for testing the desired function and replacing the return value of a nested function within that desired function we are testing.


1 Answers

Having struggled with the same question, please find my answer below. Most of this comes from: http://omiron.ro/post/python/how_to_mock_open_file/. I used Python 3.6 and Py.test through the pydev plugin in Eclipse.

import unittest.mock as mock
from unittest.mock import mock_open

#main function
def myfunction(filename):
    f=open(filename)
    maximum = 0
    for line in f:
        if maximum < len(line):
            maximum = len(line)
        pass
    f.close()
    return maximum

#test function for the main function
@mock.patch('builtins.open', new_callable=mock_open, create=True)
def test_myfunction(mock_open):
    mock_open.return_value.__enter__ = mock_open
    mock_open.return_value.__iter__ = mock.Mock(
        return_value = iter(['12characters', '13_characters']))
    answer = myfunction('foo')
    assert not answer == 12
    assert answer == 13
like image 123
Oppy Avatar answered Oct 12 '22 23:10

Oppy