Here are some examples of using the @patch decorator in Python:
- Patching a single function:
import patch
import unittest
def some_function():
return 1
class TestSomeFunction(unittest.TestCase):
@patch('path.to.some_function')
def test_some_function(self, mock_some_function):
mock_some_function.return_value = 2
self.assertEqual(some_function(), 2)
In this example, we are patching the some_function function with a new function that returns 2. We then test that our patched version of some_function returns the expected value.
- Patching a class method:
import patch
import unittest
class SomeClass:
def some_method(self):
return 1
class TestSomeClass(unittest.TestCase):
@patch('path.to.SomeClass.some_method')
def test_some_method(self, mock_some_method):
mock_some_method.return_value = 2
obj = SomeClass()
self.assertEqual(obj.some_method(), 2)
In this example, we are patching the some_method class method with a new function that returns 2. We then test that our patched version of some_method returns the expected value.
- Patching a module:
import patch
import unittest
def some_function():
return 1
class TestSomeFunction(unittest.TestCase):
@patch('path.to.some_function')
def test_some_function(self, mock_some_function):
mock_some_function.return_value = 2
self.assertEqual(some_function(), 2)
In this example, we are patching the some_function function with a new function that returns 2. We then test that our patched version of some_function returns the expected value.
- Patching a class:
import patch
import unittest
class SomeClass:
def some_method(self):
return 1
class TestSomeClass(unittest.TestCase):
@patch('path.to.SomeClass')
def test_some_method(self, mock_some_class):
mock_some_class.some_method.return_value = 2
obj = SomeClass()
self.assertEqual(obj.some_method(), 2)
In this example, we are patching the SomeClass class with a new class that has a some_method method that returns 2. We then test that our patched version of some_method returns the expected value.