miki725 / alchemy-mock

SQLAlchemy mock helpers.
Other
82 stars 15 forks source link

session.execute(text(<sql>), params).mappings().all() returns empty list rather than data configured in UnifiedAlchemyMagicMock #44

Closed kentbull closed 10 months ago

kentbull commented 10 months ago

It appears that mocking always returns an empty list with the session.execute(text(<sql>), params).mappings().all() 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_pending_requests(credential_type_said, holder_id, issuer_id, session):
    sql_query = pending_requests_query(latest_cred_req_state_subquery) # returns a valid SQL query
    terminal_states = get_terminal_states() # tuple of strings
    completed_states_str = tuple(terminal_states)  # Convert list to tuple for the SQL query
    result = session.execute(
        text(sql_query),
        {
            'credential_type_said': credential_type_said,
            'holder_id': holder_id,
            'issuer_id': issuer_id,
            'completed_states': completed_states_str
        }
    ).mappings().all()

    # Process the results: separate CredentialRequest fields and status
    requests_with_status = []
    for row in result:
        row_dict = dict(row)  # Convert proxy row to dict
        status = row_dict.pop('status')  # Extract status, removing it from the row_dict
        cred_request = CredentialRequest(**row_dict)
        requests_with_status.append((cred_request, status))
    return requests_with_status

And the test mock:

def mytest():
    ...
    mock_session = UnifiedAlchemyMagicMock(data=[
    ...# other mocks
        (
        [mock.call.execute(
            ANY,  # This will match any query text
            {
                "credential_type_said": mock_credential_type.said,
                "issuer_id": issuer_id,
                "holder_id": holder_id,
                "completed_states": credentials.terminal_states_tuple()
            }
        )],
        [mocks.make_pending_request_list_mock()]  # returns a list of CredentialRequest objects
    ),
    # call test function with session, etc.

The result of the .mappings().all() mock is always an empty list rather than the specified data.

Like in the other issue, 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.

Thanks again for building this library.

kentbull commented 10 months ago

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