-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathConfigurationPrecedenceTest.java
More file actions
207 lines (171 loc) · 8.17 KB
/
ConfigurationPrecedenceTest.java
File metadata and controls
207 lines (171 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/*
* Copyright 2023 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package software.amazon.lambda.powertools.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.SetEnvironmentVariable;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import software.amazon.lambda.powertools.common.internal.LambdaHandlerProcessor;
import software.amazon.lambda.powertools.common.stubs.TestLambdaContext;
import software.amazon.lambda.powertools.metrics.model.MetricUnit;
/**
* Tests to verify the hierarchy of precedence for configuration:
* 1. @FlushMetrics annotation
* 2. MetricsBuilder
* 3. Environment variables
*/
class ConfigurationPrecedenceTest {
private static final PrintStream STANDARD_OUT = System.out;
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
private final ObjectMapper objectMapper = new ObjectMapper();
@BeforeEach
void setUp() throws Exception {
System.setOut(new PrintStream(outputStreamCaptor));
// Reset LambdaHandlerProcessor's serviceName
Method resetServiceName = LambdaHandlerProcessor.class.getDeclaredMethod("resetServiceName");
resetServiceName.setAccessible(true);
resetServiceName.invoke(null);
// Reset isColdStart
java.lang.reflect.Field coldStartField = LambdaHandlerProcessor.class.getDeclaredField("isColdStart");
coldStartField.setAccessible(true);
coldStartField.set(null, null);
}
@AfterEach
void tearDown() throws Exception {
System.setOut(STANDARD_OUT);
// Reset the singleton state between tests
java.lang.reflect.Field field = MetricsFactory.class.getDeclaredField("metricsProxy");
field.setAccessible(true);
field.set(null, null);
field = MetricsFactory.class.getDeclaredField("provider");
field.setAccessible(true);
field.set(null, new software.amazon.lambda.powertools.metrics.provider.EmfMetricsProvider());
}
@Test
@SetEnvironmentVariable(key = "POWERTOOLS_METRICS_NAMESPACE", value = "EnvNamespace")
@SetEnvironmentVariable(key = "POWERTOOLS_SERVICE_NAME", value = "EnvService")
void annotationShouldOverrideBuilderAndEnvironment() throws Exception {
// Given
// Configure with builder first
MetricsBuilder.builder()
.withNamespace("BuilderNamespace")
.withService("BuilderService")
.build();
RequestHandler<Map<String, Object>, String> handler = new HandlerWithMetricsAnnotation();
Context context = new TestLambdaContext();
Map<String, Object> input = new HashMap<>();
// When
handler.handleRequest(input, context);
// Then
String emfOutput = outputStreamCaptor.toString().trim();
JsonNode rootNode = objectMapper.readTree(emfOutput);
// Annotation values should take precedence
assertThat(rootNode.get("_aws").get("CloudWatchMetrics").get(0).get("Namespace").asText())
.isEqualTo("AnnotationNamespace");
assertThat(rootNode.has("Service")).isTrue();
assertThat(rootNode.get("Service").asText()).isEqualTo("AnnotationService");
}
@Test
@SetEnvironmentVariable(key = "POWERTOOLS_METRICS_NAMESPACE", value = "EnvNamespace")
@SetEnvironmentVariable(key = "POWERTOOLS_SERVICE_NAME", value = "EnvService")
void builderShouldOverrideEnvironment() throws Exception {
// Given
// Configure with builder
MetricsBuilder.builder()
.withNamespace("BuilderNamespace")
.withService("BuilderService")
.build();
RequestHandler<Map<String, Object>, String> handler = new HandlerWithDefaultMetricsAnnotation();
Context context = new TestLambdaContext();
Map<String, Object> input = new HashMap<>();
// When
handler.handleRequest(input, context);
// Then
String emfOutput = outputStreamCaptor.toString().trim();
JsonNode rootNode = objectMapper.readTree(emfOutput);
// Builder values should take precedence over environment variables
assertThat(rootNode.get("_aws").get("CloudWatchMetrics").get(0).get("Namespace").asText())
.isEqualTo("BuilderNamespace");
assertThat(rootNode.has("Service")).isTrue();
assertThat(rootNode.get("Service").asText()).isEqualTo("BuilderService");
}
@Test
@SetEnvironmentVariable(key = "POWERTOOLS_METRICS_NAMESPACE", value = "EnvNamespace")
@SetEnvironmentVariable(key = "POWERTOOLS_SERVICE_NAME", value = "EnvService")
void environmentVariablesShouldBeUsedWhenNoOverrides() throws Exception {
// Given
RequestHandler<Map<String, Object>, String> handler = new HandlerWithDefaultMetricsAnnotation();
Context context = new TestLambdaContext();
Map<String, Object> input = new HashMap<>();
// When
handler.handleRequest(input, context);
// Then
String emfOutput = outputStreamCaptor.toString().trim();
JsonNode rootNode = objectMapper.readTree(emfOutput);
// Environment variable values should be used
assertThat(rootNode.get("_aws").get("CloudWatchMetrics").get(0).get("Namespace").asText())
.isEqualTo("EnvNamespace");
assertThat(rootNode.has("Service")).isTrue();
assertThat(rootNode.get("Service").asText()).isEqualTo("EnvService");
}
@Test
void shouldUseDefaultsWhenNoConfiguration() throws Exception {
// Given
MetricsBuilder.builder()
.withNamespace("TestNamespace")
.build();
RequestHandler<Map<String, Object>, String> handler = new HandlerWithDefaultMetricsAnnotation();
Context context = new TestLambdaContext();
Map<String, Object> input = new HashMap<>();
// When
handler.handleRequest(input, context);
// Then
String emfOutput = outputStreamCaptor.toString().trim();
JsonNode rootNode = objectMapper.readTree(emfOutput);
// Default values should be used
assertThat(rootNode.get("_aws").get("CloudWatchMetrics").get(0).get("Namespace").asText())
.isEqualTo("TestNamespace");
// Service dimension should not be present when service is undefined
assertThat(rootNode.has("Service")).isFalse();
}
private static final class HandlerWithMetricsAnnotation implements RequestHandler<Map<String, Object>, String> {
@Override
@FlushMetrics(namespace = "AnnotationNamespace", service = "AnnotationService")
public String handleRequest(Map<String, Object> input, Context context) {
Metrics metrics = MetricsFactory.getMetricsInstance();
metrics.addMetric("test-metric", 100, MetricUnit.COUNT);
return "OK";
}
}
private static final class HandlerWithDefaultMetricsAnnotation
implements RequestHandler<Map<String, Object>, String> {
@Override
@FlushMetrics
public String handleRequest(Map<String, Object> input, Context context) {
Metrics metrics = MetricsFactory.getMetricsInstance();
metrics.addMetric("test-metric", 100, MetricUnit.COUNT);
return "OK";
}
}
}