derwiki-adroll / mock

Automatically exported from code.google.com/p/mock
BSD 2-Clause "Simplified" License
0 stars 0 forks source link

mock.assert_called_once_with() fails when asserting against a Dictionary #228

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
import mock
import unittest

class Dependency(object):
    def __init__(self):
        self._mutable_field = None;

    def function1(self, mutable_param):
        self._mutable_feild = mutable_param
        return 1

    def function2(self, mutable_param):
        self._mutable_feild = mutable_param

def action():
    d = Dependency()
    v = {1: "a"}
    ret_val = d.function1(v)
    if ret_val:
        v.update({2: "b"})
        d.function2(v)
    return

class TestMock(unittest.TestCase):

    @mock.patch("module.Dependency")
    def test_action(self, dep):
        dep.return_value.function1.return_value = 1

        action()

        dep.return_value.function1.assert_called_once_with({1:"a"})
        dep.return_value.function2.assert_called_once_with({1; "a", 2: "b"})

What is the expected output? What do you see instead?

The test passes

But, the test does not pass, and instead gives the following error:

AssertionError: Expected call: function1({1: 'a'})
Actual call: function1({1: 'a', 2: 'b'})

It appears as though when the method_under_test action() was run, and the 
dictionary was modified under the if statement in the action() method, the 

What version of the product are you using? On what operating system?
mock v1.0.1 
Mac OS 10.8.4 

Please provide any additional information below.

Original issue reported on code.google.com by vineeth....@gmail.com on 21 Apr 2014 at 11:05

GoogleCodeExporter commented 9 years ago
This is the classic problem of making assertions with mutable arguments. The 
mock assert methods keep references to their arguments, so if you mutate the 
argument then assertions can fail. 

There's an explanation, along with a workaround, in the docs:

http://www.voidspace.org.uk/python/mock/examples.html#coping-with-mutable-argume
nts

Original comment by fuzzyman on 22 Apr 2014 at 11:14