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

Parse unitest.mock assertions as diffs #256

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 34 additions & 18 deletions teamcity/pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@

diff_tools.patch_unittest_diff()
_ASSERTION_FAILURE_KEY = '_teamcity_assertion_failure'
# unitest.mock's assertions
_MOCK_CALL_FAILURE_RE = re.compile(
r'^AssertionError: (?P<msg>expected (call|await) not found).\nExpected: (?P<expected>.+)\nActual: (?P<actual>.+?)'
# "undo" https://github.com/pytest-dev/pytest-mock#improved-reporting-of-mock-call-assertion-errors
r'(\n\npytest introspection follows:\n.*)?$',
re.DOTALL,
)


def pytest_addoption(parser):
Expand Down Expand Up @@ -211,6 +218,32 @@ def report_test_finished(self, test_id, duration=None):
self.teamcity.testFinished(test_id, testDuration=duration, flowId=test_id)
self.test_start_reported_mark.remove(test_id)

def _get_diff(self, report):
try:
err_message = str(report.longrepr.reprcrash.message)
diff_name = diff_tools.EqualsAssertionError.__name__
# There is a string like "foo.bar.DiffError: [serialized_data]"
if diff_name in err_message:
serialized_data = err_message[err_message.index(diff_name) + len(diff_name) + 1:]
return diff_tools.deserialize_error(serialized_data)

match = _MOCK_CALL_FAILURE_RE.search(err_message)
if match:
expected, actual = match.group('expected'), match.group('actual')
if self.swap_diff:
expected, actual = actual, expected
return diff_tools.EqualsAssertionError(expected=expected, actual=actual, msg=match.group('msg'), preformated=True)

assertion_tuple = getattr(self.current_test_item, _ASSERTION_FAILURE_KEY, None)
if assertion_tuple:
op, left, right = assertion_tuple
if op in ('==', '!='):
if self.swap_diff:
left, right = right, left
return diff_tools.EqualsAssertionError(expected=right, actual=left, msg='op', preformated=True)
except Exception:
return None

def report_test_failure(self, test_id, report, message=None, report_output=True):
if hasattr(report, 'duration'):
duration = timedelta(seconds=report.duration)
Expand All @@ -224,24 +257,7 @@ def report_test_failure(self, test_id, report, message=None, report_output=True)
if report_output:
self.report_test_output(report, test_id)

diff_error = None
try:
err_message = str(report.longrepr.reprcrash.message)
diff_name = diff_tools.EqualsAssertionError.__name__
# There is a string like "foo.bar.DiffError: [serialized_data]"
if diff_name in err_message:
serialized_data = err_message[err_message.index(diff_name) + len(diff_name) + 1:]
diff_error = diff_tools.deserialize_error(serialized_data)

assertion_tuple = getattr(self.current_test_item, _ASSERTION_FAILURE_KEY, None)
if assertion_tuple:
op, left, right = assertion_tuple
if self.swap_diff:
left, right = right, left
diff_error = diff_tools.EqualsAssertionError(expected=right, actual=left)
except Exception:
pass

diff_error = self._get_diff(report)
if not diff_error:
from .jb_local_exc_store import get_exception
diff_error = get_exception()
Expand Down
7 changes: 7 additions & 0 deletions tests/guinea-pigs/diff_assert_error_unittest_mock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from unittest.mock import Mock


def test_test():
m = Mock()
m('foo')
m.assert_called_with('bar')
14 changes: 14 additions & 0 deletions tests/integration-tests/pytest_integration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,20 @@ def test_multiline_diff(venv):
])


@pytest.mark.skipif("sys.version_info < (3, 3) ", reason="requires Python 3.3")
def test_unittest_mock_asserts(venv):
output = run(venv, "../diff_assert_error_unittest_mock.py")
test_name = 'tests.guinea-pigs.diff_assert_error_unittest_mock.test_test'
assert_service_messages(
output,
[
ServiceMessage('testCount', {'count': "1"}),
ServiceMessage('testStarted', {'name': test_name}),
ServiceMessage('testFailed', {'name': test_name, "actual": "mock(|'foo|')", "expected": "mock(|'bar|')"}),
ServiceMessage('testFinished', {'name': test_name}),
])


@pytest.mark.skipif("sys.version_info < (2, 7) ", reason="requires Python 2.7")
def test_num_diff(venv):
output = run(venv, "../diff_assert_error_nums.py")
Expand Down