Dealing with mutable arguments in Unit Tests
If you pass a mutable argument and then try to unittest it with .assert_called_with()
, you might run into problems. This issue can be confusing since it might seem like there is a bug with the testing framework (such as pytest), and many people have been led down that path.
After digging deeper, I found the following article that explains the problem: https://docs.python.org/3/library/unittest.mock-examples.html#coping-with-mutable-arguments
Another rare but potential issue arises when a mock is called with mutable arguments. The
call_args
andcall_args_list
variables store references to the arguments. If the code under test mutates the arguments, it can be challenging to make assertions about their values when the mock was called.
To address this issue, you can copy the arguments. This approach ensures that even if the arguments are mutated later on in the function, you can still safely and sensibly unit test them.