Kevin Welch
Kevin Welch

Reputation: 1508

Using SQLAlchemy `and_` with MagicMock

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?

Upvotes: 0

Views: 546

Answers (1)

Peter K
Peter K

Reputation: 2484

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

Upvotes: 1

Related Questions