wimglenn / pytest-structlog

Structured logging assertions
MIT License
54 stars 6 forks source link

sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session #36

Closed CarlosEduR closed 3 months ago

CarlosEduR commented 3 months ago

Python Version: 3.9.16 Platform Info: macOS-13.4.1-x86_64-i386-64bit pytest-structlog = "==0.7"

My code currently logs class objects loaded using sqlalchemy, by just adding the log fixture to an existing test it starts failing with the following error:

    @pytest.hookimpl(tryfirst=True, hookwrapper=True)
    def pytest_runtest_call(item: pytest.Item) -> Generator[None, None, None]:
        """Prints out a section of captured structlog events on test failures."""
        yield
        events = getattr(item, "structlog_events", [])
>       content = os.linesep.join([str(e) for e in events])
    def load_scalar_attributes(mapper, state, attribute_names, passive):
        """initiate a column-based attribute refresh operation."""

        # assert mapper is _state_mapper(state)
        session = state.session
        if not session:
>           raise orm_exc.DetachedInstanceError(
                "Instance %s is not bound to a Session; "
                "attribute refresh operation cannot proceed" % (state_str(state))
            )
E           sqlalchemy.orm.exc.DetachedInstanceError: Instance <XXXX at xxxxxxxx> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: https://sqlalche.me/e/14/bhk3)

Not opening it as a bug, just trying to know if there is any way to fix it on my side without changing existing logs.

wimglenn commented 3 months ago

It looks like you're logging instances and their repr requires fetching data from a db to render. Perhaps you could log with e.g. k=str(obj) instead of k=obj, so that you're logging strings directly? Just a thought.

An alternative would be to control the session(s) explicitly from test, so that the sqla instances can still be rendered during test teardown.

In either case I'm not sure what the plugin could change to help here, so I'll likely close this issue unless you have something actionable that pytest-structlog could/should do here.

CarlosEduR commented 3 months ago

Thanks for the suggestions