Skip to content

Commit

Permalink
generate asserts support for various mock types (#50)
Browse files Browse the repository at this point in the history
Signed-off-by: Peter Kogan <[email protected]>
  • Loading branch information
pksol authored May 16, 2022
1 parent c4623be commit 579ac0f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
12 changes: 5 additions & 7 deletions mock_autogen/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,13 +314,11 @@ def generate_asserts(mock, name=''):
str: the asserts matching to the call list of the sent mock
"""
name = name if name else _guess_var_name(mock)
if not isinstance(mock, python_mock.MagicMock) and \
not isinstance(mock, unittest.mock.MagicMock) and \
not isinstance(mock, python_mock.Mock) and \
not isinstance(mock, unittest.mock.Mock):
raise TypeError("Unsupported mocking object: {0}. "
"You are welcome to add code to support it :)".format(
type(mock)))
has_attr = hasattr(mock, 'call_args_list') and hasattr(mock, 'mock_calls')
if not has_attr:
raise TypeError(
f"Unsupported object: {type(mock)}. Please pass a mock which "
f"has `call_args_list` and `mock_calls` attributes.")

generated_asserts = ""
if mock.call_args_list:
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

# This call to setup() does all the work
setup(name="mock-generator",
version="2.3.2",
version="2.4.0",
description="Generate python mocks and assertions quickly",
long_description=README,
long_description_content_type="text/markdown",
Expand Down
13 changes: 13 additions & 0 deletions tests/test_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -1243,6 +1243,19 @@ def test_generate_asserts_add_multiple_calls(mock_functions_only_collection):
exec(generated) # verify the validity of assertions


def test_generate_asserts_spy_object(mocker):
my_spy = mocker.spy(tests.sample.code.tested_module, "add")

assert 5 == tests.sample.code.tested_module.add(2, 3)
assert "34" == tests.sample.code.tested_module.add("3", "4")

generated = mock_autogen.generator.generate_asserts(my_spy)
assert 'from mock import call\n\n' \
'assert 2 == my_spy.call_count\n' \
"my_spy.assert_has_calls(calls=[call(2, 3),call('3', '4'),])\n" == generated
exec(generated) # verify the validity of assertions


def test_generate_asserts_context_manager(mock_modules_only_collection):
tests.sample.code.tested_module.process_and_zip('/path/to.zip',
'in_zip.txt', 'foo bar')
Expand Down

0 comments on commit 579ac0f

Please sign in to comment.