How to mock a function imported into an imported method from another module

I had the following function checked:

my_package.db_engine.db_functions.py:

from ..utils import execute_cmd
from my_package.db_engine.db_functions import dbinfo 

def dbinfo(db_name):
    params = (cmd_cfg.DB, add_pj_suffix(db_name))
    cmd = get_db_cmd_string(cmd_cfg.DBINFO, params=params)
    cmd_result = execute_cmd(cmd)
    result_dict = map_cmd_output_to_dict(cmd_result)
    return result_dict

This function takes the name of the database, then builds a command line from it and executes this command as if subprocessusing a method execute_cmd. I want to test this function without actually executing subprocess. I only want to check the correctness and correctness of the transmission of the command to execute_cmd. Therefore, I need to make fun of the method execute_cmdthat is imported from the module utils.

The structure of my folder is as follows:

my_project
|_src
| |_my_package
| | |_db_engine
| | | |_db_functions.py
| | | |_ __init__.py
| | |_utils.py
| | |_ __init__.py
| | |_ ....
| |_ __init__.py
|_tests
  |_test_db_engine.py

So, for my test, I tried the following in test_db_engine.py:

import unittest
from mock import patch

from my_pacakge.db_engine.db_functions import dbinfo


def execute_db_info_cmd_mock():
    return {
            'Last Checkpoint': '1.7',
            'Last Checkpoint Date': 'May 20, 2015 10:07:41 AM'
    }


class DBEngineTestSuite(unittest.TestCase):
    """ Tests für DB Engine"""

    @patch('my_package.utils.execute_cmd')
    def test_dbinfo(self, test_patch):
        test_patch.return_value = execute_db_info_cmd_mock()
        db_info = dbinfo('MyDBNameHere')
        self.assertEqual(sandbox_info['Last Checkpoint'], '1.7')

1.6 Last Checkpoint. , , mock, 1.7. , - 1.6, , ​​ mock.

, ?

+4
1

. :

patch() (), , . , , , , .

, , , .

-- execute_cmd , :

from ..utils import execute_cmd

my_package.utils.execute_cmd , execute_cmd my_package.db_engine.db_functions - , .

:

@patch('my_package.db_engine.db_functions.execute_cmd')

execute_cmd dbinfo -, from ... import ....

+4

Source: https://habr.com/ru/post/1687370/


All Articles