简体   繁体   中英

How to replace function with mock object for unittesting in Python

How do you replace all references to a function with a mock object in Python?

I'm trying to write some unittests for a Fabric script. Specifically, I want to replace fabric.api.run with a mock version that logs the command instead of executing. However, I want to do this in a way so I don't have to rewrite all code that references fabric.

I've tried doing:

import fabric.api
_run = fabric.api.run
fabric.api.run = my_mock_run_function

but since I can't guarantee this will run before any other modules import fabric.api, a lot of code is still using the real run function.

If your code uses:

from fabric.api import run

you will have to patch the local reference your module has of the run function:

@patch('yourmodule.run')
def test_method(self, run):
    pass

If your code uses:

import fabric.api
...
api.run(...)

you will be able to patch the original copy:

@patch('fabric.api.run')
def test_method(self, run):
    pass

See this nice explanation .

use unittest.mock.patch

import fabric.api
import unittest
from unittest.mock import Mock, patch

class TestCases(unittest.TestCase):
    @patch('fabric.api.run')
    def test_test(self):
        self.assertTrue(True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM