title: Mocking a Sqlalchemy session for pytest
body: <p>I don't know if this can be done but I'm trying to mock my db.session.save.</p>
  
  <p>I'm using flask and flask-alchemy.</p>
  
  <p>db.py</p>
  
  <pre class="lang-py prettyprint-override"><code>from flask_sqlalchemy import SQLAlchemy
  
  db = SQLAlchemy()
  </code></pre>
  
  <p>The unit test</p>
  
  <pre class="lang-py prettyprint-override"><code>def test_post(self):
      with app.app_context():
          with app.test_client() as client:
              with mock.patch('models.db.session.save') as mock_save:
                  with mock.patch('models.db.session.commit') as mock_commit:
  
                      data = self.gen_legend_data()
                      response = client.post('/legends', data=json.dumps([data]), headers=access_header)
  
                      assert response.status_code == 200
                      mock_save.assert_called()
                      mock_commit.assert_called_once()
  </code></pre>
  
  <p>And the method:</p>
  
  <pre class="lang-py prettyprint-override"><code>def post(cls):
      legends = schemas.Legends(many=True).load(request.get_json())
  
      for legend in legends:
          db.session.add(legend)
  
      db.session.commit()
  
      return {'message': 'legends saved'}, 200
  </code></pre>
  
  <p>I'm trying to mock the db.session.add and db.session.commit. I've tried <code>db.session.save</code> and <code>legends.models.db.session.save</code> and <code>models.db.session.save</code>. They all came back with the save error:</p>
  
  <pre><code>ModuleNotFoundError: No module named 'models.db.session'; 'models.db' is not a package
  </code></pre>
  
  <p>I don't get the error and I'm not sure how to solve it.</p>
  
  <p>Or am I doing something that is totally wrong in wanting to mock a db.session?</p>
  
  <p>Thanks.
  Desmond</p>