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

Add supplier variant for Observation.Context.getOrDefault() #3708

Merged
merged 2 commits into from
Mar 22, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,19 @@ interface ContextView {
*/
<T> T getOrDefault(Object key, T defaultObject);

/**
* Returns an element or default if not present.
* @param key key
* @param defaultObjectSupplier supplier for default object to return
* @param <T> value type
* @return object or default if not present
* @since 1.11.0
*/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add @since 1.11.0?

default <T> T getOrDefault(Object key, Supplier<T> defaultObjectSupplier) {
T value = get(key);
return value != null ? value : defaultObjectSupplier.get();
}

/**
* Returns low cardinality key values.
* @return low cardinality key values
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.function.Supplier;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

/**
* Tests for {@link Observation.Context}.
Expand Down Expand Up @@ -68,6 +71,30 @@ void getOrDefaultShouldUseFallbackValue() {
assertThat(context.getOrDefault(Integer.class, 123)).isEqualTo(123);
}

@Test
void getOrDefaultSupplierWhenKeyIsPresent() {
context.put(String.class, "42");

@SuppressWarnings("unchecked")
Supplier<String> defaultSupplier = mock(Supplier.class);
when(defaultSupplier.get()).thenReturn("abc");

assertThat(context.getOrDefault(String.class, defaultSupplier)).isEqualTo("42");
verifyNoInteractions(defaultSupplier);
}

@Test
void getOrDefaultSupplierWhenKeyIsMissing() {
context.put(String.class, "42");

@SuppressWarnings("unchecked")
Supplier<Integer> defaultSupplier = mock(Supplier.class);
when(defaultSupplier.get()).thenReturn(123);

assertThat(context.getOrDefault(Integer.class, defaultSupplier)).isEqualTo(123);
verify(defaultSupplier, times(1)).get();
}

@Test
void getRequiredShouldFailIfThereIsNoValue() {
context.put(String.class, "42");
Expand Down