Update TestSpanHandler.java

This commit is contained in:
Marcin Grzejszczak
2021-11-08 09:11:14 +01:00
committed by GitHub
parent f562809830
commit f6e3208a1a

View File

@@ -1,3 +1,4 @@
/*
* Copyright 2013-2021 the original author or authors.
*
@@ -18,10 +19,13 @@ package org.springframework.cloud.sleuth.test;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.exporter.FinishedSpan;
import static org.assertj.core.api.BDDAssertions.then;
public interface TestSpanHandler extends Iterable<FinishedSpan> {
List<FinishedSpan> reportedSpans();
@@ -36,6 +40,30 @@ public interface TestSpanHandler extends Iterable<FinishedSpan> {
FinishedSpan get(int index);
void assertAllSpansWereFinishedOrAbandoned(Queue<Span> createdSpans);
default void assertAllSpansWereFinishedOrAbandoned(Queue<Span> createdSpans) {
List<FinishedSpan> finishedSpans = reportedSpans();
then(finishedSpans).as("There should be that many finished spans as many created ones")
.hasSize(createdSpans.size());
// finished -> a,b,c ; created -> b,c,d => matchedFinished = b,c
List<FinishedSpan> matchedFinishedSpans = finishedSpans.stream()
.filter(f -> createdSpans.stream().anyMatch(cs -> f.getSpanId().equals(cs.context().spanId())))
.collect(Collectors.toList());
// finished -> a,b,c ; created -> b,c,d => matchedCreated = b,c
List<Span> matchedCreatedSpans = createdSpans.stream()
.filter(cs -> finishedSpans.stream().anyMatch(f -> cs.context().spanId().equals(f.getSpanId())))
.collect(Collectors.toList());
// finished -> a,b,c ; created -> b,c,d => missingFinished = a
List<FinishedSpan> missingFinishedSpans = finishedSpans.stream()
.filter(f -> matchedFinishedSpans.stream().noneMatch(m -> m.getSpanId().equals(f.getSpanId())))
.collect(Collectors.toList());
// finished -> a,b,c ; created -> b,c,d => missingCreated = d
List<Span> missingCreatedSpans = createdSpans.stream().filter(
f -> matchedCreatedSpans.stream().noneMatch(m -> m.context().spanId().equals(f.context().spanId())))
.collect(Collectors.toList());
if (!missingFinishedSpans.isEmpty() || !missingCreatedSpans.isEmpty()) {
throw new AssertionError("There were unmatched created spans " + missingCreatedSpans
+ " and/or finished span " + missingFinishedSpans);
}
}
}