GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Preserve insertion order for extra dict items in assertion output by RafiB982 · Pull Request #14066 · pytest-dev/pytest

Conversation

@RafiB982

@RafiB982 RafiB982 commented Dec 26, 2025

Copy link
Copy Markdown

When dict assertions fail, pytest currently displays extra items using
unordered set iteration, which loses insertion order.

This change preserves insertion order for the
"Left contains N more items" and "Right contains N more items" sections
by iterating keys in mapping order instead of set order.

A focused regression test is included.

Closes #13503

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Dec 26, 2025
@RafiB982
RafiB982 marked this pull request as ready for review December 26, 2025 13:35
@RafiB982 RafiB982 mentioned this pull request Dec 26, 2025
Failure output order of dictionary keys is alphabetical instead of insertion order #13503
Closed
nicoddemus
nicoddemus requested changes Dec 26, 2025
View reviewed changes

@nicoddemus nicoddemus left a comment

Copy link
Copy Markdown
Member

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.

Thanks @RafiB982, please take a look at my comments.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/_pytest/assertion/util.py
+ highlighter(saferepr({k: right[k]}))
]
extra_left = set_left - set_right
extra_left = [k for k in left if k not in right]

@nicoddemus nicoddemus Dec 26, 2025

Copy link
Copy Markdown
Member

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.

It is more efficient to reuse the set for the containment check:

Suggested change
extra_left = [k for k in left if k not in right]
extra_left = [k for k in left if k not in set_right]

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread src/_pytest/assertion/util.py
highlighter(pprint.pformat({k: left[k] for k in extra_left})).splitlines()
)
extra_right = set_right - set_left
extra_right = [k for k in right if k not in left]

@nicoddemus nicoddemus Dec 26, 2025

Copy link
Copy Markdown
Member

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.

