Skip to content
Draft
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 @@ -8,4 +8,19 @@ public interface ContextScope extends AutoCloseable {
/** Detaches the context from the execution unit. */
@Override
void close();

/**
* Closes the given scope, tolerating a {@code null} scope.
*
* <p>Useful in advice that attaches a scope on enter and closes it on exit: if the enter advice
* throws before assigning the scope, the exit advice would otherwise NPE on a null scope, masking
* the original failure.
*
* @param scope the scope to close; can be {@code null}.
*/
static void close(ContextScope scope) {
if (scope != null) {
scope.close();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package datadog.context;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

class ContextScopeTest {

private static final class RecordingScope implements ContextScope {
private boolean closed;

@Override
public Context context() {
return null;
}

@Override
public void close() {
closed = true;
}
}

@Test
void staticCloseToleratesNullScope() {
assertDoesNotThrow(() -> ContextScope.close(null));
}

@Test
void staticCloseClosesNonNullScope() {
RecordingScope scope = new RecordingScope();
ContextScope.close(scope);
assertTrue(scope.closed);
}
}
Loading