vendredi 6 juillet 2018

Mock a function that modify one of the variables

Say, I have the function like:

def add_errors_if_need(param1, param2, errors):
    for <condition_on param_1>:
        errors.append(<something>)
    if <condition_on_param2>:
        errors.append(<something_else>)

It does not return anything - simply adds something to given errors list or not.

Now in my class, or wherever actually, I have code like this one:

def my_method(<many_stuff_here>):
    error_list = []
    if <condition>:
        error_list.append(<error_msg>)
    add_errors_if_need(param1, param2, errors=error_list)
    ...
    <some other checks that may append something to error_list>
    if errors:
        return error_parser(errors) # formats and prints error messages
    return <success_action>

It works pretty well, the problem is, I am trying to write a test, that mocks it, but since it does not return any value (and I would like to leave it as it is), how can I mock it so it modify error_list variable?

IF it would return a list, I could do something like (I am using pytest):

@patch('path.to.add_errors_if_need'):
def test_my_life(mocked_function, fixture1, fixture2):
   mocked_fun.return_value = [('error_field', 'error_message')]
   result = MyClass.my_method(<many_arguments>)
   assert result == <formatted_error_list>

But I don't know how to achieve such effect.

Aucun commentaire:

Enregistrer un commentaire