Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock patch every method of a class

Tags:

python

nose

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?

like image 215
tinutomson Avatar asked Nov 15 '18 00:11

tinutomson


People also ask

What is the difference between mock and MagicMock?

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.

What is mocking patching?

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.

What is Side_effect in mock Python?

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.


1 Answers

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.

like image 197
blhsing Avatar answered Sep 28 '22 03:09

blhsing