-
Notifications
You must be signed in to change notification settings - Fork 241
Expand file tree
/
Copy pathAllureGrpcTest.java
More file actions
570 lines (490 loc) · 25.8 KB
/
Copy pathAllureGrpcTest.java
File metadata and controls
570 lines (490 loc) · 25.8 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*
* Copyright 2016-2026 Qameta Software Inc
*
* 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 io.qameta.allure.grpc;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ForwardingClientCall;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import io.qameta.allure.Allure;
import io.qameta.allure.http.HttpExchange;
import io.qameta.allure.model.Attachment;
import io.qameta.allure.model.StepResult;
import io.qameta.allure.test.AllureResults;
import io.qameta.allure.test.IsolatedLifecycle;
import org.grpcmock.GrpcMock;
import org.grpcmock.junit5.GrpcMockExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.qameta.allure.test.RunUtils.runWithinTestContext;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.grpcmock.GrpcMock.bidiStreamingMethod;
import static org.grpcmock.GrpcMock.clientStreamingMethod;
import static org.grpcmock.GrpcMock.serverStreamingMethod;
import static org.grpcmock.GrpcMock.unaryMethod;
@ExtendWith(GrpcMockExtension.class)
@IsolatedLifecycle
class AllureGrpcTest {
private static final String RESPONSE_MESSAGE = "Hello world!";
private static final String GRPC_EXCHANGE = "gRPC exchange";
private static final Metadata.Key<String> REQUEST_ID_HEADER = Metadata.Key.of("x-request-id", Metadata.ASCII_STRING_MARSHALLER);
private static final ObjectMapper JSON = new ObjectMapper();
private ManagedChannel managedChannel;
@BeforeEach
void configureMockServer() {
managedChannel = ManagedChannelBuilder
.forAddress("localhost", GrpcMock.getGlobalPort())
.usePlaintext()
.directExecutor()
.build();
GrpcMock.stubFor(
unaryMethod(TestServiceGrpc.getCalculateMethod())
.willReturn(Response.newBuilder().setMessage(RESPONSE_MESSAGE).build())
);
GrpcMock.stubFor(
serverStreamingMethod(TestServiceGrpc.getCalculateServerStreamMethod())
.willReturn(
asList(
Response.newBuilder().setMessage(RESPONSE_MESSAGE).build(),
Response.newBuilder().setMessage(RESPONSE_MESSAGE).build()
)
)
);
GrpcMock.stubFor(
clientStreamingMethod(TestServiceGrpc.getCalculateClientStreamMethod())
.willReturn(Response.newBuilder().setMessage(RESPONSE_MESSAGE).build())
);
GrpcMock.stubFor(
bidiStreamingMethod(TestServiceGrpc.getCalculateBidiStreamMethod())
.willProxyTo(responseObserver -> new StreamObserver<Request>() {
@Override
public void onNext(Request request) {
responseObserver.onNext(Response.newBuilder().setMessage(RESPONSE_MESSAGE).build());
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
})
);
}
@AfterEach
void shutdownChannel() {
Optional.ofNullable(managedChannel).ifPresent(ManagedChannel::shutdown);
}
@Test
void shouldCreateRequestAttachment() {
Request request = Request.newBuilder()
.setTopic("1")
.build();
Status errorStatus = Status.NOT_FOUND;
GrpcMock.stubFor(unaryMethod(TestServiceGrpc.getCalculateMethod()).willReturn(errorStatus));
AllureResults allureResults = executeUnaryExpectingException(request);
assertThat(allureResults.getTestResults().get(0).getSteps().get(0).getStatus())
.isEqualTo(io.qameta.allure.model.Status.FAILED);
assertThat(allureResults.getTestResults().get(0).getSteps())
.flatExtracting(StepResult::getAttachments)
.extracting(Attachment::getName)
.contains(GRPC_EXCHANGE);
}
@Test
void shouldCreateResponseAttachment() {
Request request = Request.newBuilder()
.setTopic("1")
.build();
AllureResults allureResults = executeUnary(request);
assertThat(allureResults.getTestResults().get(0).getSteps())
.flatExtracting(StepResult::getAttachments)
.extracting(Attachment::getName)
.contains(GRPC_EXCHANGE);
}
@Test
void shouldCreateResponseAttachmentForServerStreamingResponse() {
Request request = Request.newBuilder()
.setTopic("1")
.build();
AllureResults allureResults = executeServerStreaming(request);
assertThat(allureResults.getTestResults().get(0).getSteps())
.flatExtracting(StepResult::getAttachments)
.extracting(Attachment::getName)
.contains(GRPC_EXCHANGE);
}
@Test
void shouldCreateResponseAttachmentOnStatusException() {
Status notFoundStatus = Status.NOT_FOUND;
GrpcMock.stubFor(unaryMethod(TestServiceGrpc.getCalculateMethod()).willReturn(notFoundStatus));
Request request = Request.newBuilder()
.setTopic("2")
.build();
AllureResults allureResults = executeUnaryExpectingException(request);
assertThat(allureResults.getTestResults().get(0).getSteps().get(0).getStatus())
.isEqualTo(io.qameta.allure.model.Status.FAILED);
assertThat(allureResults.getTestResults().get(0).getSteps())
.flatExtracting(StepResult::getAttachments)
.extracting(Attachment::getName)
.contains(GRPC_EXCHANGE);
}
@Test
void shouldCreateAttachmentsForClientStreamingWithAsynchronousStub() {
Request firstClientRequest = Request.newBuilder().setTopic("A").build();
Request secondClientRequest = Request.newBuilder().setTopic("B").build();
final AllureResults results = Allure.step(
"Execute asynchronous client-streaming gRPC request and collect Allure results",
() -> runWithinTestContext(() -> {
final TestServiceGrpc.TestServiceStub asynchronousStub = TestServiceGrpc.newStub(managedChannel).withInterceptors(new AllureGrpc());
final List<Response> receivedResponses = new ArrayList<Response>();
final CountDownLatch streamCompleted = new CountDownLatch(1);
final AtomicReference<Throwable> streamError = new AtomicReference<>();
Allure.step("async-root-client-stream", () -> {
StreamObserver<Response> responseObserver = new StreamObserver<Response>() {
@Override
public void onNext(Response value) {
receivedResponses.add(value);
}
@Override
public void onError(Throwable throwable) {
streamError.set(throwable);
streamCompleted.countDown();
}
@Override
public void onCompleted() {
streamCompleted.countDown();
}
};
StreamObserver<Request> requestObserver = asynchronousStub.calculateClientStream(
responseObserver
);
requestObserver.onNext(firstClientRequest);
requestObserver.onNext(secondClientRequest);
requestObserver.onCompleted();
});
awaitStreamCompletion(streamCompleted, streamError);
assertThat(receivedResponses).hasSize(1);
assertThat(receivedResponses.get(0).getMessage()).isEqualTo(RESPONSE_MESSAGE);
})
);
Allure.step("Verify asynchronous client-streaming exchange evidence", () -> {
assertThat(results.getTestResults().get(0).getSteps())
.extracting(StepResult::getName)
.contains("async-root-client-stream");
assertThat(results.getAttachmentsRecursively())
.extracting(Attachment::getName)
.contains(GRPC_EXCHANGE);
});
}
@Test
void shouldCreateAttachmentsForBidirectionalStreamingWithAsynchronousStub() {
Request firstBidirectionalRequest = Request.newBuilder().setTopic("C").build();
Request secondBidirectionalRequest = Request.newBuilder().setTopic("D").build();
final AllureResults results = Allure.step(
"Execute asynchronous bidirectional gRPC stream and collect Allure results",
() -> runWithinTestContext(() -> {
final TestServiceGrpc.TestServiceStub asynchronousStub = TestServiceGrpc.newStub(managedChannel).withInterceptors(new AllureGrpc());
final List<Response> receivedResponses = new ArrayList<>();
final CountDownLatch streamCompleted = new CountDownLatch(1);
final AtomicReference<Throwable> streamError = new AtomicReference<>();
Allure.step("async-root-bidi-stream", () -> {
StreamObserver<Response> responseObserver = new StreamObserver<Response>() {
@Override
public void onNext(Response value) {
receivedResponses.add(value);
}
@Override
public void onError(Throwable throwable) {
streamError.set(throwable);
streamCompleted.countDown();
}
@Override
public void onCompleted() {
streamCompleted.countDown();
}
};
StreamObserver<Request> requestObserver = asynchronousStub.calculateBidiStream(
responseObserver
);
requestObserver.onNext(firstBidirectionalRequest);
requestObserver.onNext(secondBidirectionalRequest);
requestObserver.onCompleted();
});
awaitStreamCompletion(streamCompleted, streamError);
assertThat(receivedResponses).hasSize(2);
assertThat(receivedResponses.get(0).getMessage()).isEqualTo(RESPONSE_MESSAGE);
assertThat(receivedResponses.get(1).getMessage()).isEqualTo(RESPONSE_MESSAGE);
})
);
Allure.step("Verify asynchronous bidirectional exchange evidence", () -> {
assertThat(results.getTestResults().get(0).getSteps())
.extracting(StepResult::getName)
.contains("async-root-bidi-stream");
assertThat(results.getAttachmentsRecursively())
.extracting(Attachment::getName)
.contains(GRPC_EXCHANGE);
});
}
@Test
void unaryRequestBodyIsCapturedAsJsonObject() throws Exception {
GrpcMock.stubFor(
unaryMethod(TestServiceGrpc.getCalculateMethod())
.willReturn(Response.newBuilder().setMessage("ok").build())
);
Request request = Request.newBuilder().setTopic("topic-1").build();
AllureResults allureResults = Allure.step(
"Execute unary gRPC request and collect Allure results",
() -> runWithinTestContext(() -> {
TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(managedChannel).withInterceptors(new AllureGrpc());
Response response = stub.calculate(request);
assertThat(response.getMessage()).isEqualTo("ok");
})
);
JsonNode exchange = readGrpcExchangeAttachment(allureResults);
JsonNode actualJsonNode = JSON.readTree(exchange.at("/request/body/value").asText());
JsonNode expectedJsonNode = JSON.createObjectNode().put("topic", "topic-1");
assertThat(actualJsonNode).isEqualTo(expectedJsonNode);
assertThat(exchange.at("/request/method").asText()).isEqualTo("POST");
assertThat(exchange.at("/request/httpVersion").asText()).isEqualTo("HTTP/2");
assertThat(exchange.at("/request/body/contentType").asText()).isEqualTo("application/grpc+json");
}
@Test
void unaryRequestMetadataIsCapturedWhenEnabled() throws Exception {
Request request = Request.newBuilder().setTopic("topic-with-metadata").build();
Metadata requestHeaders = new Metadata();
requestHeaders.put(REQUEST_ID_HEADER, "request-42");
AllureResults allureResults = executeUnaryWithMetadata(
request,
requestHeaders,
true
);
JsonNode exchange = readGrpcExchangeAttachment(allureResults);
assertThat(findValueByName(exchange.at("/request/headers"), REQUEST_ID_HEADER.name()))
.contains("request-42");
}
@Test
void unaryRequestMetadataIsNotCapturedWhenDisabled() throws Exception {
Request request = Request.newBuilder().setTopic("topic-without-metadata").build();
Metadata requestHeaders = new Metadata();
requestHeaders.put(REQUEST_ID_HEADER, "request-42");
AllureResults allureResults = executeUnaryWithMetadata(
request,
requestHeaders,
false
);
JsonNode exchange = readGrpcExchangeAttachment(allureResults);
assertThat(findValueByName(exchange.at("/request/headers"), REQUEST_ID_HEADER.name()))
.isEmpty();
}
@Test
void unaryResponseBodyIsCapturedAsJsonObject() throws Exception {
GrpcMock.stubFor(
unaryMethod(TestServiceGrpc.getCalculateMethod())
.willReturn(Response.newBuilder().setMessage("hello-world").build())
);
Request request = Request.newBuilder().setTopic("x").build();
AllureResults allureResults = Allure.step(
"Execute unary gRPC request and collect Allure results",
() -> runWithinTestContext(() -> {
TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(managedChannel).withInterceptors(new AllureGrpc());
Response response = stub.calculate(request);
assertThat(response.getMessage()).isEqualTo("hello-world");
})
);
JsonNode exchange = readGrpcExchangeAttachment(allureResults);
JsonNode actualJsonNode = JSON.readTree(exchange.at("/response/body/value").asText());
JsonNode expectedJsonNode = JSON.createObjectNode().put("message", "hello-world");
assertThat(actualJsonNode).isEqualTo(expectedJsonNode);
assertThat(findValueByName(exchange.at("/response/trailers"), "grpc-status")).contains("0");
}
@Test
void serverStreamingResponseBodyIsJsonArrayInOrder() throws Exception {
GrpcMock.stubFor(
serverStreamingMethod(TestServiceGrpc.getCalculateServerStreamMethod())
.willReturn(
asList(
Response.newBuilder().setMessage("first").build(),
Response.newBuilder().setMessage("second").build()
)
)
);
Request request = Request.newBuilder().setTopic("stream-topic").build();
AllureResults allureResults = Allure.step(
"Execute server-streaming gRPC request and collect Allure results",
() -> runWithinTestContext(() -> {
TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(managedChannel).withInterceptors(new AllureGrpc());
Iterator<Response> responseIterator = stub.calculateServerStream(request);
assertThat(responseIterator.hasNext()).isTrue();
assertThat(responseIterator.next().getMessage()).isEqualTo("first");
assertThat(responseIterator.hasNext()).isTrue();
assertThat(responseIterator.next().getMessage()).isEqualTo("second");
assertThat(responseIterator.hasNext()).isFalse();
})
);
JsonNode exchange = readGrpcExchangeAttachment(allureResults);
JsonNode actualJsonArray = JSON.readTree(exchange.at("/response/body/value").asText());
assertThat(actualJsonArray.isArray()).isTrue();
assertThat(actualJsonArray.size()).isEqualTo(2);
assertThat(actualJsonArray.get(0)).isEqualTo(JSON.createObjectNode().put("message", "first"));
assertThat(actualJsonArray.get(1)).isEqualTo(JSON.createObjectNode().put("message", "second"));
assertThat(exchange.at("/response/body/stream/type").asText()).isEqualTo("grpc");
assertThat(exchange.at("/response/body/stream/chunkCount").asLong()).isEqualTo(2L);
}
private static void awaitStreamCompletion(
final CountDownLatch streamCompleted,
final AtomicReference<Throwable> streamError) {
Allure.step("Wait for asynchronous gRPC stream completion", () -> {
assertThat(streamCompleted.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(streamError.get()).isNull();
});
}
private static JsonNode readGrpcExchangeAttachment(AllureResults allureResults) throws Exception {
List<Attachment> attachments = allureResults.getAttachmentsRecursively();
assertThat(attachments)
.extracting(Attachment::getType)
.doesNotContain("text/html");
Attachment matchedAttachment = attachments.stream()
.filter(attachment -> GRPC_EXCHANGE.equals(attachment.getName()))
.findFirst()
.orElseThrow(
() -> new IllegalStateException(
"Attachment not found: " + GRPC_EXCHANGE
+ ", attachments=" + attachments
+ ", raw=" + allureResults.getAttachments().keySet()
)
);
assertThat(matchedAttachment.getType()).isEqualTo(HttpExchange.CONTENT_TYPE);
assertThat(matchedAttachment.getSource()).endsWith(HttpExchange.FILE_EXTENSION);
return JSON.readTree(allureResults.getAttachmentContentAsString(matchedAttachment));
}
private static Optional<String> findValueByName(final JsonNode values, final String name) {
for (JsonNode value : values) {
if (name.equals(value.path("name").asText())) {
return Optional.of(value.path("value").asText());
}
}
return Optional.empty();
}
protected final AllureResults executeUnary(Request request) {
return Allure.step(
"Execute unary gRPC request and collect Allure results",
() -> runWithinTestContext(() -> {
try {
TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(managedChannel).withInterceptors(new AllureGrpc());
Response response = stub.calculate(request);
assertThat(response.getMessage()).isEqualTo(RESPONSE_MESSAGE);
} catch (Exception exception) {
throw new RuntimeException("Could not execute request " + request, exception);
}
})
);
}
protected final AllureResults executeServerStreaming(Request request) {
return Allure.step(
"Execute server-streaming gRPC request and collect Allure results",
() -> runWithinTestContext(() -> {
try {
TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(managedChannel).withInterceptors(new AllureGrpc());
Iterator<Response> responseIterator = stub.calculateServerStream(request);
int responseCount = 0;
while (responseIterator.hasNext()) {
assertThat(responseIterator.next().getMessage()).isEqualTo(RESPONSE_MESSAGE);
responseCount++;
}
assertThat(responseCount).isEqualTo(2);
} catch (Exception exception) {
throw new RuntimeException("Could not execute request " + request, exception);
}
})
);
}
protected final AllureResults executeUnaryExpectingException(Request request) {
return Allure.step(
"Execute unary gRPC request expecting a status exception and collect Allure results",
() -> runWithinTestContext(
() -> assertThatExceptionOfType(StatusRuntimeException.class)
.isThrownBy(() -> {
TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(managedChannel)
.withInterceptors(new AllureGrpc());
Response response = stub.calculate(request);
assertThat(response.getMessage()).isEqualTo("ok");
})
)
);
}
protected final AllureResults executeUnaryWithMetadata(
final Request request,
final Metadata requestHeaders,
final boolean interceptRequestMetadata) {
return Allure.step(
"Execute unary gRPC request with custom metadata and collect Allure results",
() -> runWithinTestContext(() -> {
try {
AllureGrpc interceptor = new RequestMetadataAllureGrpc(
requestHeaders,
interceptRequestMetadata
);
TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(managedChannel)
.withInterceptors(interceptor);
Response response = stub.calculate(request);
assertThat(response.getMessage()).isEqualTo(RESPONSE_MESSAGE);
} catch (Exception exception) {
throw new RuntimeException("Could not execute request " + request, exception);
}
})
);
}
private static final class RequestMetadataAllureGrpc extends AllureGrpc {
private final Metadata requestHeaders;
RequestMetadataAllureGrpc(final Metadata requestHeaders, final boolean interceptRequestMetadata) {
super(Allure.getLifecycle(), true, interceptRequestMetadata, false);
this.requestHeaders = new Metadata();
this.requestHeaders.merge(requestHeaders);
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
final MethodDescriptor<ReqT, RespT> method,
final CallOptions callOptions,
final Channel next) {
final ClientCall<ReqT, RespT> delegate = super.interceptCall(method, callOptions, next);
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(delegate) {
@Override
public void start(final Listener<RespT> responseListener, final Metadata headers) {
headers.merge(requestHeaders);
super.start(responseListener, headers);
}
};
}
}
}