Cannot return tuple when mocking a function

I am trying to enjoy the ridicule of Python, and I am tripping over to mock the next 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 set the return value as a tuple, I do not understand why Python cannot unpack it.

Then I changed my code to test_sanitize_line_endingssave the print return value input_path.in_place(), and I see that the return value is an object MagicMock. In particular, it prints something like <MagicMock name='Path().in_place()' id='13023525345'> If I understand correctly, I want mock_pathMagicMock, which has an in_place function that returns a tuple.

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

+6
4

, , , .

, . , , :

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

, , , , @didi2002, . , , , , .

+3

, input_path.in_place() , __enter__, .

( ) :

def test():
    context = MagicMock()
    context.__enter__.return_value = (1, 2)

    func = MagicMock()
    func.in_place.return_value = context

    path_mock = MagicMock()
    path_mock.return_value = func

    with patch("path.Path", path_mock):
        sanitize_line_ending("test.txt")
0

:

ret = (1, 2)
type(mock_path).return_value = PropertyMock(return_value = ret)
0
source

I struggled with this error ValueError: need more than 0 values to unpackfor several hours. But the problem was not how I set in the layout (the correct way was described by @ Varuna-madiath here ).

This was in the use of a decorator @mock.patch():

@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 the parameters must be canceled! See python docs .

0
source

Source: https://habr.com/ru/post/1598390/


All Articles