-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathAllureLifecycle.java
More file actions
1435 lines (1324 loc) · 60.5 KB
/
Copy pathAllureLifecycle.java
File metadata and controls
1435 lines (1324 loc) · 60.5 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
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
/*
* 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;
import io.qameta.allure.internal.AllureExecutionContext;
import io.qameta.allure.internal.AllureThreadContext;
import io.qameta.allure.listener.ContainerLifecycleListener;
import io.qameta.allure.listener.FixtureLifecycleListener;
import io.qameta.allure.listener.LifecycleNotifier;
import io.qameta.allure.listener.StepLifecycleListener;
import io.qameta.allure.listener.TestLifecycleListener;
import io.qameta.allure.model.Attachment;
import io.qameta.allure.model.FixtureResult;
import io.qameta.allure.model.Parameter;
import io.qameta.allure.model.ScopeFixtureResult;
import io.qameta.allure.model.ScopeFixtureType;
import io.qameta.allure.model.ScopeResult;
import io.qameta.allure.model.Stage;
import io.qameta.allure.model.Status;
import io.qameta.allure.model.StepResult;
import io.qameta.allure.model.TestResult;
import io.qameta.allure.model.TestResultContainer;
import io.qameta.allure.model.WithAttachments;
import io.qameta.allure.model.WithMetadata;
import io.qameta.allure.model.WithSteps;
import io.qameta.allure.util.ExceptionUtils;
import io.qameta.allure.util.PropertiesUtils;
import io.qameta.allure.util.WellKnownFileExtensionsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static io.qameta.allure.AllureConstants.ATTACHMENT_FILE_SUFFIX;
import static io.qameta.allure.util.ResultsUtils.firstNonEmpty;
import static io.qameta.allure.util.ResultsUtils.getStatus;
import static io.qameta.allure.util.ResultsUtils.getStatusDetails;
import static io.qameta.allure.util.ResultsUtils.md5;
import static io.qameta.allure.util.ServiceLoaderUtils.load;
/**
* The Allure lifecycle: one class, three method groups. The addressing mode of every method is readable from its
* signature.
*
* <ul>
* <li><b>Manual core</b> — key-addressed methods. Every parent and owner is explicit; they touch no thread state
* and are safe from any thread. The exceptions are the start/stop transitions of tests and fixtures: starts bind
* the calling thread (the thread that calls start is by definition the executing thread), and stops unbind or
* restore only when the calling thread's root is the stopped key.</li>
* <li><b>Ambient group</b> — keyless overloads that resolve their target from the calling thread's binding.</li>
* <li><b>Thread group</b> — explicit binding control: {@link #setCurrent(AllureExternalKey)},
* {@link #clearCurrent()}, {@link #bind(AllureExternalKey)}, {@link #bindDetached(AllureExternalKey)}, and the
* current-key accessors.</li>
* </ul>
*
* <p>Integration adapters model suite-level grouping through flat scopes using
* {@link #registerScope(AllureExternalKey)}, {@link #addTestToScope(AllureExternalKey, AllureExternalKey)}, and
* {@link #writeScope(AllureExternalKey)}.</p>
*/
@SuppressWarnings(
{
"PMD.AvoidSynchronizedStatement",
"PMD.GodClass", "PMD.TooManyMethods", "ClassFanOutComplexity"}
)
public class AllureLifecycle {
private static final Logger LOGGER = LoggerFactory.getLogger(AllureLifecycle.class);
private static final String EXTERNAL_KEY = "external key";
private static final String KEY_NOT_FOUND = "Could not {}: item with key {} not found";
private static final String WRONG_ENTITY = "Could not {}: item with key {} is not the expected type";
private static final String KEY_ALREADY_EXISTS = "Could not {}: item with key {} already exists";
private static final String NO_CONTEXT_FOR_ATTACHMENT = "Could not add attachment: no test or fixture running";
private static final String ADD_TEST_TO_SCOPE = "add test to scope";
private static final String SCHEDULE_TEST = "schedule test";
private static final String START_FIXTURE = "start fixture";
private static final String START_STEP = "start step";
private final AllureResultsWriter writer;
private final AllureThreadContext threadContext;
private final LifecycleNotifier notifier;
private final Map<AllureExternalKey, Object> items = new ConcurrentHashMap<>();
/**
* Creates a new lifecycle with default results writer. Shortcut
* for {@link #AllureLifecycle(AllureResultsWriter)}
*/
public AllureLifecycle() {
this(getDefaultWriter());
}
/**
* Creates a new lifecycle instance with specified {@link AllureResultsWriter}.
*
* @param writer the results writer.
*/
public AllureLifecycle(final AllureResultsWriter writer) {
this(writer, getDefaultNotifier());
}
/**
* Creates a new lifecycle instance with specified {@link AllureResultsWriter}
* and {@link LifecycleNotifier}.
*
* @param writer the results writer.
*/
AllureLifecycle(final AllureResultsWriter writer, final LifecycleNotifier lifecycleNotifier) {
this.notifier = lifecycleNotifier;
this.writer = writer;
this.threadContext = new AllureThreadContext();
}
// ── Scopes ───────────────────────────────────────────────────────────────────────────────
/**
* Registers scope.
*
* @param key the external scope key
*/
public void registerScope(final AllureExternalKey key) {
Objects.requireNonNull(key, EXTERNAL_KEY);
final ScopeResult scope = new ScopeResult()
.setUuid(UUID.randomUUID().toString());
if (Objects.nonNull(items.putIfAbsent(key, new ScopeItem(scope)))) {
LOGGER.warn(KEY_ALREADY_EXISTS, "register scope", key);
}
}
/**
* Adds test to scope. The test is referenced by its runtime key, so it must still be live in storage; the
* scope's metadata is merged into it when it stops.
*
* @param scopeKey the external scope key
* @param testKey the external test key
*/
public void addTestToScope(final AllureExternalKey scopeKey, final AllureExternalKey testKey) {
final ScopeItem scope = getItem(scopeKey, ScopeItem.class, ADD_TEST_TO_SCOPE);
final TestItem test = getItem(testKey, TestItem.class, ADD_TEST_TO_SCOPE);
if (Objects.isNull(scope) || Objects.isNull(test)) {
return;
}
test.scopes().add(scopeKey);
addTest(scope, test.result().getUuid());
}
/**
* Adds test to scope, referencing the test by its model uuid instead of a runtime key. Use for tests that are
* already written and released from storage — the normal case for a scope that is written after its children,
* such as an after-method scope or a suite scope closing at run end.
*
* @param scopeKey the external scope key
* @param testUuid the model uuid of the test
*/
public void addTestToScope(final AllureExternalKey scopeKey, final String testUuid) {
final ScopeItem scope = getItem(scopeKey, ScopeItem.class, ADD_TEST_TO_SCOPE);
if (Objects.isNull(scope)) {
return;
}
addTest(scope, testUuid);
}
/**
* Writes scope.
*
* @param key the external scope key
*/
public void writeScope(final AllureExternalKey key) {
final ScopeItem scope = getItem(key, ScopeItem.class, "write scope");
if (Objects.isNull(scope)) {
return;
}
final TestResultContainer container;
synchronized (scope) {
container = toScopeContainer(scope.result());
}
// the scope may be written before its linked tests stop (for example TestNG per-method scopes are written
// at test start) — drain its metadata into the still-live tests now, claiming the link so the merge at
// stopTest cannot apply it twice
items.values().forEach(item -> {
if (item instanceof TestItem && ((TestItem) item).scopes().remove(key)) {
synchronized (scope) {
mergeScopeMetadata(scope.result(), ((TestItem) item).result());
}
}
});
notifier.beforeContainerWrite(container);
waitForFutures(scope.futures());
writer.write(container);
sweepOwnedSteps(key);
items.remove(key);
notifier.afterContainerWrite(container);
}
// ── Tests ────────────────────────────────────────────────────────────────────────────────
/**
* Schedules test with given key.
*
* @param key the external test key
* @param result the test to schedule
*/
public void scheduleTest(final AllureExternalKey key, final TestResult result) {
Objects.requireNonNull(key, EXTERNAL_KEY);
if (items.containsKey(key)) {
LOGGER.warn(KEY_ALREADY_EXISTS, SCHEDULE_TEST, key);
return;
}
if (firstNonEmpty(result.getUuid()).isEmpty()) {
result.setUuid(UUID.randomUUID().toString());
}
notifier.beforeTestSchedule(result);
result.setStage(Stage.SCHEDULED);
if (Objects.nonNull(items.putIfAbsent(key, new TestItem(result)))) {
LOGGER.warn(KEY_ALREADY_EXISTS, SCHEDULE_TEST, key);
return;
}
notifier.afterTestSchedule(result);
}
/**
* Schedules test with given scopes.
*
* @param scopeKeys the external scope keys
* @param key the external test key
* @param result the test to schedule
*/
public void scheduleTest(final Collection<AllureExternalKey> scopeKeys,
final AllureExternalKey key,
final TestResult result) {
scheduleTest(key, result);
scopeKeys.forEach(scopeKey -> addTestToScope(scopeKey, key));
}
/**
* Starts test with given key and binds it as the calling thread's root. The test must be scheduled.
*
* @param key the external test key
*/
public void startTest(final AllureExternalKey key) {
final TestItem item = getItem(key, TestItem.class, "start test");
if (Objects.isNull(item)) {
return;
}
final TestResult testResult = item.result();
if (!Stage.SCHEDULED.equals(testResult.getStage())) {
LOGGER.warn("Could not start test: test with key {} is not scheduled", key);
return;
}
threadContext.clear();
notifier.beforeTestStart(testResult);
testResult
.setStage(Stage.RUNNING)
.setStart(System.currentTimeMillis());
threadContext.start(key);
notifier.afterTestStart(testResult);
}
/**
* Updates test by given key.
*
* @param key the external test key
* @param update the update function
*/
public void updateTest(final AllureExternalKey key, final Consumer<TestResult> update) {
final TestItem item = getItem(key, TestItem.class, "update test");
if (Objects.isNull(item)) {
return;
}
notifier.beforeTestUpdate(item.result());
update.accept(item.result());
notifier.afterTestUpdate(item.result());
}
/**
* Updates current running test.
*
* @param update the update function.
*/
public void updateTest(final Consumer<TestResult> update) {
final Optional<AllureExternalKey> root = threadContext.getRoot();
if (root.isEmpty()) {
LOGGER.warn("Could not update test: no test running");
return;
}
updateTest(root.get(), update);
}
/**
* Stops test by given key. The test must be running; scope metadata is merged into the test here. If the test has
* a test case id but no history id, a compatibility history id is generated from the test case id and the final
* parameters. A history id supplied by a {@link TestLifecycleListener#beforeTestStop(TestResult)} listener is
* preserved. Unbinds the calling thread only if the test is the calling thread's root.
*
* @param key the external test key
*/
public void stopTest(final AllureExternalKey key) {
final TestItem item = getItem(key, TestItem.class, "stop test");
if (Objects.isNull(item)) {
return;
}
final TestResult testResult = item.result();
if (!Stage.RUNNING.equals(testResult.getStage())) {
LOGGER.warn("Could not stop test: test with key {} is not running", key);
return;
}
if (isCurrentRoot(key)) {
closeOpenStages();
}
notifier.beforeTestStop(testResult);
testResult
.setStage(Stage.FINISHED)
.setStop(System.currentTimeMillis());
if (Objects.isNull(testResult.getParameters())) {
testResult.setParameters(new ArrayList<>());
}
applyScopeMetadata(item);
if (Objects.isNull(testResult.getHistoryId()) && Objects.nonNull(testResult.getTestCaseId())) {
testResult.setHistoryId(calculateHistoryId(testResult.getTestCaseId(), testResult.getParameters()));
}
if (isCurrentRoot(key)) {
threadContext.clear();
}
notifier.afterTestStop(testResult);
}
private static String calculateHistoryId(final String testCaseId, final List<Parameter> parameters) {
final StringBuilder source = new StringBuilder(testCaseId);
final Stream<Parameter> parameterStream = Objects.isNull(parameters) ? Stream.empty() : parameters.stream();
parameterStream
.filter(Objects::nonNull)
.filter(parameter -> !Boolean.TRUE.equals(parameter.getExcluded()))
.sorted(
Comparator.comparing((Parameter parameter) -> Objects.toString(parameter.getName(), ""))
.thenComparing(parameter -> Objects.toString(parameter.getValue(), ""))
)
.forEachOrdered(
parameter -> source
.append(Objects.toString(parameter.getName(), ""))
.append(Objects.toString(parameter.getValue(), ""))
);
return md5(source.toString());
}
/**
* Writes test by given key. Waits for the test's pending async attachments before serializing, so the written
* result file is a completion marker: everything it references exists.
*
* @param key the external test key
*/
public void writeTest(final AllureExternalKey key) {
final TestItem item = getItem(key, TestItem.class, "write test");
if (Objects.isNull(item)) {
return;
}
notifier.beforeTestWrite(item.result());
waitForFutures(item.futures());
writer.write(item.result());
sweepOwnedSteps(key);
items.remove(key);
notifier.afterTestWrite(item.result());
}
// ── Fixtures ─────────────────────────────────────────────────────────────────────────────
/**
* Starts a new before fixture with given scope and binds it as the calling thread's root, saving the previous
* binding for {@link #stopFixture(AllureExternalKey)} to restore.
*
* @param scopeKey the external scope key
* @param fixtureKey the external fixture key
* @param result the fixture
*/
public void startBeforeFixture(final AllureExternalKey scopeKey, final AllureExternalKey fixtureKey,
final FixtureResult result) {
startFixture(scopeKey, fixtureKey, result, ScopeFixtureType.BEFORE);
}
/**
* Starts a new after fixture with given scope and binds it as the calling thread's root, saving the previous
* binding for {@link #stopFixture(AllureExternalKey)} to restore.
*
* @param scopeKey the external scope key
* @param fixtureKey the external fixture key
* @param result the fixture
*/
public void startAfterFixture(final AllureExternalKey scopeKey, final AllureExternalKey fixtureKey,
final FixtureResult result) {
startFixture(scopeKey, fixtureKey, result, ScopeFixtureType.AFTER);
}
private void startFixture(final AllureExternalKey scopeKey, final AllureExternalKey key,
final FixtureResult result, final ScopeFixtureType type) {
Objects.requireNonNull(key, EXTERNAL_KEY);
final ScopeItem scope = getItem(scopeKey, ScopeItem.class, START_FIXTURE);
if (Objects.isNull(scope)) {
return;
}
if (items.containsKey(key)) {
LOGGER.warn(KEY_ALREADY_EXISTS, START_FIXTURE, key);
return;
}
synchronized (scope) {
scope.result().getFixtures().add(
new ScopeFixtureResult()
.setUuid(UUID.randomUUID().toString())
.setValue(result)
.setType(type)
.setScopeUuid(scope.result().getUuid())
);
}
notifier.beforeFixtureStart(result);
final FixtureItem item = new FixtureItem(result, scopeKey, type, threadContext.copy());
items.put(key, item);
result.setStage(Stage.RUNNING);
result.setStart(System.currentTimeMillis());
threadContext.clear();
threadContext.start(key);
notifier.afterFixtureStart(result);
}
/**
* Updates fixture by given key.
*
* @param key the external fixture key
* @param update the update function
*/
public void updateFixture(final AllureExternalKey key, final Consumer<FixtureResult> update) {
final FixtureItem item = getItem(key, FixtureItem.class, "update fixture");
if (Objects.isNull(item)) {
return;
}
notifier.beforeFixtureUpdate(item.result());
update.accept(item.result());
notifier.afterFixtureUpdate(item.result());
}
/**
* Updates current running fixture.
*
* @param update the update function.
*/
public void updateFixture(final Consumer<FixtureResult> update) {
final Optional<AllureExternalKey> root = threadContext.getRoot();
if (root.isEmpty()) {
LOGGER.warn("Could not update fixture: no fixture running");
return;
}
updateFixture(root.get(), update);
}
/**
* Stops fixture by given key. Restores the binding saved at fixture start only if the fixture is the calling
* thread's root.
*
* @param key the external fixture key
*/
public void stopFixture(final AllureExternalKey key) {
final FixtureItem item = getItem(key, FixtureItem.class, "stop fixture");
if (Objects.isNull(item)) {
return;
}
final FixtureResult fixture = item.result();
if (isCurrentRoot(key)) {
closeOpenStages();
}
notifier.beforeFixtureStop(fixture);
fixture.setStage(Stage.FINISHED);
fixture.setStop(System.currentTimeMillis());
if (isCurrentRoot(key)) {
threadContext.set(item.savedContext());
}
items.remove(key);
notifier.afterFixtureStop(fixture);
}
// ── Steps ────────────────────────────────────────────────────────────────────────────────
/**
* Starts a new step as a child of the current executable and makes it current on the calling thread. Takes no
* effect if no executable is running.
*
* @param result the step
*/
public void startStep(final StepResult result) {
startStep(AllureExternalKey.random(AllureLifecycle.class), result);
}
/**
* Starts a new step as a child of the current executable and makes it current on the calling thread, using the
* given key as the step's identity. The key lets callers address this step later (for example a
* {@code StepContext} that must target this step even while a nested step is current). Takes no effect if no
* executable is running.
*
* @param key the external step key
* @param result the step
*/
public void startStep(final AllureExternalKey key, final StepResult result) {
final Optional<AllureExternalKey> current = threadContext.getCurrentExecutable();
if (current.isEmpty()) {
LOGGER.warn("Could not start step: no test or fixture running");
return;
}
startStep(current.get(), key, result, true);
}
/**
* Starts a new step as a child of the specified parent. Pure manual linkage: the step is attached under the
* parent and no thread state is touched, so this is safe to call from any thread. Stop it with
* {@link #stopStep(AllureExternalKey)}.
*
* @param parentKey the external parent key
* @param key the external step key
* @param result the step
*/
public void startStep(final AllureExternalKey parentKey, final AllureExternalKey key, final StepResult result) {
startStep(parentKey, key, result, false);
}
private void startStep(final AllureExternalKey parentKey, final AllureExternalKey key,
final StepResult result, final boolean bind) {
startStep(parentKey, key, result, bind, false);
}
private void startStep(final AllureExternalKey parentKey, final AllureExternalKey key,
final StepResult result, final boolean bind, final boolean stage) {
Objects.requireNonNull(key, EXTERNAL_KEY);
Objects.requireNonNull(parentKey, EXTERNAL_KEY);
final Object parent = items.get(parentKey);
if (Objects.isNull(parent)) {
LOGGER.warn(KEY_NOT_FOUND, START_STEP, parentKey);
return;
}
final Object parentModel = modelOf(parent);
if (!(parentModel instanceof WithSteps)) {
LOGGER.warn(WRONG_ENTITY, START_STEP, parentKey);
return;
}
if (items.containsKey(key)) {
LOGGER.warn(KEY_ALREADY_EXISTS, START_STEP, key);
return;
}
notifier.beforeStepStart(result);
result.setStage(Stage.RUNNING);
result.setStart(System.currentTimeMillis());
if (bind) {
threadContext.start(key);
}
final AllureExecutionContext snapshot = bind
? threadContext.copy()
: deriveSnapshot(parentKey, parent, key);
items.put(key, new StepItem(result, writeOwnerOf(parentKey, parent), snapshot, stage));
synchronized (parent) {
((WithSteps) parentModel).getSteps().add(result);
}
notifier.afterStepStart(result);
}
/**
* Starts a stage — a lightweight phase marker rendered as a regular step. A stage has no explicit stop: it stays
* open, collecting the steps and attachments that follow, until the next stage starts at the same level or the
* enclosing step, test, or fixture ends. A stage started inside a step becomes a child of that step. A stage
* with no status when it closes is marked passed.
*
* <p>Stages are an ambient-only concept: their lifetime is defined by the calling thread's binding, so there is
* no key-addressed form. Takes no effect if no executable is running.</p>
*
* @param result the stage step, carrying its name
*/
public void startStage(final StepResult result) {
if (threadContext.getCurrentExecutable().isEmpty()) {
LOGGER.warn("Could not start stage: no test or fixture running");
return;
}
closeOpenStages();
final Optional<AllureExternalKey> parent = threadContext.getCurrentExecutable();
if (parent.isEmpty()) {
return;
}
startStep(parent.get(), AllureExternalKey.random(AllureLifecycle.class), result, true, true);
}
/**
* Closes consecutive open stages on top of the calling thread's stack. A stage with no status is marked passed.
*/
private void closeOpenStages() {
closeOpenStagesAbove(null);
}
/**
* Closes consecutive open stages bound above the given step on the calling thread's stack, or all consecutive
* top stages when the step is {@code null}. A stage with no status is marked passed.
*/
private void closeOpenStagesAbove(final AllureExternalKey key) {
while (true) {
final Optional<AllureExternalKey> current = threadContext.getCurrentStep();
if (current.isEmpty() || current.get().equals(key)) {
return;
}
final Object item = items.get(current.get());
if (!(item instanceof StepItem) || !((StepItem) item).stage()) {
return;
}
if (Objects.isNull(((StepItem) item).result().getStatus())) {
((StepItem) item).result().setStatus(Status.PASSED);
}
stopStep(current.get(), true);
}
}
/**
* Updates step by specified key.
*
* @param key the external step key
* @param update the update function
*/
public void updateStep(final AllureExternalKey key, final Consumer<StepResult> update) {
final StepItem item = getItem(key, StepItem.class, "update step");
if (Objects.isNull(item)) {
return;
}
notifier.beforeStepUpdate(item.result());
update.accept(item.result());
notifier.afterStepUpdate(item.result());
}
/**
* Updates the current running step. A stage cannot be updated: stages are addressed by nobody once started, so
* when the current step is a stage this warns and does nothing — a caller finishing its own step must address
* it by key.
*
* @param update the update function.
*/
public void updateStep(final Consumer<StepResult> update) {
final Optional<AllureExternalKey> current = threadContext.getCurrentStep();
if (current.isEmpty()) {
LOGGER.warn("Could not update step: no step running");
return;
}
final Object item = items.get(current.get());
if (item instanceof StepItem && ((StepItem) item).stage()) {
LOGGER.warn("Could not update step: the current step is a stage");
return;
}
updateStep(current.get(), update);
}
/**
* Stops step by given key. Pure manual form with one thread-affine convenience: when the stopped step is bound
* on the calling thread with open stages above it, those stages are closed first.
*
* @param key the external step key
*/
public void stopStep(final AllureExternalKey key) {
if (threadContext.getLocalKeys().contains(key)) {
closeOpenStagesAbove(key);
}
stopStep(key, false);
}
/**
* Stops the current running step and pops it from the calling thread. Open stages above it are closed first.
*/
public void stopStep() {
closeOpenStages();
final Optional<AllureExternalKey> current = threadContext.getCurrentStep();
if (current.isEmpty()) {
LOGGER.warn("Could not stop step: no step running");
return;
}
stopStep(current.get(), true);
}
private void stopStep(final AllureExternalKey key, final boolean unbind) {
final StepItem item = getItem(key, StepItem.class, "stop step");
if (Objects.isNull(item)) {
return;
}
final StepResult step = item.result();
notifier.beforeStepStop(step);
step.setStage(Stage.FINISHED);
step.setStop(System.currentTimeMillis());
items.remove(key);
if (unbind) {
threadContext.stop();
}
notifier.afterStepStop(step);
}
/**
* Logs an instant step — started and finished in one call — under the current executable. The step is bound as
* current for the duration of its listener callbacks, so listeners observe it exactly like a regular step.
* Takes no effect if no executable is running.
*
* @param result the step, carrying its name and status
*/
public void logStep(final StepResult result) {
final Optional<AllureExternalKey> current = threadContext.getCurrentExecutable();
if (current.isEmpty()) {
LOGGER.warn("Could not log step: no test or fixture running");
return;
}
final AllureExternalKey key = AllureExternalKey.random(AllureLifecycle.class);
startStep(current.get(), key, result, true);
if (items.containsKey(key)) {
stopStep(key, true);
}
}
/**
* Logs an instant step — started and finished in one call — under the specified parent. Pure manual linkage:
* no thread state is touched, so this is safe to call from any thread.
*
* @param parentKey the external parent key
* @param result the step, carrying its name and status
*/
public void logStep(final AllureExternalKey parentKey, final StepResult result) {
final AllureExternalKey key = AllureExternalKey.random(AllureLifecycle.class);
startStep(parentKey, key, result, false);
if (items.containsKey(key)) {
stopStep(key, false);
}
}
// ── Attachments ──────────────────────────────────────────────────────────────────────────
/**
* Adds attachment to a running test, fixture, or step by key.
*
* @param key the external executable key
* @param name the name of attachment
* @param type the content type of attachment
* @param stream attachment content
* @param options the attachment options
*/
public void addAttachment(final AllureExternalKey key, final String name, final String type,
final InputStream stream, final AttachmentOptions options) {
addAttachmentLink(key, name, type, options)
.ifPresent(source -> writer.write(source, stream));
}
/**
* Adds attachment to the current test, fixture, or step if one is running.
*
* @param name the name of attachment
* @param type the content type of attachment
* @param stream attachment content
* @param options the attachment options
*/
public void addAttachment(final String name, final String type,
final InputStream stream, final AttachmentOptions options) {
final Optional<AllureExternalKey> current = threadContext.getCurrentExecutable();
if (current.isEmpty()) {
LOGGER.warn(NO_CONTEXT_FOR_ATTACHMENT);
return;
}
addAttachment(current.get(), name, type, stream, options);
}
/**
* Adds an async attachment to a running test, fixture, or step by key. The attachment content is awaited before
* the owning test or scope is written.
*
* @param key the external executable key
* @param name the name of attachment
* @param type the content type of attachment
* @param body the future stream that contains attachment content
* @param options the attachment options
* @return future completed when attachment content is written
*/
public CompletableFuture<Void> addAttachmentAsync(final AllureExternalKey key, final String name,
final String type,
final CompletionStage<? extends InputStream> body,
final AttachmentOptions options) {
return addAttachmentAsync(key, name, type, body, options, null);
}
/**
* Adds an async attachment to the current test, fixture, or step if one is running. The attachment content is
* awaited before the owning test or scope is written.
*
* @param name the name of attachment
* @param type the content type of attachment
* @param body the future stream that contains attachment content
* @param options the attachment options
* @return future completed when attachment content is written
*/
public CompletableFuture<Void> addAttachmentAsync(final String name, final String type,
final CompletionStage<? extends InputStream> body,
final AttachmentOptions options) {
final Optional<AllureExternalKey> current = threadContext.getCurrentExecutable();
if (current.isEmpty()) {
LOGGER.warn(NO_CONTEXT_FOR_ATTACHMENT);
return CompletableFuture.completedFuture(null);
}
return addAttachmentAsync(current.get(), name, type, body, options, null);
}
private CompletableFuture<Void> addAttachmentAsync(final AllureExternalKey key, final String name,
final String type,
final CompletionStage<? extends InputStream> body,
final AttachmentOptions options,
final BiConsumer<Void, Throwable> onComplete) {
final Optional<String> source = addAttachmentLink(key, name, type, options);
if (source.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
final String attachmentSource = source.get();
CompletableFuture<Void> future = body
.thenAccept(stream -> writer.write(attachmentSource, stream))
.toCompletableFuture();
if (Objects.nonNull(onComplete)) {
future = future.whenComplete(onComplete);
}
final Optional<Set<CompletableFuture<?>>> futures = futuresOf(writeOwnerOf(key, items.get(key)));
if (futures.isEmpty()) {
LOGGER.warn("Could not track async attachment: no write owner found for key {}", key);
} else {
registerFuture(futures.get(), future);
}
return future;
}
/**
* Adds an attachment wrapped in its own instant step under the current executable — the default representation
* for user-facing attachments. Safe to call from listener callbacks: the wrapper step emits no further events.
* Takes no effect if no executable is running.
*
* @param name the name of attachment
* @param type the content type of attachment
* @param content attachment content
* @param options the attachment options
*/
public void addAttachmentStep(final String name, final String type,
final InputStream content, final AttachmentOptions options) {
final Optional<AllureExternalKey> current = threadContext.getCurrentExecutable();
if (current.isEmpty()) {
LOGGER.warn(NO_CONTEXT_FOR_ATTACHMENT);
return;
}
final AllureExternalKey key = AllureExternalKey.random(AllureLifecycle.class);
startStep(current.get(), key, new StepResult().setName(attachmentStepName(name)), true);
if (!items.containsKey(key)) {
return;
}
try {
addAttachment(key, name, type, content, options);
updateStep(key, step -> step.setStatus(Status.PASSED));
} catch (Throwable throwable) {
updateStep(
key, step -> step
.setStatus(getStatus(throwable).orElse(Status.BROKEN))
.setStatusDetails(getStatusDetails(throwable).orElse(null))
);
throw ExceptionUtils.sneakyThrow(throwable);
} finally {
stopStep(key, true);
}
}
/**
* Adds an attachment wrapped in its own instant step under the specified parent — the default representation
* for user-facing attachments. Pure manual linkage: no thread state is touched.
*
* @param parentKey the external parent key
* @param name the name of attachment
* @param type the content type of attachment
* @param content attachment content
* @param options the attachment options
*/
public void addAttachmentStep(final AllureExternalKey parentKey, final String name, final String type,
final InputStream content, final AttachmentOptions options) {
final AllureExternalKey key = AllureExternalKey.random(AllureLifecycle.class);
startStep(parentKey, key, new StepResult().setName(attachmentStepName(name)), false);
if (!items.containsKey(key)) {
return;
}
try {
addAttachment(key, name, type, content, options);
updateStep(key, step -> step.setStatus(Status.PASSED));
} catch (Throwable throwable) {
updateStep(
key, step -> step
.setStatus(getStatus(throwable).orElse(Status.BROKEN))
.setStatusDetails(getStatusDetails(throwable).orElse(null))
);
throw ExceptionUtils.sneakyThrow(throwable);
} finally {
stopStep(key, false);
}
}
/**
* Adds an async attachment wrapped in its own instant step under the current executable. The attachment content
* is awaited before the owning test or scope is written; a failed body marks the step broken before the owner
* is serialized. Takes no effect if no executable is running.
*
* @param name the name of attachment
* @param type the content type of attachment
* @param body the future stream that contains attachment content
* @param options the attachment options
* @return future completed when attachment content is written
*/
public CompletableFuture<Void> addAttachmentStepAsync(final String name, final String type,
final CompletionStage<? extends InputStream> body,
final AttachmentOptions options) {
final Optional<AllureExternalKey> current = threadContext.getCurrentExecutable();
if (current.isEmpty()) {
LOGGER.warn(NO_CONTEXT_FOR_ATTACHMENT);
return CompletableFuture.completedFuture(null);
}
final AllureExternalKey key = AllureExternalKey.random(AllureLifecycle.class);
final StepResult step = new StepResult()
.setName(attachmentStepName(name))
.setStatus(Status.PASSED);
startStep(current.get(), key, step, true);
if (!items.containsKey(key)) {
return CompletableFuture.completedFuture(null);
}
try {
// the status update runs inside the tracked future, so a failed async attachment is
// guaranteed to mark the step before the owning result is written
return addAttachmentAsync(key, name, type, body, options, (result, throwable) -> {
if (Objects.nonNull(throwable)) {
step.setStatus(getStatus(throwable).orElse(Status.BROKEN))
.setStatusDetails(getStatusDetails(throwable).orElse(null));
}
});
} finally {
stopStep(key, true);
}
}
/**
* Adds an async attachment wrapped in its own instant step under the specified parent. Pure manual linkage: no
* thread state is touched. The attachment content is awaited before the owning test or scope is written; a
* failed body marks the step broken before the owner is serialized.
*
* @param parentKey the external parent key
* @param name the name of attachment
* @param type the content type of attachment
* @param body the future stream that contains attachment content
* @param options the attachment options
* @return future completed when attachment content is written
*/
public CompletableFuture<Void> addAttachmentStepAsync(final AllureExternalKey parentKey, final String name,
final String type,
final CompletionStage<? extends InputStream> body,
final AttachmentOptions options) {
final AllureExternalKey key = AllureExternalKey.random(AllureLifecycle.class);
final StepResult step = new StepResult()
.setName(attachmentStepName(name))
.setStatus(Status.PASSED);
startStep(parentKey, key, step, false);
if (!items.containsKey(key)) {
return CompletableFuture.completedFuture(null);