Suggested change
extra_right = [k for k in right if k not in left]
extra_right = [k for k in right if k not in set_left]

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread testing/test_assertion.py
test_order="""
def test_order():
a = {
"first": 1,

@nicoddemus nicoddemus Dec 26, 2025

Copy link
Copy Markdown
Member

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.

Please let's use a dict with more keys for this test, only 2 seems few to catch any regressions. I suggest using simply "a", "b", etc, inserted in non-alphabetical order.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread testing/test_assertion.py
Comment on lines +2221 to +2235
stdout = re.sub(r"\x1b\[[0-9;]*m", "", stdout)

assert "Left contains 2 more items:" in stdout

dict_line = next(
line
for line in stdout.splitlines()
if "{" in line and "}" in line and "first" in line
)

first = dict_line.find("first")
second = dict_line.find("second")

assert first != -1 and second != -1
assert first < second

@nicoddemus nicoddemus Dec 26, 2025

Copy link
Copy Markdown
Member

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.

Could we use just result.stdout.fnmatch_lines instead to verify the output, instead of this custom parsing logic?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@RafiB982

RafiB982 commented Dec 27, 2025

Copy link
Copy Markdown
Author

Thanks for the review @nicoddemus

I’ve addressed the feedback by:

  1. reusing sets for containment checks in the implementation

  2. expanding the test to use more keys in non-alphabetical insertion order

  3. relying on -vv full assertion diffs and result.stdout.fnmatch_lines for verification

  4. The rebase conflict has been resolved and tox -e py310 passes successfully.

Please let me know if you’d like any further adjustments.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@RafiB982
RafiB982 requested a review from nicoddemus December 27, 2025 04:44
nicoddemus
nicoddemus requested changes Dec 27, 2025
View reviewed changes
Comment thread testing/test_assertion.py
Comment on lines +2203 to +2229
def test_dict_extra_items_preserve_insertion_order(pytester):
pytester.makepyfile(
test_order="""
def test_order():
a = {
"b": 2,
"a": 1,
"d": 4,
"e": 5,
"c": 3,
}
assert a == {}
"""
)

result = pytester.runpytest("-vv")

result.stdout.fnmatch_lines(
[
"*Left contains 5 more items:*",
"*'b': 2*",
"*'a': 1*",
"*'d': 4*",
"*'e': 5*",
"*'c': 3*",
]
)

@nicoddemus nicoddemus Dec 27, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

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.

Thanks, but I noticed the test as written still passes in main, because it ends up matching against several lines of the output by chance.

Here is the output of the internal test_order in your branch:

================================ FAILURES =================================
_______________________________ test_order ________________________________

    def test_order():
        a = {
            "b": 2,
            "a": 1,
            "d": 4,
            "e": 5,
            "c": 3,
        }
>       assert a == {}
E       AssertionError: assert {'b': 2, 'a': 1, 'd': 4, 'e': 5, 'c': 3} == {}
E
E         Left contains 5 more items:
E         {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
E
E         Full diff:
E         - {}
E         + {
E         +     'a': 1,
E         +     'b': 2,
E         +     'c': 3,
E         +     'd': 4,
E         +     'e': 5,
E         + }

.tmp\test_order.py:12: AssertionError
========================= short test summary info =========================
FAILED .tmp\test_order.py::test_order - AssertionError: assert {'b': 2, 'a': 1, 'd': 4, 'e': 5, 'c': 3} == {}

  Left contains 5 more items:
  {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

  Full diff:
  - {}
  + {
  +     'a': 1,
  +     'b': 2,
  +     'c': 3,
  +     'd': 4,
  +     'e': 5,
  + }
============================ 1 failed in 0.19s ============================

As we can see, the full diff still shows the keys in sorted order.

The problem is that the keys (for example 'a': 1) appear many times in the output and the test as written ends up matching that in different places, even though the "Full diff" output is still sorted.

Here is an improved version of the test which fails in main:

Suggested change
def test_dict_extra_items_preserve_insertion_order(pytester):
pytester.makepyfile(
test_order="""
def test_order():
a = {
"b": 2,
"a": 1,
"d": 4,
"e": 5,
"c": 3,
}
assert a == {}
"""
)
result = pytester.runpytest("-vv")
result.stdout.fnmatch_lines(
[
"*Left contains 5 more items:*",
"*'b': 2*",
"*'a': 1*",
"*'d': 4*",
"*'e': 5*",
"*'c': 3*",
]
)
def test_dict_extra_items_preserve_insertion_order(pytester: Pytester) -> None:
"""Assertion output of dict diff shows keys in insertion order (#13503)."""
pytester.makepyfile(
test_order="""
def test_order():
a = {
"b": 2,
"a": 1,
"d": 4,
"e": 5,
"c": 3,
}
assert a == {}
"""
)
result = pytester.runpytest("-vv")
result.stdout.fnmatch_lines(
[
"*Left contains 5 more items:*",
"*Full diff:",
"* + *'b': 2,",
"* + *'a': 1,",
"* + *'d': 4,",
"* + *'e': 5,",
"* + *'c': 3,",
"test_order.py:*: AssertionError",
]
)

The test above fails in main and also fails in this branch. It seems more work is needed to handle the Full diff output.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Comment thread changelog/13503.bugfix.rst
@@ -0,0 +1 @@
Preserved insertion order for extra dictionary items in assertion failure output.

@nicoddemus nicoddemus Dec 27, 2025

Copy link
Copy Markdown
Member

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.

Suggested change
Preserved insertion order for extra dictionary items in assertion failure output.
Display dictionary differences in assertion failures using the original key insertion order instead of sorted order.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@nicoddemus

nicoddemus commented Dec 27, 2025

Copy link
Copy Markdown
Member

The documentation failure is being addressed in #14067.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@nicoddemus nicoddemus mentioned this pull request Dec 27, 2025
Fix: assertrepr_compare respects dict insertion order #14050
Merged
@RafiB982

RafiB982 commented Dec 28, 2025

Copy link
Copy Markdown
Author

Hi @nicoddemus ,
I’ve addressed the latest feedback as follows:

  1. Updated test_dict_extra_items_preserve_insertion_order to assert against the Full diff section explicitly, ensuring the test fails on main and only passes when insertion order is preserved. This avoids false positives from matching keys appearing elsewhere in the output.

  2. Insertion order coverage: Expanded the test data to include multiple keys inserted in a non-alphabetical order (b, a, d, e, c) to better guard against regressions.

  3. Assertion output behavior: Updated the assertion diff logic to preserve dictionary insertion order when rendering extra items, including in the Full diff output.

  4. Reused precomputed key sets (set_left / set_right) for containment checks as suggested.

  5. Changelog
    Updated changelog/13503.bugfix.rst to reflect the corrected behavior.

I’ve rebased the branch and pushed the changes. Please let me know if anything else should be adjusted.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@RafiB982
RafiB982 requested a review from nicoddemus December 28, 2025 05:28
nicoddemus
nicoddemus requested changes Dec 28, 2025
View reviewed changes

@nicoddemus nicoddemus left a comment

Copy link
Copy Markdown
Member

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.

I have not reviewed the changes in deep, but:

  • All builds are failing
  • There are a bunch of unrelated changes (plugins_list.rst, workflow versions) that are included, please rebase the branch into main removing those.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@RafiB982

RafiB982 commented Dec 29, 2025

Copy link
Copy Markdown
Author

Hi @nicoddemus ,
I’ve refreshed and rebased the branch onto the latest main and pushed the updated history.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@RafiB982
RafiB982 requested a review from nicoddemus December 29, 2025 03:29
nicoddemus
nicoddemus requested changes Dec 29, 2025
View reviewed changes

@nicoddemus nicoddemus left a comment

Copy link
Copy Markdown
Member

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.

Thanks @RafiB982

However I still see unrelated changes; please rebase and remove the extra commits.

Also, tests are still failing.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@RafiB982

RafiB982 commented Dec 31, 2025

Copy link
Copy Markdown
Author

Hello @nicoddemus ,
i am confused to see those many files under the PR i raised, as i did not make any changes..

(pytest-venv) rafi@ENDEAVOUR:~/pytest$ git show
commit 2ac996017eaa065271e6451757f7cf4f4c542950 (HEAD -> preserve-dict-insertion-order)
Author: Rafi [email protected]
Date: Fri Dec 26 18:14:14 2025 +0530

Preserve insertion order for extra dict items in assertion output

diff --git a/src/_pytest/assertion/util.py b/src/_pytest/assertion/util.py
index f35d83a6f..a5bcc5d02 100644
--- a/src/_pytest/assertion/util.py
+++ b/src/_pytest/assertion/util.py
@@ -520,7 +520,7 @@ def _compare_eq_dict(
+ " != "
+ highlighter(saferepr({k: right[k]}))
]

  • extra_left = set_left - set_right
  • extra_left = [k for k in left if k not in right]
    len_extra_left = len(extra_left)
    if len_extra_left:
    explanation.append(
    @@ -529,7 +529,7 @@ def _compare_eq_dict(
    explanation.extend(
    highlighter(pprint.pformat({k: left[k] for k in extra_left})).splitlines()
    )
  • extra_right = set_right - set_left
  • extra_right = [k for k in right if k not in left]
    len_extra_right = len(extra_right)
    if len_extra_right:
    explanation.append(
    diff --git a/testing/test_assertion.py b/testing/test_assertion.py
    :...skipping...
    commit 2ac996017eaa065271e6451757f7cf4f4c542950 (HEAD -> preserve-dict-insertion-order)
    Author: Rafi [email protected]
    Date: Fri Dec 26 18:14:14 2025 +0530
Preserve insertion order for extra dict items in assertion output

diff --git a/src/_pytest/assertion/util.py b/src/_pytest/assertion/util.py
index f35d83a6f..a5bcc5d02 100644
--- a/src/_pytest/assertion/util.py
+++ b/src/_pytest/assertion/util.py
@@ -520,7 +520,7 @@ def _compare_eq_dict(
+ " != "
+ highlighter(saferepr({k: right[k]}))
]

  • extra_left = set_left - set_right
  • extra_left = [k for k in left if k not in right]
    len_extra_left = len(extra_left)
    if len_extra_left:
    explanation.append(
    @@ -529,7 +529,7 @@ def _compare_eq_dict(
    explanation.extend(
    highlighter(pprint.pformat({k: left[k] for k in extra_left})).splitlines()
    )
  • extra_right = set_right - set_left
  • extra_right = [k for k in right if k not in left]
    len_extra_right = len(extra_right)
    if len_extra_right:
    explanation.append(
    diff --git a/testing/test_assertion.py b/testing/test_assertion.py
    index 5179b13b0..a9cb1075d 100644
    --- a/testing/test_assertion.py
    +++ b/testing/test_assertion.py
    @@ -2198,3 +2198,36 @@ def test_full_output_vvv(pytester: Pytester) -> None:
    ]
    )
    result.stdout.no_fnmatch_line(expected_non_vvv_arg_line)

+import re
+
+def test_dict_extra_items_preserve_insertion_order(pytester):

  • pytester.makepyfile(
  •    test_order="""
    
  •    def test_order():
    
  •        a = {
    
  •            "first": 1,
    
  •            "second": 2,
    
  •        }
    
  •        assert a == {}
    
  •    """
    
  • )
  • result = pytester.runpytest()
  • stdout = result.stdout.str()
  • stdout = re.sub(r"\x1b[[0-9;]*m", "", stdout)
  • assert "Left contains 2 more items:" in stdout
  • dict_line = next(
  •    line for line in stdout.splitlines()
    
  •    if "{" in line and "}" in line and "first" in line
    
  • )
  • first = dict_line.find("first")
  • second = dict_line.find("second")
  • assert first != -1 and second != -1
  • assert first < second
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

RafiB982 and others added 4 commits December 31, 2025 09:07
@RafiB982
Preserve insertion order for extra dict items in assertion output
0262fd3
@RafiB982
Fix changelog entry for #13503
5bb95f2
@pre-commit-ci
[pre-commit.ci] auto fixes from pre-commit.com hooks
69ce953
for more information, see https://pre-commit.ci
@RafiB982
Fix import order in test_assertion
7e7f100
@RafiB982

RafiB982 commented Dec 31, 2025

Copy link
Copy Markdown
Author

Hi @nicoddemus , as suggested fixed all errors.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@RafiB982
RafiB982 requested a review from nicoddemus December 31, 2025 04:54
@RafiB982

RafiB982 commented Jan 3, 2026

Copy link
Copy Markdown
Author

Hi @nicoddemus, let me know if you are okay with PR..

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@nicoddemus

nicoddemus commented Jan 5, 2026

Copy link
Copy Markdown
Member

@RafiB982 not there yet, please see #14066 (comment).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@nicoddemus nicoddemus mentioned this pull request Jan 5, 2026
Add regression test and fixed dict insertion order in assertion diffs… #14086
Closed
@nicoddemus nicoddemus mentioned this pull request Jan 16, 2026
Fix: Preserve dict insertion order in assertion output #14116
Closed
3 tasks done
@nicoddemus nicoddemus added backport 9.0.x and removed backport 9.0.x labels Feb 14, 2026
@nicoddemus nicoddemus closed this in 966edc9 Feb 14, 2026
patchback Bot pushed a commit that referenced this pull request Feb 14, 2026
@DavidAGInnovation @patchback
Fix: assertrepr_compare respects dict insertion order (#14050)
1a81ee6
Fixes #13503

Closes #14066

(cherry picked from commit 966edc9)
@nicoddemus

nicoddemus commented Feb 14, 2026

Copy link
Copy Markdown
Member

Superseded by #14050, thanks anyway, appreciate the attempt. 👍

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

nicoddemus pushed a commit that referenced this pull request Feb 14, 2026
@patchback @DavidAGInnovation
Fix: assertrepr_compare respects dict insertion order (#14050) (#14193)
60fb59d
Fixes #13503

Closes #14066

(cherry picked from commit 966edc9)

Co-authored-by: DavidAG <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@nicoddemus nicoddemus Awaiting requested review from nicoddemus

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Failure output order of dictionary keys is alphabetical instead of insertion order

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@RafiB982 @nicoddemus
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.