mocking - How to mock path like `module.Class`? using Python's Mock module? -


How will create a class with the path ablib.Pin ? And how do I duplicate the properties of an example from a pin? I would say that it should work like this:

  fake = magic mac () fake Pin = magic mac () fake Pinkkrnl_aidi = 'N 21' Nklikpinkset_vlukritrn_vlu = true duplicate pages .get_value.return_value.return_value = 3 modules = { 'ablib': mock, 'ablib.Pin': mock.Pin,} patcher = patch .dict ( 'sys.modules', modules) patcher.start ()  

when I have a pin creates an instance and get_value or set_value , I get a mock instance instead of true 3 .

  & gt; & Gt; & Gt; P = pin ()> gt; & Gt; & Gt; P.set_value (3) & lt; MagicMock name = 'mock.pan (). Set_value (3) 'id =' 47965 968 '& gt; & Gt; & Gt; & Gt; P.kernel_id & lt; MagicMock name = 'mock.pan (). Kernel_id 'id =' 49231056 '& gt;  

When I call kernel_id directly to pin , I need a result.

  & gt; & Gt; & Gt; Pin.kernel_id 'N21' I want  

can copy how ablib.Pin I know I am a frequency ablib.Pin () that I can get the value. Pin ()

Here is a working version with minimal change in your code:

  from unittest.mock import patches, MagicMock mock = MagicMock () mock.Pin (). Kernel_id = 'N21' fake. Pin (). Set_value.return_value = True mock.Pin (). Get_valuekreturn_value = Modules 3 = { 'Ablib': Fake} patcher = Patch.dict ( 'sys.modules', modules) patcher.start ()  

Test:

  & gt; & Gt; & Gt; Import ablib & gt; & Gt; & Gt; Ablib.Pin & lt; MagicMock name = 'mock.pin' id = '139917634188240' & gt; & Gt; & Gt; & Gt; Ablib.Pin & lt; MagicMock name = 'mock.pin' id = '139917634188240' & gt; & Gt; & Gt; & Gt; Ablib.Pin () & lt; MagicMock name = 'mock.Pin ()' id = '139917634233616' & gt; & Gt; & Gt; & Gt; Ablib.Pin () & lt; MagicMock name = 'mock.Pin ()' id = '139917634233616' & gt; & Gt; & Gt; & Gt; P = ablib.Pin ()> & gt; & Gt; & Gt; P.set_value (3) true & gt; & Gt; & Gt; P.kernel_id 'N21'  

Note that I have deleted the code. Pin = MagicMock () and mock.Pin have been deleted from dictionary. When you use the existing Magic-Mac feature or call it, the new MagicMock instance is created by default. The next time you return that action the next time, fake.pin (for the PIN class), fake. There is no need to explicitly create MagicMock to register with PIN () (for example PIN) and patch.dict () . Just enough to enter duplicate .

Thanks to patch.dict () This module also works on ablib . I believe it is not possible to get it from patches () and patch.object () . Yet real unit testing I have a class patch.object () and patch (to fake fake characteristics of an example of a particular test or group of tests) < / Code>. I am not in a situation where I need to copy the whole module, but I am new to unit-testing and Python.


Comments