Skip to content

Commit 112039f

Browse files
Added tests
1 parent f49cd9a commit 112039f

File tree

7 files changed

+249
-16
lines changed

7 files changed

+249
-16
lines changed

spring-data-mongodb/pom.xml

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -193,11 +193,6 @@
193193
<optional>true</optional>
194194
</dependency>
195195

196-
<dependency>
197-
<groupId>io.micrometer</groupId>
198-
<artifactId>micrometer-core</artifactId>
199-
<optional>true</optional>
200-
</dependency>
201196
<dependency>
202197
<groupId>io.micrometer</groupId>
203198
<artifactId>micrometer-tracing</artifactId>
@@ -313,6 +308,17 @@
313308
<scope>test</scope>
314309
</dependency>
315310

311+
<dependency>
312+
<groupId>io.micrometer</groupId>
313+
<artifactId>micrometer-test</artifactId>
314+
<scope>test</scope>
315+
</dependency>
316+
<dependency>
317+
<groupId>io.micrometer</groupId>
318+
<artifactId>micrometer-tracing-test</artifactId>
319+
<scope>test</scope>
320+
</dependency>
321+
316322
<!-- jMolecules -->
317323

318324
<dependency>

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/observability/MicrometerMongoCommandListener.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public void commandStarted(CommandStartedEvent event) {
6969
}
7070
String databaseName = event.getDatabaseName();
7171
if ("admin".equals(databaseName)) {
72-
return; // don't trace commands like "endSessions"
72+
return; // don't instrument commands like "endSessions"
7373
}
7474
RequestContext requestContext = event.getRequestContext();
7575
if (requestContext == null) {
@@ -91,7 +91,7 @@ private void setupObservability(CommandStartedEvent event, RequestContext reques
9191
String collectionName = getCollectionName(command, commandName);
9292
Timer.Builder timerBuilder = Timer.builder("mongodb.command");
9393
MongoHandlerContext mongoHandlerContext = new MongoHandlerContext(event) {
94-
@Override public String getSimpleName() {
94+
@Override public String getContextualName() {
9595
return getMetricName(commandName, collectionName);
9696
}
9797

@@ -190,7 +190,7 @@ public void commandFailed(CommandFailedEvent event) {
190190
}
191191

192192
@Nullable
193-
String getCollectionName(BsonDocument command, String commandName) {
193+
private String getCollectionName(BsonDocument command, String commandName) {
194194
if (COMMANDS_WITH_COLLECTION_NAME.contains(commandName)) {
195195
String collectionName = getNonEmptyBsonString(command.get(commandName));
196196
if (collectionName != null) {

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/observability/MongoHandlerContext.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,5 @@ public void setCommandFailedEvent(CommandFailedEvent commandFailedEvent) {
5353
this.commandFailedEvent = commandFailedEvent;
5454
}
5555

56-
public abstract String getSimpleName();
56+
public abstract String getContextualName();
5757
}

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/observability/MongoTracingRecordingHandler.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ private void setRemoteIpAndPort(CommandStartedEvent event, Span.Builder spanBuil
7979
@Override public void onStop(Timer.Sample sample, MongoHandlerContext context, Timer timer, Duration duration) {
8080
TracingContext tracingContext = getTracingContext(context);
8181
Span span = tracingContext.getSpan();
82-
span.name(context.getSimpleName());
82+
span.name(context.getContextualName());
8383
tagSpan(context, timer.getId(), span);
8484
span.end();
8585
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/*
2+
* Copyright 2002-2021 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.mongodb.observability;
17+
18+
import com.mongodb.ServerAddress;
19+
import com.mongodb.connection.ClusterId;
20+
import com.mongodb.connection.ConnectionDescription;
21+
import com.mongodb.connection.ServerId;
22+
import com.mongodb.event.CommandFailedEvent;
23+
import com.mongodb.event.CommandStartedEvent;
24+
import com.mongodb.event.CommandSucceededEvent;
25+
import io.micrometer.core.instrument.Timer;
26+
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
27+
import io.micrometer.tracing.Span;
28+
import io.micrometer.tracing.test.simple.SimpleSpan;
29+
import io.micrometer.tracing.test.simple.SimpleTracer;
30+
import org.bson.BsonDocument;
31+
import org.bson.BsonString;
32+
import org.jetbrains.annotations.NotNull;
33+
import org.junit.jupiter.api.BeforeEach;
34+
import org.junit.jupiter.api.Test;
35+
36+
import static org.assertj.core.api.Assertions.assertThat;
37+
38+
class MicrometerMongoCommandListenerForTracingTests {
39+
40+
SimpleMeterRegistry registry = new SimpleMeterRegistry();
41+
42+
MicrometerMongoCommandListener listener = new MicrometerMongoCommandListener(registry);
43+
44+
SimpleTracer simpleTracer = new SimpleTracer();
45+
46+
MongoTracingRecordingHandler handler = new MongoTracingRecordingHandler(simpleTracer);
47+
48+
@BeforeEach
49+
void setup() {
50+
registry.config().timerRecordingHandler(handler);
51+
}
52+
53+
@Test void successfullyCompletedCommandShouldCreateSpanWhenParentSampleInRequestContext() {
54+
TestRequestContext testRequestContext = testRequestContextWithParentSample();
55+
56+
commandStartedAndSucceeded(testRequestContext);
57+
58+
// TODO: Convert to SpanAssert
59+
SimpleSpan span = assertThatMongoSpanIsClientWithTags();
60+
assertThat(span.getIp()).isNull();
61+
assertThat(span.getPort()).isZero();
62+
}
63+
64+
@Test void successfullyCompletedCommandShouldCreateSpanWithAddressInfoWhenParentSampleInRequestContextAndHandlerAddressInfoEnabled() {
65+
handler.setSetRemoteIpAndPortEnabled(true);
66+
TestRequestContext testRequestContext = testRequestContextWithParentSample();
67+
68+
commandStartedAndSucceeded(testRequestContext);
69+
70+
// TODO: Convert to SpanAssert
71+
SimpleSpan span = assertThatMongoSpanIsClientWithTags();
72+
assertThat(span.getIp()).isNotBlank();
73+
assertThat(span.getPort()).isPositive();
74+
}
75+
76+
@Test void commandWithErrorShouldCreateTimerWhenParentSampleInRequestContext() {
77+
TestRequestContext testRequestContext = testRequestContextWithParentSample();
78+
79+
listener.commandStarted(new CommandStartedEvent(testRequestContext, 0, new ConnectionDescription(new ServerId(new ClusterId("description"), new ServerAddress("localhost", 1234))), "database", "insert", new BsonDocument("collection", new BsonString("user"))));
80+
listener.commandFailed(new CommandFailedEvent(testRequestContext, 0, null, "insert", 0, new IllegalAccessException()));
81+
82+
SimpleSpan simpleSpan = assertThatMongoSpanIsClientWithTags();
83+
// TODO: Convert to SpanAssert
84+
assertThat(simpleSpan.getThrowable()).isInstanceOf(IllegalAccessException.class);
85+
}
86+
87+
@NotNull private TestRequestContext testRequestContextWithParentSample() {
88+
Timer.Sample parent = Timer.start(registry);
89+
TestRequestContext testRequestContext = TestRequestContext.withSample(parent);
90+
return testRequestContext;
91+
}
92+
93+
private void commandStartedAndSucceeded(TestRequestContext testRequestContext) {
94+
listener.commandStarted(new CommandStartedEvent(
95+
testRequestContext, 0, new ConnectionDescription(new ServerId(new ClusterId("description"), new ServerAddress("localhost", 1234))), "database", "insert", new BsonDocument("collection", new BsonString("user"))));
96+
listener.commandSucceeded(new CommandSucceededEvent(testRequestContext, 0, null, "insert", null, 0));
97+
}
98+
99+
// TODO: Convert to SpanAssert
100+
private SimpleSpan assertThatMongoSpanIsClientWithTags() {
101+
SimpleSpan simpleSpan = simpleTracer.onlySpan();
102+
assertThat(simpleSpan).isNotNull();
103+
assertThat(simpleSpan.getName()).isEqualTo("insert user");
104+
assertThat(simpleSpan.getSpanKind()).isEqualTo(Span.Kind.CLIENT);
105+
assertThat(simpleSpan.getRemoteServiceName()).isEqualTo("mongodb-database");
106+
assertThat(simpleSpan.getTags())
107+
.containsEntry("mongodb.command", "insert")
108+
.containsEntry("mongodb.collection", "user")
109+
.containsKey("mongodb.cluster_id");
110+
return simpleSpan;
111+
}
112+
113+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/*
2+
* Copyright 2002-2021 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.mongodb.observability;
17+
18+
import com.mongodb.ServerAddress;
19+
import com.mongodb.connection.ClusterId;
20+
import com.mongodb.connection.ConnectionDescription;
21+
import com.mongodb.connection.ServerId;
22+
import com.mongodb.event.CommandFailedEvent;
23+
import com.mongodb.event.CommandStartedEvent;
24+
import com.mongodb.event.CommandSucceededEvent;
25+
import io.micrometer.core.instrument.Tag;
26+
import io.micrometer.core.instrument.Tags;
27+
import io.micrometer.core.instrument.Timer;
28+
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
29+
import io.micrometer.core.tck.MeterRegistryAssert;
30+
import org.bson.BsonDocument;
31+
import org.bson.BsonString;
32+
import org.junit.jupiter.api.Test;
33+
34+
import static io.micrometer.core.tck.MeterRegistryAssert.assertThat;
35+
import static org.assertj.core.api.Assertions.assertThat;
36+
37+
class MicrometerMongoCommandListenerTests {
38+
39+
SimpleMeterRegistry registry = new SimpleMeterRegistry();
40+
41+
MicrometerMongoCommandListener listener = new MicrometerMongoCommandListener(registry);
42+
43+
@Test void commandStartedShouldNotInstrumentWhenAdminDatabase() {
44+
listener.commandStarted(new CommandStartedEvent(null, 0, null, "admin", "", null));
45+
46+
// TODO: Move this to MeterAssert#doesNotHaveMeterWithName or MeterAssert#isEmpty
47+
assertThat(registry.getMeters()).isEmpty();
48+
}
49+
50+
@Test void commandStartedShouldNotInstrumentWhenNoRequestContext() {
51+
listener.commandStarted(new CommandStartedEvent(null, 0, null, "some name", "", null));
52+
53+
// TODO: Move this to MeterAssert#doesNotHaveMeterWithName or MeterAssert#isEmpty
54+
assertThat(registry.getMeters()).isEmpty();
55+
}
56+
57+
@Test void commandStartedShouldNotInstrumentWhenNoParentSampleInRequestContext() {
58+
listener.commandStarted(new CommandStartedEvent(new TestRequestContext(), 0, null, "some name", "", null));
59+
60+
// TODO: Move this to MeterAssert#doesNotHaveMeterWithName or MeterAssert#isEmpty
61+
assertThat(registry.getMeters()).isEmpty();
62+
}
63+
64+
@Test void successfullyCompletedCommandShouldCreateTimerWhenParentSampleInRequestContext() {
65+
Timer.Sample parent = Timer.start(registry);
66+
TestRequestContext testRequestContext = TestRequestContext.withSample(parent);
67+
68+
listener.commandStarted(new CommandStartedEvent(testRequestContext, 0, new ConnectionDescription(new ServerId(new ClusterId("description"), new ServerAddress("localhost", 1234))), "database", "insert", new BsonDocument("collection", new BsonString("user"))));
69+
listener.commandSucceeded(new CommandSucceededEvent(testRequestContext, 0, null, "insert", null, 0));
70+
71+
assertThatTimerRegisteredWithTags();
72+
}
73+
74+
@Test void successfullyCompletedCommandWithCollectionHavingCommandNameShouldCreateTimerWhenParentSampleInRequestContext() {
75+
Timer.Sample parent = Timer.start(registry);
76+
TestRequestContext testRequestContext = TestRequestContext.withSample(parent);
77+
78+
listener.commandStarted(new CommandStartedEvent(testRequestContext, 0, new ConnectionDescription(new ServerId(new ClusterId("description"), new ServerAddress("localhost", 1234))), "database", "aggregate", new BsonDocument("aggregate", new BsonString("user"))));
79+
listener.commandSucceeded(new CommandSucceededEvent(testRequestContext, 0, null, "aggregate", null, 0));
80+
81+
assertThatTimerRegisteredWithTags();
82+
}
83+
84+
@Test void successfullyCompletedCommandWithoutClusterInformationShouldCreateTimerWhenParentSampleInRequestContext() {
85+
Timer.Sample parent = Timer.start(registry);
86+
TestRequestContext testRequestContext = TestRequestContext.withSample(parent);
87+
88+
listener.commandStarted(new CommandStartedEvent(testRequestContext, 0, null, "database", "insert", new BsonDocument("collection", new BsonString("user"))));
89+
listener.commandSucceeded(new CommandSucceededEvent(testRequestContext, 0, null, "insert", null, 0));
90+
91+
assertThat(registry)
92+
.hasTimerWithNameAndTags("mongodb.command", Tags.of(Tag.of("mongodb.collection", "user")));
93+
}
94+
95+
@Test void commandWithErrorShouldCreateTimerWhenParentSampleInRequestContext() {
96+
Timer.Sample parent = Timer.start(registry);
97+
TestRequestContext testRequestContext = TestRequestContext.withSample(parent);
98+
99+
listener.commandStarted(new CommandStartedEvent(testRequestContext, 0, new ConnectionDescription(new ServerId(new ClusterId("description"), new ServerAddress("localhost", 1234))), "database", "insert", new BsonDocument("collection", new BsonString("user"))));
100+
listener.commandFailed(new CommandFailedEvent(testRequestContext, 0, null, "insert", 0, new IllegalAccessException()));
101+
102+
assertThatTimerRegisteredWithTags();
103+
}
104+
105+
private void assertThatTimerRegisteredWithTags() {
106+
assertThat(registry)
107+
.hasTimerWithNameAndTags("mongodb.command", Tags.of(Tag.of("mongodb.collection", "user")))
108+
.hasTimerWithNameAndTagKeys("mongodb.command", "mongodb.cluster_id");
109+
}
110+
111+
}
Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,16 @@
1616

1717
package org.springframework.data.mongodb.observability;
1818

19+
import java.util.HashMap;
1920
import java.util.Map;
2021
import java.util.stream.Stream;
2122

2223
import com.mongodb.RequestContext;
24+
import io.micrometer.core.instrument.Timer;
2325

24-
class MicrometerRequestContext implements RequestContext {
26+
class TestRequestContext implements RequestContext {
2527

26-
private final Map<Object, Object> map;
27-
28-
MicrometerRequestContext(Map<Object, Object> map) {
29-
this.map = map;
30-
}
28+
private final Map<Object, Object> map = new HashMap<>();
3129

3230
@Override
3331
public <T> T get(Object key) {
@@ -64,4 +62,9 @@ public Stream<Map.Entry<Object, Object>> stream() {
6462
return map.entrySet().stream();
6563
}
6664

65+
static TestRequestContext withSample(Timer.Sample value) {
66+
TestRequestContext testRequestContext = new TestRequestContext();
67+
testRequestContext.put(Timer.Sample.class, value);
68+
return testRequestContext;
69+
}
6770
}

0 commit comments

Comments
 (0)