-
Notifications
You must be signed in to change notification settings - Fork 66
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
Sketch: new testing API #432
Draft
itamarst
wants to merge
5
commits into
master
Choose a base branch
from
422-capture-logging-pytest
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,16 +13,18 @@ | |
from ._validation import MessageType, Field | ||
from ._errors import _error_extraction | ||
|
||
|
||
def class_fqpn(typ): | ||
"""Convert a class to it's fully-qualified name.""" | ||
return "%s.%s" % (typ.__module__, typ.__name__) | ||
|
||
|
||
TRACEBACK_MESSAGE = MessageType( | ||
"eliot:traceback", | ||
[ | ||
Field(REASON_FIELD, safeunicode, "The exception's value."), | ||
Field("traceback", safeunicode, "The traceback."), | ||
Field( | ||
EXCEPTION_FIELD, | ||
lambda typ: "%s.%s" % (typ.__module__, typ.__name__), | ||
"The exception type's FQPN.", | ||
), | ||
Field(EXCEPTION_FIELD, class_fqpn, "The exception type's FQPN."), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If using |
||
], | ||
"An unexpected exception indicating a bug.", | ||
) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
"""Plugins for py.test.""" | ||
|
||
import json | ||
|
||
import pytest | ||
|
||
from .testutil import _capture_logs | ||
from .json import EliotJSONEncoder | ||
|
||
|
||
@pytest.fixture | ||
def eliot_logs(request): | ||
""" | ||
Capture log messages for the duration of the test. | ||
|
||
1. The fixture object is a L{eliot.testutil.TestingDestination}. | ||
|
||
2. All messages logged during the test are validated at the end of | ||
the test. | ||
|
||
3. Any unflushed logged tracebacks will cause the test to fail. If you | ||
expect a particular tracekbac, you can flush it by calling | ||
C{remove_expected_tracebacks} on the C{TestingDestination} instance. | ||
""" | ||
|
||
def logs_for_pyttest(encode=EliotJSONEncoder().encode, decode=json.loads): | ||
return _capture_logs(request.addfinalizer, encode, decode) | ||
|
||
|
||
__all__ = ["eliot_logs"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# Enable pytester, so we can test fixtures/plugins: | ||
pytest_plugins = ["pytester"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
"""Utilities for testing.""" | ||
|
||
import json | ||
from unittest import TestCase | ||
from typing import Type | ||
|
||
from .json import EliotJSONEncoder | ||
from ._message import MESSAGE_TYPE_FIELD | ||
from ._traceback import REASON_FIELD, class_fqpn | ||
from ._util import exclusively | ||
|
||
|
||
__all__ = ["TestingDestination", "UnexpectedTracebacks", "logs_for_pyunit"] | ||
|
||
|
||
class UnexpectedTracebacks(Exception): | ||
""" | ||
A test had some tracebacks logged which were not marked as expected. | ||
|
||
If you expected the traceback then you will need to flush it using | ||
C{TestingDestination.flush_tracebacks}. | ||
""" | ||
|
||
|
||
class TestingDestination: | ||
""" | ||
A destination that stores messages for testing purposes. | ||
|
||
Unexpected tracebacks are considered errors (your code logging a traceback | ||
typically indicates a bug), so you will need to remove expected tracebacks | ||
by calling C{remove_expected_tracebacks}. | ||
""" | ||
|
||
def __init__(self, encode, decode): | ||
""" | ||
@param encode: Take an unserialized message, serialize it. | ||
@param decode: Take an serialized message, deserialize it. | ||
""" | ||
self.messages = [] | ||
self._traceback_messages = [] | ||
self._encode = encode | ||
self._decode = decode | ||
|
||
@exclusively | ||
def write(self, message): | ||
if message.get(MESSAGE_TYPE_FIELD) == "eliot:traceback": | ||
self._traceback_messages.append(message) | ||
self.messages.append(self._decode(self._encode(message))) | ||
|
||
@exclusively | ||
def remove_expected_tracebacks(self, exceptionType: Type[Exception]): | ||
""" | ||
Remove all logged tracebacks whose exception is of the given type. | ||
|
||
This means they are expected tracebacks and should not cause the test | ||
to fail. | ||
|
||
@param exceptionType: A subclass of L{Exception}. | ||
|
||
@return: C{list} of flushed messages. | ||
""" | ||
result = [] | ||
remaining = [] | ||
for message in self._traceback_messages: | ||
if message[REASON_FIELD] == class_fqpn(exceptionType): | ||
result.append(message) | ||
else: | ||
remaining.append(message) | ||
self.traceback_messages = remaining | ||
return result | ||
|
||
def _ensure_no_bad_messages(self): | ||
""" | ||
Raise L{UnexpectedTracebacks} if there are any unexpected tracebacks. | ||
|
||
Raise L{ValueError} if there are serialization failures from the Eliot | ||
type system, or serialization errors from the encoder/decoder | ||
(typically JSON). | ||
|
||
If you expect a traceback to be logged, remove it using | ||
C{remove_expected_tracebacks}. | ||
""" | ||
if self._traceback_messages: | ||
raise UnexpectedTracebacks(self._traceback_messages) | ||
serialization_failures = [ | ||
m | ||
for m in self.messages | ||
if m.get(MESSAGE_TYPE_FIELD) | ||
in ("eliot:serialization_failure", "eliot:destination_failure") | ||
] | ||
if serialization_failures: | ||
raise ValueError(serialization_failures) | ||
|
||
|
||
def _capture_logs(addfinalizer, encode, decode): | ||
test_dest = TestingDestination(encode, decode) | ||
from . import add_destinations, remove_destination | ||
|
||
add_destinations(test_dest) | ||
addfinalizer(remove_destination, test_dest) | ||
addfinalizer(test_dest._ensure_no_bad_messages) | ||
|
||
return test_dest | ||
|
||
|
||
def logs_for_pyunit( | ||
test_case: TestCase, encode=EliotJSONEncoder().encode, decode=json.loads | ||
) -> TestingDestination: | ||
"""Capture the logs for a C{unittest.TestCase}. | ||
|
||
1. Captures all log messages. | ||
|
||
2. At the end of the test, raises an exception if there are any | ||
unexpected tracebacks, or any of the messages couldn't be | ||
serialized. | ||
|
||
@returns: The L{TestingDestination} that will capture the log messages. | ||
""" | ||
return _capture_logs(test_case.addCleanup, encode, decode) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can't you just use
__qualname__
?It's available since Python 3.3.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Python 2.7 is still supported.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not anymore! But when that code was written, it was supported.