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

Dictionary ordering of custom comparable keys is not deterministic #1386

Open
Euan-McVie opened this issue Jan 10, 2025 · 0 comments
Open

Dictionary ordering of custom comparable keys is not deterministic #1386

Euan-McVie opened this issue Jan 10, 2025 · 0 comments

Comments

@Euan-McVie
Copy link

Euan-McVie commented Jan 10, 2025

Describe the bug

We have dictionaries where the key has custom equality and hashcode (actually they are automatic via record but the issue is the same)

When verifying the order of the keys sometimes swaps. I have been unable to work out why when the input object to verify is the same as some rusn are the expected way around and others are not.

The resulting comparison is non-deterministic resulting in flaky tests.

Note that we are actually using json and immutable dictionaries, but I can see the issue with a simple repro using a plain dictionary.

Minimal Repro

I can see that that the existing test DictionaryOrderNonComparable is only validating when created alphabetically.

To recreate update the DictionaryOrderNonComparable test to provide Foo2 before Foo1.

Not sure if multiple runs are required as it always happens when I run an equivalent locally, but our full object tests it is flaky and sometimes does pass with no code changes.

public class VerifyImmutableDictionaryTests
{
    [Fact]
    public Task DictionaryOrderNonComparable()
    {
        var dictionary = new Dictionary<NonComparableKey, string>
        {
            [new("Foo2")] = "Bar",
            [new("Foo1")] = "Bar",
        };

        return Verify(dictionary);
    }

    private sealed class NonComparableKey(string member)
    {
        public override string ToString() =>
            member;

        public override int GetHashCode() =>
            member.GetHashCode(StringComparison.InvariantCulture);
    }
}

Verified:

{
  Foo1: Bar,
  Foo2: Bar
}

Received:

{
  Foo2: Bar,
  Foo1: Bar
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant