hRobert12 / mock

Automatically exported from code.google.com/p/mock
BSD 2-Clause "Simplified" License
0 stars 0 forks source link

Mocking os.kill does not work #124

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Maybe I missed something but this looks strange to me:

from mock import Mock, patch
from os import kill

@patch('os.kill', Mock(return_value=2))
def test():
   print( kill(1084,4) )
test()
>>> OSError: [Errno 3] No such process

Mock works if the test is formulated the following way:

from mock import Mock, patch
import os 

@patch('os.kill', Mock(return_value=2))
def test():
   print( os.kill(1084,4) )
test()
>>>2

But that formulation is no solution since the place where "kill" is called may 
not lie within the scope of the test but elsewhere in an other package. And 
there kill may be imported as "from os import kill".

Original issue reported on code.google.com by otoomuel...@googlemail.com on 3 Nov 2011 at 4:03

GoogleCodeExporter commented 8 years ago
Patch works by changing what objects names point to. So patch('os.kill', thing) 
says "change the 'kill' name in the os module to point to 'thing'". If you have 
directly imported kill then you have created a new local name (in the module 
you imported it) pointing to the original kill object.

There is *no way* in Python (no sane way anyway) to say - "find every name 
pointing to os.kill and rebind them to point to something else". What you need 
to do is patch the name kill *in the module where it is being used*.

I've tried to explain this in the "where to patch" section of the documentation:

http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch

Original comment by fuzzyman on 3 Nov 2011 at 4:14