Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to return a tuple when mocking a function

I'm trying to get comfortable with mocking in Python and I'm stumbling while trying to mock the following function.

helpers.py

from path import Path

def sanitize_line_ending(filename):
    """ Converts the line endings of the file to the line endings
        of the current system.
    """
    input_path = Path(filename)

    with input_path.in_place() as (reader, writer):
        for line in reader:
            writer.write(line)

test_helpers.py

@mock.patch('downloader.helpers.Path')
def test_sanitize_line_endings(self, mock_path):
    mock_path.in_place.return_value = (1,2)
    helpers.sanitize_line_ending('varun.txt')

However I constantly get the following error:

ValueError: need more than 0 values to unpack

Given that I've set the return value to be a tuple, I don't understand why Python is unable to unpack it.

I then changed my code to have test_sanitize_line_endings store print return value of input_path.in_place() and I can see that the return value is a MagicMock object. Specifically it prints something like <MagicMock name='Path().in_place()' id='13023525345'> If I understand things correctly, what I want is to have mock_path be the MagicMock which has an in_place function that returns a tuple.

What am I doing wrong, and how can I go about correctly replacing the return value of input_path.in_place() in sanitize_line_ending.

like image 404
Varun Madiath Avatar asked Jul 17 '15 14:07

Varun Madiath


1 Answers

I struggled with this error ValueError: need more than 0 values to unpack for several hours. But the problem was not in the way I set the mock up (the correct way was described by @varun-madiath here).

It was in using @mock.patch() decorator:

@mock.patch('pika.BlockingConnection') @mock.patch('os.path.isfile') @mock.patch('subprocess.Popen') def test_foo(self, **mocked_connection**, mock_isfile, **mock_popen**):

The order of parameters must be reversed! See python docs.

like image 145
flam3 Avatar answered Oct 25 '22 10:10

flam3