miki725 / alchemy-mock

SQLAlchemy mock helpers.
Other
82 stars 15 forks source link

session.execute(text(<sql>), params).fetchall() returns mock rather than data configured in UnifiedAlchemyMagicMock #43

Closed kentbull closed 10 months ago

kentbull commented 10 months ago

It appears that mocking does not work with the session.execute(text(<sql>), params).fetchall() call.

I have a multi-step mock where I am, in a large transaction, performing multiple lookups.

One of these example lookups is below, the one that doesn't work.

def get_data_source_url(type_id, issuer_id, session):
    sql_query = """
    SELECT e.config_key 
      FROM data_sources c
        INNER JOIN external_systems e on c.external_system_id = e.id 
     WHERE c.ctype_id = :type_id
       AND c.issuer_id = :issuer_id
    """
    result = session.execute(
        text(sql_query),
        {'type_id': type_id,
         'issuer_id': issuer_id}) \
        .fetchall()
    return result

And the test mock:

def mytest():
    ...
    mock_session = UnifiedAlchemyMagicMock(data=[
    ...# other mocks
        (
            [mock.call.execute(
                ANY,  # Match any text query
                {
                    'type_id': mock_type.id,
                    'issuer_id': issuer_id),
                }
            )],
           [  # Mock response
            (external_system_id,)  # Return a list with a single tuple containing the external system ID
           ]
    )
    # call test function with session, etc.

The result of the .fetchall() mock is always a mock instance rather than the specified data.

I end up having to use unittest.mock to work with my test, though that means I can't use alchemy-mock for this specific mock. I'd like to be able to use alchemy-mock.

Thank you for building this library. It's hard work to do things like this.

kentbull commented 10 months ago

I opened this on the wrong repo. This should be for mock-alchemy.