0

I have a SQLAlchemy call that I am trying to mock.

Model.query.filter(and_(Model.id.in_(some_ids), Model.other_id != None)).all()

I am using MagicMock to mock this call and give it a return value. The issue I am having is when I add the and_.

Setting a return value for a call that does not have and_ is as simple as:

mock_model_class.query.filter().all.return_value = some_value

When I try to mock the and_ I get an error from SQLAlchemy.

sqlalchemy.exc.ArgumentError: SQL expression object or string expected, got object of type <class 'unittest.mock.MagicMock'> instead

I have tried different variations, to no avail... such as:

mock_model_class.query.filter().and_().all.return_value
mock_model_class.query.filter(and_).all.return_value

Is there some syntax to this that I am missing?

Kevin Welch
  • 1,488
  • 1
  • 9
  • 18
  • 1
    This is a good argument for making query executor function - so that its easy to mock out, e.g.: `def query_all(model, *filters): return Model.query.filter(*filters).all()` something like that anyway. – SuperShoot Aug 21 '19 at 11:20
  • This is a great suggestion, thank you. – Kevin Welch Aug 21 '19 at 17:51

1 Answers1

1

Just mock sqlalchemy.and_. The reasoning is that this is called before your mocked filter is executed.

Peter K
  • 1,959
  • 1
  • 16
  • 22