0
import module
from x import X

class A:
   def method(): 
       return module.something(arg=X())

I created the following to unit test:

with patch('filename.module.something') as something_mock:
   with patch('filename.X'): as x_mock:
       a.method()
something_mock.assert_called_once_with(arg=x_mock.return_value)
x_mock.assert_called_once_with()

Someone mentioned that there is no need to mock filenme.X without an explanation. Is there other way to verify the call to something without mocking filename.X? How would I change the following assertion to verify the call?

something_mock.assert_called_once_with(arg=_____) 
Cory
  • 14,865
  • 24
  • 57
  • 72
  • 1
    If your code really looks like the example given, what's the point of unit testing it all all? There's nothing happening at this level of the code -- no logical, algorithmic, or data complexity at all. FWIW, with each passing year I find myself mocking less and less, writing fewer unit tests, and writing more (and more interesting) integration or end-to-end tests that exercise larger components of the system. – FMc Apr 12 '15 at 01:22
  • @FMc The code is simplified for clarity – Cory Apr 12 '15 at 01:24
  • This answer might help: http://stackoverflow.com/questions/8658043/how-to-mock-an-import – abrugh Apr 12 '15 at 02:54
  • @FMc ... interesting... I did exactly the reverse path :). IMHO integration tests are less useful without good and extensive unit tests: when an integration test fail unit test give to you a very solid base on what you can trust and where you can have some holes in your code/design. – Michele d'Amico Apr 12 '15 at 21:11

1 Answers1

-1

If create X is not a issue (i.e. db connection or network access) you can do your test without mock it.

You have follow alternatives:

  1. Use mock's called attribute if you are not interested to check how your method call something_mock
  2. Use mock.ANY if you would like to check that something_mock has called by arg keyword arg but you are not interested about what is the value
  3. Use call_args to extract something_mock call arguments and by calls as tuple extract arg value

The first one is

assert something_mock.called

The second one is

something_mock.assert_called_once_with(arg=mock.ANY)

Finally the third one is

args, kwargs = something_mock.call_args
assert isinstance(kwarg['arg'], x.X)

Last option is quite the same to mock X but I wrote it just to show all possibilities.

Michele d'Amico
  • 22,111
  • 8
  • 69
  • 76