Skip to content

caplog: add convenience last_message property or messages? #3579

@wcooley

Description

@wcooley

While refactoring, I noticed in a number of my tests which use caplog a common pattern of doing something then asserting something a pattern match for the very last log message, then doing something else, asserting something a pattern match for the very last log message, etc.

I created a helper function called last_message that just calls caplog.records[-1].getMessage().
That leads me to wonder if it would be useful enough to warrant LogCaptureFixture growing a last_message property?
Or, perhaps, an iterable messages property, which iterates through caplog.records calling getMessage() on each?
The difference between this and caplog.text.splitlines() is that log events can span lines (log.exceptions); caplog.records generally needs to have getMessage() called to get an actual string with formatting expanded.

Either is pretty simple; here are some untested implementations:

  1. messages returning a list, so caplog.messages[-1] is sufficient for the last message:

    @property
    def messages(self):
        return [r.getMessage() for r in self.records]
  2. messages returning a generator plus a last_message because list(caplog.messages)[-1] isn't so nice:

    @property
    def messages(self):
        for r in self.records:
            yield r.getMessage()
    
    @property
    def last_message(self):
        self.records[-1].getMessage()

Would there be interest in a PR adding one of these?

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: loggingrelated to the logging builtin plugintype: enhancementnew feature or API change, should be merged into features branchtype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions