Unable to return a tuple when mocking a function

python mock return multiple values
python unittest mock return tuple
python mock variable in function
python mock exception
python mock tuple return values
python mock reset
python mock function return value
pytest-mock

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.

After much head scratching and attending a meetup I finally came across this blog post that finally solved my issue.

The crux of the issue is that I was not mocking the correct value. Since I want to replace the result of a function call the code I needed to have written was:

@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')

This correctly results in the function being able to unpack the tuple, it then immediately fails since like @didi2002 mentioned this isn't a context manager. However I was focussed on getting the unpacking to work, and after I was able to achieve that replaced the tuple with a construct with the appropriate methods.

Having a mock return a tuple (for example mocking out os.walk , Having a mock return a tuple (for example mocking out os.walk()) #86. Closed. dhommel Ran 1 test in 0.000s. FAILED (errors=1) The outer parens are for the function call obviously so let's ignore them. Next is the list,  Unable to return a tuple from a constexpr function visual studio 2017 version 15.8 windows 10.0 Jason Turner reported Sep 17, 2018 at 01:24 PM

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.

26.4. unittest.mock — mock object library, Mock and MagicMock objects create all attributes and methods as you access or methods on the mock that don't exist on the spec will fail with an AttributeError . If side_effect is an iterable then each call to the mock will return the next value This will be in the form of a tuple: the first member is any ordered arguments  Return multiple items from a mocked function with Python's mock. - gist:1174019

To be valid, the return value of input_path.in_place() must be an object that has an __enter__ method that returns a tuple.

This is a (very verbose) example:

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")

When and how to use Python mock, We cannot see print statements of cow and dog anymore. The default return value of calling a Mock function is another Mock instance. I have a function (foo) which calls another function (bar). If invoking bar() raises an HttpError, I want to handle it specially if the status code is 404, otherwise re-raise. I am trying to write some unit tests around this foo function, mocking out the call to bar().

try this for return tuple from mocked function:

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

Mocking in Python ⋆ Mark McDonnell, In this example, the side_effect attribute used the create_response() method to build a dynamic For non-trivial tests, it's important to be sure that the test can actually fail. We used the following: return Mock( status = 201, getheaders The value of response_headers is a sequence of two-tuples that has (key, value) pairs. A simple example is a random function since one can’t predict what it will return. Another could be a database call for a database that’s only available in certain environments. Python’s mock library is the de facto standard when mocking functions in Python, yet I have always struggled to understand it from the official documentation.

Modern Python Cookbook, DELETED def _copy(value): if type(value) in (dict, list, tuple, set): return create magic methods on the # class without stomping on other mocks new = type(cls. fail early? return obj class CallableMixin(Base): def __init__(self, spec=None,  As you can see that now we can access members of a tuple just by their name using a .. Let’s disect it a little more. A named tuple has two required arguments. They are the tuple name and the tuple field_names. In the above example our tuple name was ‘Animal’ and the tuple field_names were ‘name’, ‘age’ and ‘cat’.

unittest.mock, A system Jarvis requested for a specific site "gradeup.co", in return to this request it got the error as "LOOKUP FAILED". S3: Count(*) also counts the tuples The function F will be high only when atleast two of the input variables are set to  This is an age-old problem. A method may need to return many things, not just one. A tuple can return multiple values (with less code than a class would require). Note: This causes an allocation. Using ref and out parameters would be faster for a method that is hot. Parameters. Note 2: A Tuple has advantages. It is a reference and can be reused.

GATE 2021: CS & IT Engineering (12 Mock Tests + 20 Subject-wise , If no return value is specified, functional mocks return null. By default, mocks expect one or more calls (i.e., only fail if the function or method is never called). More ways of setting return values. This covers the very basics of setting a return value, but NSubstitute can do much more. Read on for other approachs, including matching specific arguments, ignoring arguments, using functions to calculate return values and returning multiple results.

Comments
  • type(mock_path).return_value = PropertyMock(return_value = (1, 2))