Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Scalar to mocked functions #154

Closed
rajivsarvepalli opened this issue Oct 9, 2021 Discussed in #153 · 1 comment · Fixed by #155 or #162
Closed

Adding Scalar to mocked functions #154

rajivsarvepalli opened this issue Oct 9, 2021 Discussed in #153 · 1 comment · Fixed by #155 or #162
Assignees
Labels
enhancement New feature or request

Comments

@rajivsarvepalli
Copy link
Owner

Discussed in #153

Originally posted by jonyscathe October 6, 2021
Hi,

We are using a lot of scalar() in our project: https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.scalar

Usually to get a single value as per SQLAlchemys example session.query(Item.id, Item.name).scalar()

Is there currently any way to do this with mock-alchemy?
Currently the best option I seem to have seems to be after creating a mock_session to make a new boundary lambda for scalar() such as:

def get_scalar(rows: list[Any]) -> Any:
    if len(rows) == 1:
        for key in rows[0].__mapper__.c.keys():
            if getattr(rows[0], key) is not None:
                return getattr(rows[0], key)
    elif len(rows) > 1:
        raise MultipleResultsFound("Multiple rows were found for scalar()")
    else:
        return None

mock_session = UnifiedAlchemyMagicMock(
        data=[...]
)
mock_session.boundary['scalar']= lambda x: get_scalar(x)
mock_session.scalar = AlchemyMagicMock(side_effect=partial(mock_session._get_data, _mock_name='scalar'))

Is there some better way to be mocking scalar with the UnifiedAlchemyMagicMocks?
Or if there is the best way, could we get scalar() added to the standard boundary dict?

@rajivsarvepalli rajivsarvepalli added the enhancement New feature or request label Oct 9, 2021
@rajivsarvepalli rajivsarvepalli self-assigned this Oct 9, 2021
@rajivsarvepalli
Copy link
Owner Author

rajivsarvepalli commented Oct 9, 2021

Per Discussion, adding scalar to default boundary dict.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
1 participant