-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
QuarkusTestExtension.java
1346 lines (1227 loc) · 60.2 KB
/
QuarkusTestExtension.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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package io.quarkus.test.junit;
import static io.quarkus.test.junit.IntegrationTestUtil.activateLogging;
import static io.quarkus.test.junit.IntegrationTestUtil.getAdditionalTestResources;
import java.io.Closeable;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.file.Path;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.AbstractMap;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.Index;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.jupiter.api.extension.TestInstantiationException;
import org.opentest4j.TestAbortedException;
import io.quarkus.bootstrap.app.AugmentAction;
import io.quarkus.bootstrap.app.RunningQuarkusApplication;
import io.quarkus.bootstrap.app.StartupAction;
import io.quarkus.bootstrap.classloading.ClassPathElement;
import io.quarkus.bootstrap.classloading.QuarkusClassLoader;
import io.quarkus.bootstrap.logging.InitialConfigurator;
import io.quarkus.builder.BuildChainBuilder;
import io.quarkus.builder.BuildContext;
import io.quarkus.builder.BuildStep;
import io.quarkus.deployment.builditem.ApplicationClassPredicateBuildItem;
import io.quarkus.deployment.builditem.TestAnnotationBuildItem;
import io.quarkus.deployment.builditem.TestClassBeanBuildItem;
import io.quarkus.deployment.builditem.TestClassPredicateBuildItem;
import io.quarkus.deployment.builditem.TestProfileBuildItem;
import io.quarkus.dev.testing.ExceptionReporting;
import io.quarkus.dev.testing.TracingHandler;
import io.quarkus.runtime.ApplicationLifecycleManager;
import io.quarkus.runtime.LaunchMode;
import io.quarkus.runtime.configuration.DurationConverter;
import io.quarkus.runtime.logging.JBossVersion;
import io.quarkus.runtime.test.TestHttpEndpointProvider;
import io.quarkus.test.TestMethodInvoker;
import io.quarkus.test.common.GroovyClassValue;
import io.quarkus.test.common.PathTestHelper;
import io.quarkus.test.common.PropertyTestUtil;
import io.quarkus.test.common.RestAssuredURLManager;
import io.quarkus.test.common.RestorableSystemProperties;
import io.quarkus.test.common.TestClassIndexer;
import io.quarkus.test.common.TestResourceManager;
import io.quarkus.test.common.TestScopeManager;
import io.quarkus.test.common.http.TestHTTPEndpoint;
import io.quarkus.test.common.http.TestHTTPResourceManager;
import io.quarkus.test.junit.buildchain.TestBuildChainCustomizerProducer;
import io.quarkus.test.junit.callback.QuarkusTestContext;
import io.quarkus.test.junit.callback.QuarkusTestMethodContext;
import io.quarkus.test.junit.internal.DeepClone;
import io.quarkus.test.junit.internal.NewSerializingDeepClone;
public class QuarkusTestExtension extends AbstractJvmQuarkusTestExtension
implements BeforeEachCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback, AfterEachCallback,
BeforeAllCallback, InvocationInterceptor, AfterAllCallback,
ParameterResolver, ExecutionCondition {
private static final Logger log = Logger.getLogger(QuarkusTestExtension.class);
public static final String QUARKUS_TEST_HANG_DETECTION_TIMEOUT = "quarkus.test.hang-detection-timeout";
private static boolean failedBoot;
private static Class<?> actualTestClass;
private static Object actualTestInstance;
// needed for @Nested
private static final Deque<Object> outerInstances = new ArrayDeque<>(1);
private static RunningQuarkusApplication runningQuarkusApplication;
private static Throwable firstException; //if this is set then it will be thrown from the very first test that is run, the rest are aborted
private static Class<?> quarkusTestMethodContextClass;
private static boolean hasPerTestResources;
private static List<Function<Class<?>, String>> testHttpEndpointProviders;
private static List<Object> testMethodInvokers;
private static DeepClone deepClone;
private static volatile ScheduledExecutorService hangDetectionExecutor;
private static volatile Duration hangTimeout;
private static volatile ScheduledFuture<?> hangTaskKey;
private static final Runnable hangDetectionTask = new Runnable() {
final AtomicBoolean runOnce = new AtomicBoolean();
@Override
public void run() {
if (!runOnce.compareAndSet(false, true)) {
return;
}
System.err.println("@QuarkusTest has detected a hang, as there has been no test activity in " + hangTimeout);
System.err.println("To configure this timeout use the " + QUARKUS_TEST_HANG_DETECTION_TIMEOUT + " config property");
System.err.println("A stack trace is below to help diagnose the potential hang");
System.err.println("=== Stack Trace ===");
ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
for (ThreadInfo info : threads) {
if (info == null) {
System.err.println(" Inactive");
continue;
}
Thread.State state = info.getThreadState();
System.err.println("Thread " + info.getThreadName() + ": " + state);
if (state == Thread.State.WAITING) {
System.err.println(" Waiting on " + info.getLockName());
} else if (state == Thread.State.BLOCKED) {
System.err.println(" Blocked on " + info.getLockName());
System.err.println(" Blocked by " + info.getLockOwnerName());
}
System.err.println(" Stack:");
for (StackTraceElement frame : info.getStackTrace()) {
System.err.println(" " + frame.toString());
}
}
System.err.println("=== End Stack Trace ===");
//we only every dump once
}
};
static {
ClassLoader classLoader = QuarkusTestExtension.class.getClassLoader();
if (classLoader instanceof QuarkusClassLoader) {
((QuarkusClassLoader) classLoader).addCloseTask(new Runnable() {
@Override
public void run() {
ScheduledExecutorService h = QuarkusTestExtension.hangDetectionExecutor;
if (h != null) {
h.shutdownNow();
QuarkusTestExtension.hangDetectionExecutor = null;
}
}
});
}
}
private ExtensionState doJavaStart(ExtensionContext context, Class<? extends QuarkusTestProfile> profile) throws Throwable {
JBossVersion.disableVersionLogging();
TracingHandler.quarkusStarting();
hangDetectionExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "Quarkus hang detection timer thread");
}
});
String time = "10m";
//config is not established yet
//we can only read from system properties
String sysPropString = System.getProperty(QUARKUS_TEST_HANG_DETECTION_TIMEOUT);
if (sysPropString != null) {
time = sysPropString;
}
hangTimeout = new DurationConverter().convert(time);
hangTaskKey = hangDetectionExecutor.schedule(hangDetectionTask, hangTimeout.toMillis(), TimeUnit.MILLISECONDS);
quarkusTestProfile = profile;
Class<?> requiredTestClass = context.getRequiredTestClass();
Closeable testResourceManager = null;
try {
final LinkedBlockingDeque<Runnable> shutdownTasks = new LinkedBlockingDeque<>();
PrepareResult result = createAugmentor(context, profile, shutdownTasks);
AugmentAction augmentAction = result.augmentAction;
QuarkusTestProfile profileInstance = result.profileInstance;
testHttpEndpointProviders = TestHttpEndpointProvider.load();
StartupAction startupAction = augmentAction.createInitialRuntimeApplication();
Thread.currentThread().setContextClassLoader(startupAction.getClassLoader());
populateDeepCloneField(startupAction);
//must be done after the TCCL has been set
testResourceManager = (Closeable) startupAction.getClassLoader().loadClass(TestResourceManager.class.getName())
.getConstructor(Class.class, Class.class, List.class, boolean.class, Map.class, Optional.class, Path.class)
.newInstance(requiredTestClass,
profile != null ? profile : null,
getAdditionalTestResources(profileInstance, startupAction.getClassLoader()),
profileInstance != null && profileInstance.disableGlobalTestResources(),
startupAction.getDevServicesProperties(), Optional.empty(), result.testClassLocation);
testResourceManager.getClass().getMethod("init", String.class).invoke(testResourceManager,
profile != null ? profile.getName() : null);
Map<String, String> properties = (Map<String, String>) testResourceManager.getClass().getMethod("start")
.invoke(testResourceManager);
startupAction.overrideConfig(properties);
startupAction.addRuntimeCloseTask(testResourceManager);
hasPerTestResources = (boolean) testResourceManager.getClass().getMethod("hasPerTestResources")
.invoke(testResourceManager);
// make sure that we start over every time we populate the callbacks
// otherwise previous runs of QuarkusTest (with different TestProfile values can leak into the new run)
quarkusTestMethodContextClass = null;
populateCallbacks(startupAction.getClassLoader());
populateTestMethodInvokers(startupAction.getClassLoader());
if (profileInstance == null || !profileInstance.runMainMethod()) {
runningQuarkusApplication = startupAction
.run(profileInstance == null ? new String[0] : profileInstance.commandLineParameters());
} else {
Class<?> lifecycleManager = Class.forName(ApplicationLifecycleManager.class.getName(), true,
startupAction.getClassLoader());
lifecycleManager.getDeclaredMethod("setDefaultExitCodeHandler", Consumer.class).invoke(null,
(Consumer<Integer>) integer -> {
});
runningQuarkusApplication = startupAction
.runMainClass(profileInstance.commandLineParameters());
}
TracingHandler.quarkusStarted();
deepClone.setRunningQuarkusApplication(runningQuarkusApplication);
//now we have full config reset the hang timer
if (hangTaskKey != null) {
hangTaskKey.cancel(false);
hangTimeout = runningQuarkusApplication.getConfigValue(QUARKUS_TEST_HANG_DETECTION_TIMEOUT, Duration.class)
.orElse(Duration.of(10, ChronoUnit.MINUTES));
hangTaskKey = hangDetectionExecutor.schedule(hangDetectionTask, hangTimeout.toMillis(), TimeUnit.MILLISECONDS);
}
ConfigProviderResolver.setInstance(new RunningAppConfigResolver(runningQuarkusApplication));
RestorableSystemProperties restorableSystemProperties = RestorableSystemProperties.setProperties(
Collections.singletonMap("test.url", TestHTTPResourceManager.getUri(runningQuarkusApplication)));
Closeable shutdownTask = new Closeable() {
@Override
public void close() throws IOException {
TracingHandler.quarkusStopping();
try {
runningQuarkusApplication.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
TracingHandler.quarkusStopped();
try {
while (!shutdownTasks.isEmpty()) {
shutdownTasks.pop().run();
}
} finally {
restorableSystemProperties.close();
shutdownHangDetection();
}
try {
TestClassIndexer.removeIndex(requiredTestClass);
} catch (Exception ignored) {
}
}
}
};
ExtensionState state = new ExtensionState(testResourceManager, shutdownTask);
return state;
} catch (Throwable e) {
if (!InitialConfigurator.DELAYED_HANDLER.isActivated()) {
activateLogging();
}
Throwable effectiveException = determineEffectiveException(e);
try {
if (testResourceManager != null) {
testResourceManager.close();
}
} catch (Exception ex) {
effectiveException.addSuppressed(determineEffectiveException(ex));
}
throw effectiveException;
} finally {
if (originalCl != null) {
Thread.currentThread().setContextClassLoader(originalCl);
}
}
}
private Throwable determineEffectiveException(Throwable e) {
Throwable effectiveException = e;
if ((e instanceof InvocationTargetException) && (e.getCause() != null)) { // QuarkusTestResourceLifecycleManager.start is called reflectively
effectiveException = e.getCause();
if ((effectiveException instanceof CompletionException) && (effectiveException.getCause() != null)) { // can happen because instances of QuarkusTestResourceLifecycleManager are started asynchronously
effectiveException = effectiveException.getCause();
}
}
return effectiveException;
}
private void shutdownHangDetection() {
if (hangTaskKey != null) {
hangTaskKey.cancel(true);
hangTaskKey = null;
}
var h = hangDetectionExecutor;
if (h != null) {
h.shutdownNow();
hangDetectionExecutor = null;
}
}
private void populateDeepCloneField(StartupAction startupAction) {
deepClone = new NewSerializingDeepClone(originalCl, startupAction.getClassLoader());
}
private void populateTestMethodInvokers(ClassLoader quarkusClassLoader) {
testMethodInvokers = new ArrayList<>();
try {
ServiceLoader<?> loader = ServiceLoader.load(quarkusClassLoader.loadClass(TestMethodInvoker.class.getName()),
quarkusClassLoader);
for (Object testMethodInvoker : loader) {
testMethodInvokers.add(testMethodInvoker);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
if (isNativeOrIntegrationTest(context.getRequiredTestClass()) || isBeforeTestCallbacksEmpty()) {
return;
}
if (!failedBoot) {
ClassLoader original = setCCL(runningQuarkusApplication.getClassLoader());
try {
Map.Entry<Class<?>, ?> tuple = createQuarkusTestMethodContextTuple(context);
invokeBeforeTestExecutionCallbacks(tuple.getKey(), tuple.getValue());
} finally {
setCCL(original);
}
} else {
throwBootFailureException();
return;
}
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
if (isNativeOrIntegrationTest(context.getRequiredTestClass())) {
return;
}
resetHangTimeout();
if (!failedBoot) {
ClassLoader original = setCCL(runningQuarkusApplication.getClassLoader());
try {
pushMockContext();
Map.Entry<Class<?>, ?> tuple = createQuarkusTestMethodContextTuple(context);
invokeBeforeEachCallbacks(tuple.getKey(), tuple.getValue());
String endpointPath = getEndpointPath(context, testHttpEndpointProviders);
if (runningQuarkusApplication != null) {
boolean secure = false;
Optional<String> insecureAllowed = runningQuarkusApplication
.getConfigValue("quarkus.http.insecure-requests", String.class);
if (insecureAllowed.isPresent()) {
secure = !insecureAllowed.get().toLowerCase(Locale.ENGLISH).equals("enabled");
}
runningQuarkusApplication.getClassLoader().loadClass(RestAssuredURLManager.class.getName())
.getDeclaredMethod("setURL", boolean.class, String.class).invoke(null, secure, endpointPath);
runningQuarkusApplication.getClassLoader().loadClass(TestScopeManager.class.getName())
.getDeclaredMethod("setup", boolean.class).invoke(null, false);
}
} finally {
setCCL(original);
}
} else {
throwBootFailureException();
return;
}
}
public static String getEndpointPath(ExtensionContext context, List<Function<Class<?>, String>> testHttpEndpointProviders) {
String endpointPath = null;
TestHTTPEndpoint testHTTPEndpoint = context.getRequiredTestMethod().getAnnotation(TestHTTPEndpoint.class);
if (testHTTPEndpoint == null) {
Class<?> clazz = context.getRequiredTestClass();
while (true) {
// go up the hierarchy because most Native tests extend from a regular Quarkus test
testHTTPEndpoint = clazz.getAnnotation(TestHTTPEndpoint.class);
if (testHTTPEndpoint != null) {
break;
}
clazz = clazz.getSuperclass();
if (clazz == Object.class) {
break;
}
}
}
if (testHTTPEndpoint != null) {
for (Function<Class<?>, String> i : testHttpEndpointProviders) {
endpointPath = i.apply(testHTTPEndpoint.value());
if (endpointPath != null) {
break;
}
}
if (endpointPath == null) {
throw new RuntimeException("Cannot determine HTTP path for endpoint " + testHTTPEndpoint.value()
+ " for test method " + context.getRequiredTestMethod());
}
}
if (endpointPath != null) {
if (endpointPath.indexOf(':') != -1) {
return sanitizeEndpointPath(endpointPath);
}
}
return endpointPath;
}
/**
* Remove any sort of regex restrictions from "variables in the path"
*/
private static String sanitizeEndpointPath(String path) {
int openBrackets = 0;
boolean inRegex = false;
StringBuilder replaced = new StringBuilder(path.length() - 1);
for (int i = 0; i < path.length(); i++) {
char c = path.charAt(i);
if (c == '{') {
openBrackets++;
} else if (c == '}') {
openBrackets--;
if (openBrackets == 0) {
inRegex = false;
}
} else if ((c == ':') && (openBrackets > 0)) {
inRegex = true;
}
if (!inRegex) {
replaced.append(c);
}
}
return replaced.toString();
}
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
if (isNativeOrIntegrationTest(context.getRequiredTestClass()) || isAfterTestCallbacksEmpty()) {
return;
}
if (!failedBoot) {
ClassLoader original = setCCL(runningQuarkusApplication.getClassLoader());
try {
Map.Entry<Class<?>, ?> tuple = createQuarkusTestMethodContextTuple(context);
invokeAfterTestExecutionCallbacks(tuple.getKey(), tuple.getValue());
} finally {
setCCL(original);
}
}
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
if (isNativeOrIntegrationTest(context.getRequiredTestClass())) {
return;
}
resetHangTimeout();
if (!failedBoot) {
popMockContext();
ClassLoader original = setCCL(runningQuarkusApplication.getClassLoader());
try {
Map.Entry<Class<?>, ?> tuple = createQuarkusTestMethodContextTuple(context);
invokeAfterEachCallbacks(tuple.getKey(), tuple.getValue());
runningQuarkusApplication.getClassLoader().loadClass(RestAssuredURLManager.class.getName())
.getDeclaredMethod("clearURL").invoke(null);
runningQuarkusApplication.getClassLoader().loadClass(TestScopeManager.class.getName())
.getDeclaredMethod("tearDown", boolean.class).invoke(null, false);
} finally {
setCCL(original);
}
}
}
// We need the usual ClassLoader hacks in order to present the callbacks with the proper test object and context
private Map.Entry<Class<?>, ?> createQuarkusTestMethodContextTuple(ExtensionContext context) throws Exception {
ClassLoader classLoader = runningQuarkusApplication.getClassLoader();
if (quarkusTestMethodContextClass == null) {
quarkusTestMethodContextClass = Class.forName(QuarkusTestMethodContext.class.getName(), true, classLoader);
}
Method originalTestMethod = context.getRequiredTestMethod();
Class<?>[] originalParameterTypes = originalTestMethod.getParameterTypes();
Method actualTestMethod = null;
// go up the class hierarchy to fetch the proper test method
Class<?> c = resolveDeclaringClass(originalTestMethod, actualTestClass);
List<Class<?>> parameterTypesFromTccl = new ArrayList<>(originalParameterTypes.length);
for (Class<?> type : originalParameterTypes) {
if (type.isPrimitive()) {
parameterTypesFromTccl.add(type);
} else {
parameterTypesFromTccl
.add(Class.forName(type.getName(), true, classLoader));
}
}
Class<?>[] parameterTypes = parameterTypesFromTccl.toArray(new Class[0]);
try {
if (c != null) {
actualTestMethod = c.getDeclaredMethod(originalTestMethod.getName(), parameterTypes);
}
} catch (NoSuchMethodException ignored) {
}
if (actualTestMethod == null) {
throw new RuntimeException("Could not find method " + originalTestMethod + " on test class");
}
QuarkusTestExtensionState state = getState(context);
Constructor<?> constructor = quarkusTestMethodContextClass.getConstructor(Object.class, List.class, Method.class,
Throwable.class);
return new AbstractMap.SimpleEntry<>(quarkusTestMethodContextClass,
constructor.newInstance(actualTestInstance, new ArrayList<>(outerInstances), actualTestMethod,
state.getTestErrorCause()));
}
private boolean isNativeOrIntegrationTest(Class<?> clazz) {
for (Class<?> i : currentTestClassStack) {
if (i.isAnnotationPresent(QuarkusIntegrationTest.class)) {
return true;
}
}
if (clazz.isAnnotationPresent(QuarkusIntegrationTest.class)) {
return true;
}
return false;
}
private QuarkusTestExtensionState ensureStarted(ExtensionContext extensionContext) {
QuarkusTestExtensionState state = getState(extensionContext);
Class<? extends QuarkusTestProfile> selectedProfile = getQuarkusTestProfile(extensionContext);
boolean wrongProfile = !Objects.equals(selectedProfile, quarkusTestProfile);
// we reset the failed state if we changed test class and the new test class is not a nested class
boolean isNewTestClass = !Objects.equals(extensionContext.getRequiredTestClass(), currentJUnitTestClass)
&& !isNested(currentJUnitTestClass, extensionContext.getRequiredTestClass());
if (isNewTestClass && state != null) {
state.setTestFailed(null);
currentJUnitTestClass = extensionContext.getRequiredTestClass();
}
// we reload the test resources if we changed test class and the new test class is not a nested class, and if we had or will have per-test test resources
boolean reloadTestResources = isNewTestClass && (hasPerTestResources || hasPerTestResources(extensionContext));
if ((state == null && !failedBoot) || wrongProfile || reloadTestResources) {
if (wrongProfile || reloadTestResources) {
if (state != null) {
try {
state.close();
} catch (Throwable throwable) {
markTestAsFailed(extensionContext, throwable);
}
}
}
PropertyTestUtil.setLogFileProperty();
try {
state = doJavaStart(extensionContext, selectedProfile);
setState(extensionContext, state);
} catch (Throwable e) {
failedBoot = true;
markTestAsFailed(extensionContext, e);
firstException = e;
getStoreFromContext(extensionContext).put(FailedCleanup.class.getName(), new FailedCleanup());
}
}
return state;
}
private boolean isNested(Class<?> testClass, Class<?> currentTestClass) {
if (testClass == null || currentTestClass.getEnclosingClass() == null) {
return false;
}
Class<?> enclosingTestClass = currentTestClass.getEnclosingClass();
return Objects.equals(testClass, enclosingTestClass) || isNested(testClass, enclosingTestClass);
}
private static ClassLoader setCCL(ClassLoader cl) {
final Thread thread = Thread.currentThread();
final ClassLoader original = thread.getContextClassLoader();
thread.setContextClassLoader(cl);
return original;
}
private void throwBootFailureException() {
if (firstException != null) {
Throwable throwable = firstException;
firstException = null;
throw new RuntimeException(throwable);
} else {
throw new TestAbortedException("Boot failed");
}
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
Class<?> requiredTestClass = context.getRequiredTestClass();
GroovyClassValue.disable();
currentTestClassStack.push(requiredTestClass);
//set the right launch mode in the outer CL, used by the HTTP host config source
LaunchMode.set(LaunchMode.TEST);
if (isNativeOrIntegrationTest(requiredTestClass)) {
return;
}
resetHangTimeout();
ensureStarted(context);
if (runningQuarkusApplication != null) {
pushMockContext();
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(runningQuarkusApplication.getClassLoader());
invokeBeforeClassCallbacks(Class.class,
runningQuarkusApplication.getClassLoader().loadClass(requiredTestClass.getName()));
} finally {
Thread.currentThread().setContextClassLoader(old);
}
} else {
// can this ever happen?
invokeBeforeClassCallbacks(Class.class, requiredTestClass);
}
}
private void pushMockContext() {
try {
//classloader issues
Method pushContext = runningQuarkusApplication.getClassLoader().loadClass(MockSupport.class.getName())
.getDeclaredMethod("pushContext");
pushContext.setAccessible(true);
pushContext.invoke(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void popMockContext() {
try {
//classloader issues
Method popContext = runningQuarkusApplication.getClassLoader().loadClass(MockSupport.class.getName())
.getDeclaredMethod("popContext");
popContext.setAccessible(true);
popContext.invoke(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void interceptBeforeAllMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
invocation.proceed();
return;
}
resetHangTimeout();
ensureStarted(extensionContext);
if (failedBoot) {
throwBootFailureException();
return;
}
runExtensionMethod(invocationContext, extensionContext);
invocation.skip();
}
@Override
public <T> T interceptTestClassConstructor(Invocation<T> invocation,
ReflectiveInvocationContext<Constructor<T>> invocationContext, ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
return invocation.proceed();
}
resetHangTimeout();
QuarkusTestExtensionState state = ensureStarted(extensionContext);
if (failedBoot) {
throwBootFailureException();
return null;
}
T result;
ClassLoader old = Thread.currentThread().getContextClassLoader();
Class<?> requiredTestClass = extensionContext.getRequiredTestClass();
try {
Thread.currentThread().setContextClassLoader(requiredTestClass.getClassLoader());
result = invocation.proceed();
} catch (NullPointerException e) {
throw new RuntimeException(
"When using constructor injection in a test, the only legal operation is to assign the constructor values to fields. Offending class is "
+ requiredTestClass,
e);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
// We do this here as well, because when @TestInstance(Lifecycle.PER_CLASS) is used on a class,
// interceptTestClassConstructor is called before beforeAll, meaning that the TCCL will not be set correctly
// (for any test other than the first) unless this is done
old = null;
if (runningQuarkusApplication != null) {
old = setCCL(runningQuarkusApplication.getClassLoader());
}
try {
initTestState(extensionContext, state);
} finally {
if (old != null) {
setCCL(old);
}
}
return result;
}
private void initTestState(ExtensionContext extensionContext, QuarkusTestExtensionState state) {
try {
actualTestClass = Class.forName(extensionContext.getRequiredTestClass().getName(), true,
Thread.currentThread().getContextClassLoader());
if (extensionContext.getRequiredTestClass().isAnnotationPresent(Nested.class)) {
Class<?> outerClass = actualTestClass.getEnclosingClass();
Constructor<?> declaredConstructor = actualTestClass.getDeclaredConstructor(outerClass);
declaredConstructor.setAccessible(true);
if (outerClass.isInstance(actualTestInstance)) {
outerInstances.add(actualTestInstance);
actualTestInstance = declaredConstructor.newInstance(actualTestInstance);
} else {
Object outerInstance = createActualTestInstance(outerClass, state);
invokeAfterConstructCallbacks(Object.class, outerInstance);
actualTestInstance = declaredConstructor.newInstance(outerInstance);
outerInstances.add(outerInstance);
}
} else {
outerInstances.clear();
actualTestInstance = createActualTestInstance(actualTestClass, state);
}
invokeAfterConstructCallbacks(Object.class, actualTestInstance);
} catch (Exception e) {
throw new TestInstantiationException("Failed to create test instance",
e instanceof InvocationTargetException ? e.getCause() : e);
}
}
private Object createActualTestInstance(Class<?> testClass, QuarkusTestExtensionState state)
throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Object testInstance = runningQuarkusApplication.instance(testClass);
Class<?> resM = Thread.currentThread().getContextClassLoader().loadClass(TestHTTPResourceManager.class.getName());
resM.getDeclaredMethod("inject", Object.class, List.class).invoke(null, testInstance,
testHttpEndpointProviders);
state.testResourceManager.getClass().getMethod("inject", Object.class).invoke(state.testResourceManager,
testInstance);
return testInstance;
}
@Override
public void interceptBeforeEachMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
invocation.proceed();
return;
}
runExtensionMethod(invocationContext, extensionContext, true);
invocation.skip();
}
@Override
public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
invocation.proceed();
return;
}
//as a convenience to the user we attach any exceptions from the server itself
//as suppressed exceptions from the failure
//this makes it easy to see why your request has failed in the test output itself
//instead of needed to look in the log output
List<Throwable> serverExceptions = new CopyOnWriteArrayList<>();
ExceptionReporting.setListener(serverExceptions::add);
try {
runExtensionMethod(invocationContext, extensionContext, true);
invocation.skip();
} catch (Throwable t) {
for (var serverException : serverExceptions) {
if (t == serverException) {
// do not add a suppressed exception to itself
continue;
}
t.addSuppressed(serverException);
}
throw t;
} finally {
ExceptionReporting.setListener(null);
}
}
@Override
public void interceptDynamicTest(Invocation<Void> invocation, ExtensionContext extensionContext) throws Throwable {
if (runningQuarkusApplication == null) {
invocation.proceed();
return;
}
var old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(runningQuarkusApplication.getClassLoader());
invocation.proceed();
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
@Override
public void interceptTestTemplateMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
invocation.proceed();
return;
}
runExtensionMethod(invocationContext, extensionContext);
invocation.skip();
}
@SuppressWarnings("unchecked")
@Override
public <T> T interceptTestFactoryMethod(Invocation<T> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
return invocation.proceed();
}
T result = (T) runExtensionMethod(invocationContext, extensionContext);
invocation.skip();
return result;
}
@Override
public void interceptAfterEachMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
invocation.proceed();
return;
}
runExtensionMethod(invocationContext, extensionContext, true);
invocation.skip();
}
@Override
public void interceptAfterAllMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
ExtensionContext extensionContext) throws Throwable {
if (isNativeOrIntegrationTest(extensionContext.getRequiredTestClass())) {
invocation.proceed();
return;
}
runExtensionMethod(invocationContext, extensionContext);
invocation.skip();
}
private Object runExtensionMethod(ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext)
throws Throwable {
return runExtensionMethod(invocationContext, extensionContext, false);
}
private Object runExtensionMethod(ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext,
boolean testMethodInvokersAllowed)
throws Throwable {
resetHangTimeout();
ClassLoader old = setCCL(runningQuarkusApplication.getClassLoader());
try {
Class<?> testClassFromTCCL = Class.forName(extensionContext.getRequiredTestClass().getName(), true,
Thread.currentThread().getContextClassLoader());
Map<Class<?>, Object> allTestsClasses = new HashMap<>();
// static loading
allTestsClasses.put(testClassFromTCCL, actualTestInstance);
// this is needed to support before*** and after*** methods that are part of class that encloses the test class
// (the test class is in this case a @Nested test)
outerInstances.forEach(i -> allTestsClasses.put(i.getClass(), i));
Method newMethod = null;
Object effectiveTestInstance = null;
for (Map.Entry<Class<?>, Object> testClass : allTestsClasses.entrySet()) {
newMethod = determineTCCLExtensionMethod(invocationContext.getExecutable(), testClass.getKey());
if (newMethod != null) {
effectiveTestInstance = testClass.getValue();
break;
}
}
if (newMethod == null) {
throw new RuntimeException("Could not find method " + invocationContext.getExecutable() + " on test class");
}
newMethod.setAccessible(true);
Object testMethodInvokerToUse = null;
if (testMethodInvokersAllowed) {
for (Object testMethodInvoker : testMethodInvokers) {
boolean supportsMethod = (boolean) testMethodInvoker.getClass()
.getMethod("supportsMethod", Class.class, Method.class).invoke(testMethodInvoker,
extensionContext.getRequiredTestClass(), invocationContext.getExecutable());
if (supportsMethod) {
testMethodInvokerToUse = testMethodInvoker;
break;
}
}
}
// the arguments were not loaded from TCCL so we need to deep clone them into the TCCL
// because the test method runs from a class loaded from the TCCL
//TODO: make this more pluggable
List<Object> originalArguments = invocationContext.getArguments();
List<Object> argumentsFromTccl = new ArrayList<>();
Parameter[] parameters = invocationContext.getExecutable().getParameters();
for (int i = 0; i < originalArguments.size(); i++) {
if (testMethodInvokerToUse != null) {
Class<?> argClass = parameters[i].getType();
argumentsFromTccl.add(testMethodInvokerToUse.getClass().getMethod("methodParamInstance", String.class)
.invoke(testMethodInvokerToUse, argClass.getName()));
} else {
Object arg = originalArguments.get(i);
argumentsFromTccl.add(deepClone.clone(arg));
}
}
if (testMethodInvokerToUse != null) {
return testMethodInvokerToUse.getClass()
.getMethod("invoke", Object.class, Method.class, List.class, String.class)
.invoke(testMethodInvokerToUse, effectiveTestInstance, newMethod, argumentsFromTccl,
extensionContext.getRequiredTestClass().getName());
} else {
return newMethod.invoke(effectiveTestInstance, argumentsFromTccl.toArray(new Object[0]));
}
} catch (InvocationTargetException e) {
throw e.getCause();
} catch (IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException(e);
} finally {
setCCL(old);
}
}
private Method determineTCCLExtensionMethod(Method originalMethod, Class<?> c)
throws ClassNotFoundException {
Class<?> declaringClass = resolveDeclaringClass(originalMethod, c);
if (declaringClass == null) {
return null;
}
try {
Class<?>[] originalParameterTypes = originalMethod.getParameterTypes();
List<Class<?>> parameterTypesFromTccl = new ArrayList<>(originalParameterTypes.length);
for (Class<?> type : originalParameterTypes) {
if (type.isPrimitive()) {
parameterTypesFromTccl.add(type);
} else {
parameterTypesFromTccl
.add(Class.forName(type.getName(), true,
Thread.currentThread().getContextClassLoader()));