Skip to content

Commit

Permalink
refactor: ensure EnumRandomizer can be used deterministically
Browse files Browse the repository at this point in the history
Ensures `EnumRandomizer` can be used deterministically even when
excluding values by specifying a seed to be overwritten.
  • Loading branch information
npepinpe authored and fmbenhassine committed Jul 15, 2023
1 parent 7a5cd4a commit a1d6087
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,21 @@ public EnumRandomizer(final Class<E> enumeration, final E... excludedValues) thr
this.enumConstants = getFilteredList(enumeration, excludedValues);
}

/**
* Create a new {@link EnumRandomizer}.
*
* @param enumeration the enumeration from which this randomizer will generate random values
* @param seed the initial seed
* @param excludedValues the values to exclude from random picking
* @throws IllegalArgumentException when excludedValues contains all enumeration values,
* ie all elements from the enumeration are excluded
*/
public EnumRandomizer(final Class<E> enumeration, final long seed, final E... excludedValues) throws IllegalArgumentException {
super(seed);
checkExcludedValues(enumeration, excludedValues);
this.enumConstants = getFilteredList(enumeration, excludedValues);
}

/**
* Get a random value within an enumeration or an enumeration subset (when values are excluded)
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ void shouldAlwaysGenerateTheSameValueForTheSameSeed() {
assertThat(new EnumRandomizer(Gender.class, SEED).getRandomValue()).isEqualTo(FEMALE);
}

@Test
void shouldAlwaysGenerateTheSameValueForTheSameSeedWithExcludedValues() {
assertThat(
new EnumRandomizer<>(TriState.class, SEED, TriState.Maybe).getRandomValue()).isEqualTo(
TriState.False);
}

public enum Gender {
MALE, FEMALE
}
Expand All @@ -67,4 +74,11 @@ public void should_return_null_for_empty_enum() {
Empty randomElement = new EnumRandomizer<>(Empty.class).getRandomValue();
assertThat(randomElement).isNull();
}

// always keep three options here, as we want to exclude one and still select the same one
// deterministically
@SuppressWarnings("unused")
private enum TriState {
True, False, Maybe
}
}

0 comments on commit a1d6087

Please sign in to comment.