title: Using pytest-mock to mock objects and object methods
body: <p>I'm trying to use <code>pytest-mock</code> for mocking. This library is essentially a plugin/wrapper for <code>mock</code> and <code>patch</code>.</p>
  <p>My problem is defined as:</p>
  <p>I have an application (<code>mymodule.py</code>) that uses SQL Alchemy. Basically, there's a function that defines some objects from SQL Alchemy and returns a dictionary with those objects.</p>
  <pre><code>def some_function1():
      # some code
      from sqlalchemy import create_engine, MetaData, Table
  
      engine = create_engine(f&quot;mysql+pymysql://{username}:{password}@{host}:{port}&quot;)
      meta = MetaData(engine)
      my_table = Table(
          'my_table',
          meta,
          autoload=True,
          schema=&quot;some_schema&quot;
      )
      db_tools = {&quot;engine&quot;: engine, &quot;table&quot;: my_table}
      return db_tools
  </code></pre>
  <p>Then, a second function takes that output dictionary as input and uses them:</p>
  <pre><code>def some_function2(db_tools, data):
  
      sql_query = db_tools[&quot;table&quot;].insert().values(data)
      db_tools[&quot;engine&quot;].execute(sql_query)
      # some more code
  </code></pre>
  <p>So now I'm writing unit tests, and I don't want to actually communicate with the real database. So I just need to mock everything <code>sqlalchemy</code> related. So far, I've managed to mock <code>create_engine</code>, <code>MetaData</code> and <code>Table</code> by doing:</p>
  <pre><code>mocker.patch(
      'my_module.create_engine',
      return_value=True
  )
  mocker.patch(
     'my_module.MetaData',
     return_value=True
  )
  mocker.patch(
     'my_module.Table',
     return_value=True
  )
  </code></pre>
  <p>That allows me to test <code>some_function1</code>. But now I need to test <code>some_function2</code>, which uses the methods or attributes <code>.insert()</code>, <code>.values</code> and <code>.execute()</code>. How can I patch that?</p>