Re: Mock object but also assert method calls?

2015-08-15 Thread Thomas Lehmann via Python-list
Am Freitag, 14. August 2015 04:53:56 UTC+2 schrieb Steven D'Aprano:
> On Fri, 14 Aug 2015 07:21 am, Ben Finney wrote:
> 
> >> If find following totally different to the normal API which
> >> is provided by the mock library:
> >>
> >> assert call().test2("hello") in mocked_objects.mock_calls
> > 
> > The 'assert' statement is a crude tool, which knows little about the
> > intent of your assertion.
> 
> I agree with Ben here. Despite the popularity of "nose" (I think it is
> nose?) which uses `assert` for testing, I think that is a gross misuse of
> the statement. It is okay to use assertions this way for quick and dirty ad
> hoc testing, say at the command line, but IMO totally inappropriate for
> anything more formal, like unit testing.
> 
> If for no other reason than the use of `assert` for testing makes it
> impossible to test your code when running with the Python -O (optimize)
> switch.
> 
> For more detail on the uses, and abuses, of `assert` see this:
> 
Of course you do NOT use assert in unit tests but I provided
just test code to show my problem. Of course I take nose and
hamcrest and code coverage ...

Here a complete example of my problem (with comments):


from mock import MagicMock, call, patch

class Bla:
def test1(self, value):
pass

mocked_object = MagicMock(Bla)
bla = Bla()
bla.test1("hello")
# empty, why?
print(mocked_object.mock_calls)
# does not work: mocked_object.test1.assert_called_with("hello")

with patch("__main__.Bla") as mocked_object:
bla = Bla()
bla.test1("hello")
# not empty!
print(mocked_object.mock_calls)
# does also not work: mocked_object.test1.assert_called_with("hello")
# but this does work:
assert call().test1("hello") in mocked_object.mock_calls


I don't wanna patch each individual method. Is there no other way?
-- 
https://mail.python.org/mailman/listinfo/python-list


Mock object but also assert method calls?

2015-08-13 Thread Thomas Lehmann via Python-list
Hi,

How about asserting that test2 of class Bar is called?
Of course I can do a patch for a concrete method but
I was looking for something like:

mocked_object.assert_method_called_with(name="test2", "hello")

If find following totally different to the normal API which
is provided by the mock library:

assert call().test2("hello") in mocked_objects.mock_calls

Is there a better way?

APPENDIX:
Foo delegates calls to Bar.

[code]
from mock import patch
with patch("__main__.Bar") as mocked_object:
foo = Foo()
foo.test1()
foo.test2("hello")
print(mocked_object.mock_calls)
# print all calls (c'tor as well as normal methods)
for name, args, kwargs in mocked_object.mock_calls:
print(name, args, kwargs)
[/code]

Generates:


test1: Foo has been called
test2: Foo has been called with value hello
[call(), call().test1(), call().test2('hello')]
('', (), {})
('().test1', (), {})
('().test2', ('hello',), {})
-- 
https://mail.python.org/mailman/listinfo/python-list