Skip to content

Instantly share code, notes, and snippets.

@viniciusban
Created January 19, 2021 19:43
Show Gist options
  • Save viniciusban/12410bbc24f52ce6cc0721a36dc54c0b to your computer and use it in GitHub Desktop.
Save viniciusban/12410bbc24f52ce6cc0721a36dc54c0b to your computer and use it in GitHub Desktop.
Checking arguments of called mocked objects
# functions.py
class CustomPessoa:
def __init__(self, *args, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
def target_function(pessoa, outro_arg):
return
def caller():
c = CustomPessoa(nome="Vinicius")
target_function(c, False)
return
# test_functions.py
# run it with: $ python -m unittest test_functions.py
import unittest
from unittest import mock
import functions
class TestFunctions(unittest.TestCase):
@mock.patch("functions.target_function")
def test_called(self, target_mocked):
functions.caller()
self.assertEqual(target_mocked.called, True)
@unittest.expectedFailure
@mock.patch("functions.target_function")
def test_called_with_fail(self, target_mocked):
functions.caller()
expected_pessoa = functions.CustomPessoa(nome="Vinicius")
target_mocked.assert_called_with(expected_pessoa)
# O teste falha porque o argumento passado para `target_function()`
# nao eh o mesmo objeto `expected_pessoa`, apesar do atributo `nome`
# ter o mesmo conteudo.
@mock.patch("functions.target_function")
def test_inspect_call_args_success(self, target_mocked):
expected_pessoa = functions.CustomPessoa(nome="Vinicius")
functions.caller()
(arg_pessoa, arg_outro_arg) = target_mocked.call_args[0]
self.assertEqual(arg_pessoa.nome, expected_pessoa.nome)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment