Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock nested functions?

The mocking library I use is ... mock.

I came across this "mock nested functions" problem when I tried to write test case for a function(legacy code).

This function used a very complex nested function with heavy dependencies on other modules.

I wonder if it's possible to mock nested functions with mock.

like image 594
satoru Avatar asked Sep 21 '12 01:09

satoru


People also ask

How do you mock a nested method in Python?

You can use a MagicMock to replace pretty much any python object. Here, anything in the with block that would normally call super_nested instead will call the super_nested_mock and just return the value that you set to it.

How do you mock function inside another function in jest?

To mock inner function with Jest and JavaScript, we should export the inner function in a module. import * as funcBModule from "./funcB"; import { funcA } from "./foo"; describe("helper", () => { test("test funcB", () => { expect(funcBModule. funcB()). toBe("original"); }); test("test funcA", () => { const spy = jest.

How do you mock a function in Python?

How do we mock in Python? Mocking in Python is done by using patch to hijack an API function or object creation call. When patch intercepts a call, it returns a MagicMock object by default. By setting properties on the MagicMock object, you can mock the API call to return any value you want or raise an Exception .

How do you call a mock function jest?

You can create a namespace that you export as the default object and call b using the namespace. This way, when you call jest. mock it will replace the b function on the namespace object. const f = require('./f'); jest.


Video Answer


1 Answers

for example you need to mock nested function calls (chained functions) from Google DRIVE API

result = get_drive_service().files().insert(body='body', convert=True).execute()    

so you need to patch through functions: service_mock(), files(), insert(), till last execute() response:

from mock import patch with patch('path.to.import.get_drive_service') as service_mock:    service_mock.return_value.files.return_value.insert.\    return_value.execute.return_value = {'key': 'value', 'status': 200} 

Main scheme: first.return_value.second.return_value.third.return_value.last.return_value = rsp

like image 75
pymen Avatar answered Oct 02 '22 18:10

pymen