I have a Test class with as many as 50 different method. I want to patch every method with a mock function.
prod = {"foo": "bar"}
def TestClass:
@patch(db.get_product, return_value=prod)
def test_1:
pass
@patch(db.get_product, return_value=prod)
def test_2:
pass
.
.
.
@patch(db.get_product, return_value=prod)
def test_50:
pass
Is there any easy way to do this instead of repeating @patch(db.get_product, return=prod)
50 times?
So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.
mock provides a powerful mechanism for mocking objects, called patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.
side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.
You can use patch
as a class decorator instead:
@patch(db.get_product, return_value=prod)
class TestClass:
def test_1:
pass
def test_2:
pass
.
.
.
def test_50:
pass
Excerpt from the documentation:
Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With