Skip to content

Conversation

@iamkishansharma
Copy link

What is the purpose of this PR

This pull request fixes a flaky test in snippets.SnippetsTests.union_test. The original test assumed that the order of elements in the union would always be deterministic. However, the underlying implementation of Snippets.union uses a Set (likely HashSet) to compute the union, which does not guarantee element order. As a result, the test failed intermittently when the iteration order changed.

The fix ensures the test assertion is order-independent by sorting the result before comparison.


Why the test fails

  • The test used:
    assertThat(union).isEqualTo(new Integer[]{1, 2, 3, 4});
  • Snippets.union internally returns an array built from a Set with nondeterministic iteration order.
  • Since HashSet does not guarantee element order, the returned array may be [1, 2, 3, 4] in one run and [2, 4, 1, 3] in another.
  • The strict equality check caused flaky failures depending on the runtime order.

How to reproduce the test failure

  1. Run the test multiple times:

    mvn test -Dtest=snippets.SnippetsTests#union_test

    It may pass or fail depending on execution order.

  2. Run with NonDex (to shuffle iteration orders):

    mvn edu.illinois:nondex-maven-plugin:2.1.1:nondex -Dtest=snippets.SnippetsTests#union_test

    This consistently exposes the nondeterminism and reproduces the failure.


Expected results

The union of {1, 2, 3} and {1, 2, 4} should always contain all unique elements:

[1, 2, 3, 4]

Order should not matter because this is a set operation.


Actual results (before fix)

  • Sometimes the result matched:
    [1, 2, 3, 4]
    
  • Other times it returned:
    [2, 4, 1, 3]
    

causing the assertion to fail intermittently.


Description for fix

The test assertion was updated to sort the output before comparison, ensuring order independence:

@Test
public void union_test() throws Exception {
    Integer[] union = Snippets.union(
            new Integer[]{1, 2, 3},
            new Integer[]{1, 2, 4}
    );

    assertThat(union).containsExactlyInAnyOrder(1, 2, 3, 4);
}

This guarantees that the union result always matches the expected elements, regardless of iteration order.
With this fix, the test passes deterministically and is no longer prone to flakiness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant