-
Notifications
You must be signed in to change notification settings - Fork 14
/
TestUtils.java
847 lines (729 loc) · 28.4 KB
/
TestUtils.java
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
// Copyright (c) 2020-2022 VMware, Inc. or its affiliates. All rights reserved.
//
// This software, the RabbitMQ Stream Java client library, is dual-licensed under the
// Mozilla Public License 2.0 ("MPL"), and the Apache License version 2 ("ASL").
// For the MPL, please see LICENSE-MPL-RabbitMQ. For the ASL,
// please see LICENSE-APACHE2.
//
// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
// either express or implied. See the LICENSE file for specific language governing
// rights and limitations of this software.
//
// If you have any questions regarding licensing, please contact us at
// info@rabbitmq.com.
package com.rabbitmq.stream.impl;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import ch.qos.logback.classic.Level;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.stream.Address;
import com.rabbitmq.stream.Constants;
import com.rabbitmq.stream.Host;
import com.rabbitmq.stream.Message;
import com.rabbitmq.stream.MessageBuilder;
import com.rabbitmq.stream.StreamException;
import com.rabbitmq.stream.impl.Client.Broker;
import com.rabbitmq.stream.impl.Client.ClientParameters;
import com.rabbitmq.stream.impl.Client.Response;
import com.rabbitmq.stream.impl.Client.StreamMetadata;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import org.assertj.core.api.AssertDelegateTarget;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store.CloseableResource;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class TestUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(TestUtils.class);
private TestUtils() {}
public static Duration waitAtMost(CallableBooleanSupplier condition) throws Exception {
return waitAtMost(10, condition, null);
}
public static Duration waitAtMost(CallableBooleanSupplier condition, Supplier<String> message)
throws Exception {
return waitAtMost(10, condition, message);
}
public static Duration waitAtMost(Duration timeout, CallableBooleanSupplier condition)
throws Exception {
return waitAtMost((int) timeout.getSeconds(), condition, null);
}
public static Duration waitAtMost(int timeoutInSeconds, CallableBooleanSupplier condition)
throws Exception {
return waitAtMost(timeoutInSeconds, condition, null);
}
static Duration waitAtMost(
int timeoutInSeconds, CallableBooleanSupplier condition, Supplier<String> message)
throws Exception {
if (condition.getAsBoolean()) {
return Duration.ZERO;
}
int waitTime = 100;
int waitedTime = 0;
int timeoutInMs = timeoutInSeconds * 1000;
while (waitedTime <= timeoutInMs) {
Thread.sleep(waitTime);
waitedTime += waitTime;
if (condition.getAsBoolean()) {
return Duration.ofMillis(waitedTime);
}
}
if (message == null) {
fail("Waited " + timeoutInSeconds + " second(s), condition never got true");
} else {
fail("Waited " + timeoutInSeconds + " second(s), " + message.get());
}
return Duration.ofMillis(waitedTime);
}
static Address localhost() {
return new Address("localhost", Client.DEFAULT_PORT);
}
static Address localhostTls() {
return new Address("localhost", Client.DEFAULT_TLS_PORT);
}
static byte b(int value) {
return (byte) value;
}
static void publishAndWaitForConfirms(
TestUtils.ClientFactory cf, int publishCount, String stream) {
publishAndWaitForConfirms(cf, "message", publishCount, stream);
}
static void publishAndWaitForConfirms(
TestUtils.ClientFactory cf, String messagePrefix, int publishCount, String stream) {
AtomicLong sequence = new AtomicLong(0);
publishAndWaitForConfirms(
cf,
builder ->
builder
.addData(
(messagePrefix + sequence.getAndIncrement()).getBytes(StandardCharsets.UTF_8))
.build(),
publishCount,
stream);
}
static void publishAndWaitForConfirms(
TestUtils.ClientFactory cf,
Function<MessageBuilder, Message> messageFactory,
int publishCount,
String stream) {
CountDownLatch latchConfirm = new CountDownLatch(publishCount);
Client.PublishConfirmListener publishConfirmListener =
(publisherId, correlationId) -> latchConfirm.countDown();
Client client =
cf.get(new Client.ClientParameters().publishConfirmListener(publishConfirmListener));
client.declarePublisher(b(1), null, stream);
for (int i = 1; i <= publishCount; i++) {
Message message = messageFactory.apply(client.messageBuilder());
client.publish(b(1), Collections.singletonList(message));
}
latchAssert(latchConfirm).completes(Duration.ofSeconds(60));
}
static Consumer<Object> namedTask(TaskWithException task, String description) {
return new Consumer<Object>() {
@Override
public void accept(Object o) {
try {
task.run(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return description;
}
};
}
static <T> Consumer<T> namedConsumer(Consumer<T> delegate, String description) {
return new Consumer<T>() {
@Override
public void accept(T t) {
delegate.accept(t);
}
@Override
public String toString() {
return description;
}
};
}
static Answer<Void> answer(Runnable task) {
return invocationOnMock -> {
task.run();
return null;
};
}
static Answer<Void> answer(Consumer<InvocationOnMock> invocation) {
return invocationOnMock -> {
invocation.accept(invocationOnMock);
return null;
};
}
static <T> void doIfNotNull(T obj, Consumer<T> action) {
if (obj != null) {
action.accept(obj);
}
}
static void declareSuperStreamTopology(Connection connection, String superStream, int partitions)
throws Exception {
declareSuperStreamTopology(
connection,
superStream,
IntStream.range(0, partitions).mapToObj(String::valueOf).toArray(String[]::new));
}
static void declareSuperStreamTopology(Connection connection, String superStream, String... rks)
throws Exception {
try (Channel ch = connection.createChannel()) {
ch.exchangeDeclare(superStream, BuiltinExchangeType.DIRECT, true);
List<Tuple2<String, Integer>> bindings = new ArrayList<>(rks.length);
for (int i = 0; i < rks.length; i++) {
bindings.add(Tuple.of(rks[i], i));
}
// shuffle the order to make sure we get in the correct order from the server
Collections.shuffle(bindings);
for (Tuple2<String, Integer> binding : bindings) {
String routingKey = binding._1();
String partitionName = superStream + "-" + routingKey;
ch.queueDeclare(
partitionName, true, false, false, Collections.singletonMap("x-queue-type", "stream"));
ch.queueBind(
partitionName,
superStream,
routingKey,
Collections.singletonMap("x-stream-partition-order", binding._2()));
}
}
}
static void deleteSuperStreamTopology(Connection connection, String superStream, int partitions)
throws Exception {
deleteSuperStreamTopology(
connection,
superStream,
IntStream.range(0, partitions).mapToObj(String::valueOf).toArray(String[]::new));
}
static void deleteSuperStreamTopology(
Connection connection, String superStream, String... routingKeys) throws Exception {
try (Channel ch = connection.createChannel()) {
ch.exchangeDelete(superStream);
for (String routingKey : routingKeys) {
String partitionName = superStream + "-" + routingKey;
ch.queueDelete(partitionName);
}
}
}
public static String streamName(TestInfo info) {
return streamName(info.getTestClass().get(), info.getTestMethod().get());
}
private static String streamName(ExtensionContext context) {
return streamName(context.getTestInstance().get().getClass(), context.getTestMethod().get());
}
private static String streamName(Class<?> testClass, Method testMethod) {
String uuid = UUID.randomUUID().toString();
return String.format(
"%s_%s%s",
testClass.getSimpleName(), testMethod.getName(), uuid.substring(uuid.length() / 2));
}
static boolean tlsAvailable() {
if (Host.rabbitmqctlCommand() == null) {
throw new IllegalStateException(
"rabbitmqctl.bin system property not set, cannot check if TLS is enabled");
} else {
try {
Process process = Host.rabbitmqctl("status");
String output = capture(process.getInputStream());
return output.contains("stream/ssl");
} catch (Exception e) {
throw new RuntimeException("Error while trying to detect TLS: " + e.getMessage());
}
}
}
private static String capture(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder buff = new StringBuilder();
while ((line = br.readLine()) != null) {
buff.append(line).append("\n");
}
return buff.toString();
}
static <T> void forEach(Collection<T> in, CallableIndexConsumer<T> consumer) throws Exception {
int count = 0;
for (T t : in) {
consumer.accept(count++, t);
}
}
static CountDownLatchAssert latchAssert(CountDownLatch latch) {
return new CountDownLatchAssert(latch);
}
static CountDownLatchAssert latchAssert(AtomicReference<CountDownLatch> latchReference) {
return new CountDownLatchAssert(latchReference.get());
}
static class ResponseConditions {
static Condition<Response> ok() {
return new Condition<>(Response::isOk, "OK");
}
static Condition<Response> ko() {
return new Condition<>(response -> !response.isOk(), "KO");
}
static Condition<Response> responseCode(short expectedResponse) {
return new Condition<>(
response -> response.getResponseCode() == expectedResponse,
"response code %s",
Utils.formatConstant(expectedResponse));
}
}
static class ExceptionConditions {
static Condition<Throwable> responseCode(short expectedResponseCode) {
String message = "code " + Utils.formatConstant(expectedResponseCode);
return new Condition<>(
throwable ->
throwable instanceof StreamException
&& ((StreamException) throwable).getCode() == expectedResponseCode,
message);
}
}
static Map<String, StreamMetadata> metadata(String stream, Broker leader, List<Broker> replicas) {
return metadata(stream, leader, replicas, Constants.RESPONSE_CODE_OK);
}
static Map<String, StreamMetadata> metadata(
String stream, Broker leader, List<Broker> replicas, short code) {
return Collections.singletonMap(
stream, new Client.StreamMetadata(stream, code, leader, replicas));
}
static Map<String, StreamMetadata> metadata(Broker leader, List<Broker> replicas) {
return metadata("stream", leader, replicas);
}
private static String currentVersion(String currentVersion) {
// versions built from source: 3.7.0+rc.1.4.gedc5d96
if (currentVersion.contains("+")) {
currentVersion = currentVersion.substring(0, currentVersion.indexOf("+"));
}
// alpha (snapshot) versions: 3.7.0~alpha.449-1
if (currentVersion.contains("~")) {
currentVersion = currentVersion.substring(0, currentVersion.indexOf("~"));
}
// alpha (snapshot) versions: 3.7.1-alpha.40
if (currentVersion.contains("-")) {
currentVersion = currentVersion.substring(0, currentVersion.indexOf("-"));
}
return currentVersion;
}
static boolean atLeastVersion(String expectedVersion, String currentVersion) {
if (currentVersion.contains("alpha-stream")) {
return true;
}
try {
currentVersion = currentVersion(currentVersion);
return "0.0.0".equals(currentVersion) || versionCompare(currentVersion, expectedVersion) >= 0;
} catch (RuntimeException e) {
LoggerFactory.getLogger(TestUtils.class)
.warn("Unable to parse broker version {}", currentVersion, e);
throw e;
}
}
/**
* https://stackoverflow.com/questions/6701948/efficient-way-to-compare-version-strings-in-java
*/
static int versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
return Integer.signum(vals1.length - vals2.length);
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ExtendWith(DisabledIfRabbitMqCtlNotSetCondition.class)
@interface DisabledIfRabbitMqCtlNotSet {}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ExtendWith(DisabledIfMqttNotEnabledCondition.class)
@interface DisabledIfMqttNotEnabled {}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ExtendWith(DisabledIfStompNotEnabledCondition.class)
@interface DisabledIfStompNotEnabled {}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ExtendWith(DisabledIfTlsNotEnabledCondition.class)
public @interface DisabledIfTlsNotEnabled {}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ExtendWith(BrokerVersionAtLeastCondition.class)
public @interface BrokerVersionAtLeast {
String value();
}
interface TaskWithException {
void run(Object context) throws Exception;
}
interface CallableIndexConsumer<T> {
void accept(int index, T t) throws Exception;
}
public interface CallableConsumer<T> {
void accept(T t) throws Exception;
}
@FunctionalInterface
public interface CallableBooleanSupplier {
boolean getAsBoolean() throws Exception;
}
interface RunnableWithException {
void run() throws Exception;
}
static class CountDownLatchConditions {
static Condition<CountDownLatch> completed() {
return completed(Duration.ofSeconds(10));
}
static Condition<CountDownLatch> completed(int timeoutInSeconds) {
return completed(Duration.ofSeconds(timeoutInSeconds));
}
static Condition<CountDownLatch> completed(Duration timeout) {
return new Condition<>(
latch -> {
try {
return latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.interrupted();
throw new RuntimeException(e);
}
},
"completed in %d ms",
timeout.toMillis());
}
}
public static class StreamTestInfrastructureExtension
implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback {
private static final ExtensionContext.Namespace NAMESPACE =
ExtensionContext.Namespace.create(StreamTestInfrastructureExtension.class);
private static ExtensionContext.Store store(ExtensionContext extensionContext) {
return extensionContext.getRoot().getStore(NAMESPACE);
}
static EventLoopGroup eventLoopGroup(ExtensionContext context) {
return (EventLoopGroup) store(context).get("nettyEventLoopGroup");
}
@Override
public void beforeAll(ExtensionContext context) {
store(context).put("nettyEventLoopGroup", new NioEventLoopGroup());
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
try {
Field streamField =
context.getTestInstance().get().getClass().getDeclaredField("eventLoopGroup");
streamField.setAccessible(true);
streamField.set(context.getTestInstance().get(), eventLoopGroup(context));
} catch (NoSuchFieldException e) {
}
try {
Field streamField = context.getTestInstance().get().getClass().getDeclaredField("stream");
streamField.setAccessible(true);
String stream = streamName(context);
streamField.set(context.getTestInstance().get(), stream);
Client client =
new Client(new Client.ClientParameters().eventLoopGroup(eventLoopGroup(context)));
Client.Response response = client.create(stream);
assertThat(response.isOk()).isTrue();
client.close();
store(context).put("testMethodStream", stream);
} catch (NoSuchFieldException e) {
}
for (Field declaredField : context.getTestInstance().get().getClass().getDeclaredFields()) {
if (declaredField.getType().equals(ClientFactory.class)) {
declaredField.setAccessible(true);
ClientFactory clientFactory = new ClientFactory(eventLoopGroup(context));
declaredField.set(context.getTestInstance().get(), clientFactory);
store(context).put("testClientFactory", clientFactory);
break;
}
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
ClientFactory clientFactory = (ClientFactory) store(context).get("testClientFactory");
if (clientFactory != null) {
clientFactory.close();
}
try {
Field streamField = context.getTestInstance().get().getClass().getDeclaredField("stream");
streamField.setAccessible(true);
String stream = (String) streamField.get(context.getTestInstance().get());
Client client =
new Client(new Client.ClientParameters().eventLoopGroup(eventLoopGroup(context)));
Client.Response response = client.delete(stream);
assertThat(response.isOk()).isTrue();
client.close();
store(context).remove("testMethodStream");
} catch (NoSuchFieldException e) {
}
}
@Override
public void afterAll(ExtensionContext context) {
EventLoopGroup eventLoopGroup = eventLoopGroup(context);
ExecutorServiceCloseableResourceWrapper wrapper =
context
.getRoot()
.getStore(Namespace.GLOBAL)
.getOrComputeIfAbsent(ExecutorServiceCloseableResourceWrapper.class);
wrapper.executorService.submit(
() -> {
try {
eventLoopGroup.shutdownGracefully(1, 10, SECONDS).get(10, SECONDS);
} catch (InterruptedException e) {
// happens at the end of the test suite
LOGGER.debug("Error while asynchronously closing Netty event loop group", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
LOGGER.warn("Error while asynchronously closing Netty event loop group", e);
}
});
}
private static class ExecutorServiceCloseableResourceWrapper implements CloseableResource {
private final ExecutorService executorService;
private ExecutorServiceCloseableResourceWrapper() {
this.executorService = Executors.newCachedThreadPool();
}
@Override
public void close() throws Throwable {
this.executorService.shutdownNow();
}
}
}
public static class ClientFactory {
private final EventLoopGroup eventLoopGroup;
private final Set<Client> clients = ConcurrentHashMap.newKeySet();
public ClientFactory(EventLoopGroup eventLoopGroup) {
this.eventLoopGroup = eventLoopGroup;
}
public Client get() {
return get(new Client.ClientParameters());
}
public Client get(Client.ClientParameters parameters) {
Client client = new Client(parameters.eventLoopGroup(eventLoopGroup));
clients.add(client);
return client;
}
private void close() {
for (Client c : clients) {
c.close();
}
}
}
static class DisabledIfRabbitMqCtlNotSetCondition implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
if (Host.rabbitmqctlCommand() == null) {
return ConditionEvaluationResult.disabled("rabbitmqctl.bin system property not set");
} else {
return ConditionEvaluationResult.enabled("rabbitmqctl.bin system property is set");
}
}
}
static class DisabledIfMqttNotEnabledCondition implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
if (Host.rabbitmqctlCommand() == null) {
return ConditionEvaluationResult.disabled(
"rabbitmqctl.bin system property not set, cannot check if MQTT plugin is enabled");
} else {
try {
Process process = Host.rabbitmqctl("status");
String output = capture(process.getInputStream());
if (output.contains("rabbitmq_mqtt") && output.contains("protocol: mqtt")) {
return ConditionEvaluationResult.enabled("MQTT plugin enabled");
} else {
return ConditionEvaluationResult.disabled("MQTT plugin disabled");
}
} catch (Exception e) {
return ConditionEvaluationResult.disabled(
"Error while trying to detect MQTT plugin: " + e.getMessage());
}
}
}
}
static class DisabledIfStompNotEnabledCondition implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
if (Host.rabbitmqctlCommand() == null) {
return ConditionEvaluationResult.disabled(
"rabbitmqctl.bin system property not set, cannot check if STOMP plugin is enabled");
} else {
try {
Process process = Host.rabbitmqctl("status");
String output = capture(process.getInputStream());
if (output.contains("rabbitmq_stomp") && output.contains("protocol: stomp")) {
return ConditionEvaluationResult.enabled("STOMP plugin enabled");
} else {
return ConditionEvaluationResult.disabled("STOMP plugin disabled");
}
} catch (Exception e) {
return ConditionEvaluationResult.disabled(
"Error while trying to detect STOMP plugin: " + e.getMessage());
}
}
}
}
static class DisabledIfTlsNotEnabledCondition implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
if (tlsAvailable()) {
return ConditionEvaluationResult.enabled("TLS is enabled");
} else {
return ConditionEvaluationResult.disabled("TLS is disabled");
}
}
}
static class BrokerVersionAtLeastCondition implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Optional<AnnotatedElement> element = context.getElement();
// String expectedVersion = annotation.get().getAnnotation(BrokerVersionAtLeast.class);
BrokerVersionAtLeast annotation = element.get().getAnnotation(BrokerVersionAtLeast.class);
if (annotation == null) {
return ConditionEvaluationResult.enabled("No broker version requirement");
} else {
EventLoopGroup eventLoopGroup = StreamTestInfrastructureExtension.eventLoopGroup(context);
if (eventLoopGroup == null) {
throw new IllegalStateException(
"The event loop group must be in the test context to use "
+ BrokerVersionAtLeast.class.getSimpleName()
+ ", use the "
+ StreamTestInfrastructureExtension.class.getSimpleName()
+ " extension in the test");
}
Client client = new Client(new ClientParameters().eventLoopGroup(eventLoopGroup));
String expectedVersion = annotation.value();
String brokerVersion = client.brokerVersion();
client.close();
if (atLeastVersion(expectedVersion, brokerVersion)) {
return ConditionEvaluationResult.enabled(
"Broker version requirement met, expected "
+ expectedVersion
+ ", actual "
+ brokerVersion);
} else {
return ConditionEvaluationResult.disabled(
"Broker version requirement not met, expected "
+ expectedVersion
+ ", actual "
+ brokerVersion);
}
}
}
}
static class CountDownLatchAssert implements AssertDelegateTarget {
private static final Duration TIMEOUT = Duration.ofSeconds(10);
private final CountDownLatch latch;
CountDownLatchAssert(CountDownLatch latch) {
this.latch = latch;
}
void completes() {
completes(TIMEOUT);
}
void completes(int timeoutInSeconds) {
completes(Duration.ofSeconds(timeoutInSeconds));
}
void completes(Duration timeout) {
try {
assertThat(latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS)).isTrue();
} catch (InterruptedException e) {
Thread.interrupted();
throw new RuntimeException(e);
}
}
void doesNotComplete() {
doesNotComplete(TIMEOUT);
}
void doesNotComplete(int timeoutInSeconds) {
doesNotComplete(Duration.ofSeconds(timeoutInSeconds));
}
void doesNotComplete(Duration timeout) {
try {
assertThat(latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS)).isFalse();
} catch (InterruptedException e) {
Thread.interrupted();
throw new RuntimeException(e);
}
}
}
static Level newLoggerLevel(Class<?> c, Level level) {
ch.qos.logback.classic.Logger logger =
(ch.qos.logback.classic.Logger) LoggerFactory.getLogger(c);
Level initialLevel = logger.getEffectiveLevel();
logger.setLevel(level);
return initialLevel;
}
static void waitMs(long waitTime) {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Tag("single-active-consumer")
public @interface SingleActiveConsumer {}
}