allure-rust-commons 1.2.0

Core Allure runtime model, lifecycle, and result writer for Rust integrations.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
//! Framework-neutral high-level Allure runtime facade.

use std::{
    any::Any,
    cell::RefCell,
    fmt, fs,
    future::Future,
    panic::{self, AssertUnwindSafe},
    path::Path,
    pin::Pin,
    process::{ExitCode, Termination},
    sync::{
        atomic::{AtomicU64, Ordering},
        OnceLock,
    },
    task::{Context, Poll},
    time::{SystemTime, UNIX_EPOCH},
};

use crate::{
    config::{
        apply_common_runtime_labels, apply_config_labels, apply_synthetic_suite_labels,
        title_path as config_title_path,
    },
    current_owner, error_classifier,
    http_exchange::{HttpExchange, HTTP_EXCHANGE_ATTACHMENT_NAME},
    lifecycle::{AllureLifecycle, AllureRuntime, StartTestCaseParams},
    model::{GlobalAttachment, GlobalError, Globals, Label, ParameterMode, Status, StatusDetails},
    writer::{FileSystemResultsWriter, PLAYWRIGHT_TRACE_ATTACHMENT_MIME},
};

static ALLURE: OnceLock<AllureFacade> = OnceLock::new();
static FACADE_ID_COUNTER: AtomicU64 = AtomicU64::new(1);

thread_local! {
    static CURRENT_ALLURE: RefCell<Option<AllureFacade>> = const { RefCell::new(None) };
    static LAST_ASSERTION_FAILURE: RefCell<Option<StatusDetails>> = const { RefCell::new(None) };
}

/// Returns the process-wide default facade.
pub fn allure() -> &'static AllureFacade {
    ALLURE.get_or_init(AllureFacade::default)
}

/// Guard that restores the previous thread-bound facade when dropped.
pub struct CurrentAllureGuard {
    previous: Option<AllureFacade>,
}

/// Binds an Allure facade to the current thread.
pub fn push_current_allure(allure: &AllureFacade) -> CurrentAllureGuard {
    let previous = CURRENT_ALLURE.with(|current| current.replace(Some(allure.clone())));
    CurrentAllureGuard { previous }
}

/// Returns the facade currently bound to this thread.
pub fn current_allure() -> Option<AllureFacade> {
    CURRENT_ALLURE.with(|current| current.borrow().clone())
}

/// Clears pending assertion failure details captured by assertion logging.
pub fn clear_last_assertion_failure() {
    LAST_ASSERTION_FAILURE.with(|failure| {
        failure.replace(None);
    });
}

/// Returns status details for a failure message, reusing captured assertion details when present.
pub fn status_details_for_message(message: String) -> StatusDetails {
    LAST_ASSERTION_FAILURE
        .with(|failure| failure.take())
        .filter(|details| details.message.as_deref() == Some(message.as_str()))
        .unwrap_or(StatusDetails {
            message: Some(message),
            trace: None,
            actual: None,
            expected: None,
        })
}

/// Records a passed assertion as a log step on the current facade.
pub fn record_assertion_pass(name: impl Into<String>) {
    if let Some(allure) = current_allure() {
        allure.log_step(name);
    }
}

#[track_caller]
/// Records a failed assertion and panics with the original assertion message.
pub fn fail_assertion(
    name: impl Into<String>,
    message: String,
    actual: Option<String>,
    expected: Option<String>,
) -> ! {
    let details = StatusDetails {
        message: Some(message.clone()),
        trace: None,
        actual,
        expected,
    };
    LAST_ASSERTION_FAILURE.with(|failure| {
        failure.replace(Some(details.clone()));
    });
    if let Some(allure) = current_allure() {
        let guard = allure.start_step_scope(name);
        let guard = guard.with_status(Status::Failed, Some(details));
        drop(guard);
    }
    panic!("{message}");
}

fn active_allure() -> AllureFacade {
    current_allure().unwrap_or_default()
}

fn facade_id() -> String {
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .unwrap_or_default();
    let counter = FACADE_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("{millis}-{counter}")
}

fn write_globals(globals: Globals) -> std::io::Result<()> {
    FileSystemResultsWriter::from_env()?
        .write_globals_typed(&globals)
        .map(|_| ())
}

/// Options used by the macro-free `test` runtime wrappers.
#[derive(Clone, Debug)]
pub struct TestOptions {
    params: StartTestCaseParams,
    manifest_dir: Option<String>,
    module_path: Option<String>,
    title_path: Option<Vec<String>>,
    framework: Option<String>,
    synthetic_suite_labels: bool,
    panic_status: Option<Status>,
}

impl TestOptions {
    /// Creates options for a test with the given display name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            params: StartTestCaseParams::new(name),
            manifest_dir: None,
            module_path: None,
            title_path: None,
            framework: Some("cargo-test".to_string()),
            synthetic_suite_labels: true,
            panic_status: None,
        }
    }

    /// Infers options from the current cargo-test thread name.
    pub fn inferred() -> Self {
        let full_name = current_test_full_name();
        let name = test_name_from_full_name(&full_name);
        Self::new(name).with_full_name(full_name)
    }

    /// Creates options from low-level lifecycle start parameters.
    pub fn from_params(params: StartTestCaseParams) -> Self {
        Self {
            params,
            manifest_dir: None,
            module_path: None,
            title_path: None,
            framework: Some("cargo-test".to_string()),
            synthetic_suite_labels: true,
            panic_status: None,
        }
    }

    /// Sets the test full name.
    pub fn with_full_name(mut self, full_name: impl Into<String>) -> Self {
        self.params.full_name = Some(full_name.into());
        self
    }

    /// Sets an explicit history identifier.
    pub fn with_history_id(mut self, history_id: impl Into<String>) -> Self {
        self.params.history_id = Some(history_id.into());
        self
    }

    /// Sets an explicit test case identifier.
    pub fn with_test_case_id(mut self, test_case_id: impl Into<String>) -> Self {
        self.params.test_case_id = Some(test_case_id.into());
        self
    }

    /// Sets the markdown description.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.params.description = Some(description.into());
        self
    }

    /// Sets the HTML description.
    pub fn with_description_html(mut self, description: impl Into<String>) -> Self {
        self.params.description_html = Some(description.into());
        self
    }

    /// Adds an initial label.
    pub fn with_label(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.params.labels.push(Label {
            name: name.into(),
            value: value.into(),
        });
        self
    }

    /// Adds an initial Allure ID label.
    pub fn with_allure_id(self, value: impl Into<String>) -> Self {
        self.with_label("ALLURE_ID", value)
    }

    /// Sets the Cargo manifest directory used for package metadata lookup.
    pub fn with_manifest_dir(mut self, manifest_dir: impl Into<String>) -> Self {
        self.manifest_dir = Some(manifest_dir.into());
        self
    }

    /// Sets the Rust module path used for package metadata lookup.
    pub fn with_module_path(mut self, module_path: impl Into<String>) -> Self {
        self.module_path = Some(module_path.into());
        self
    }

    /// Sets the title path.
    pub fn with_title_path<I, V>(mut self, title_path: I) -> Self
    where
        I: IntoIterator<Item = V>,
        V: Into<String>,
    {
        self.title_path = Some(title_path.into_iter().map(Into::into).collect());
        self
    }

    /// Sets source-location metadata used for title path and package metadata labels.
    pub fn with_source(
        mut self,
        file: impl AsRef<str>,
        manifest_dir: impl Into<String>,
        module_path: impl Into<String>,
    ) -> Self {
        let manifest_dir = manifest_dir.into();
        self.title_path = Some(config_title_path(file.as_ref(), &manifest_dir));
        self.manifest_dir = Some(manifest_dir);
        self.module_path = Some(module_path.into());
        self
    }

    /// Sets the framework label value.
    pub fn with_framework(mut self, framework: impl Into<String>) -> Self {
        self.framework = Some(framework.into());
        self
    }

    /// Disables the framework label.
    pub fn without_framework(mut self) -> Self {
        self.framework = None;
        self
    }

    /// Disables synthetic suite labels.
    pub fn without_synthetic_suite_labels(mut self) -> Self {
        self.synthetic_suite_labels = false;
        self
    }

    /// Sets the status to use for unclassified panics.
    pub fn with_panic_status(mut self, status: Status) -> Self {
        self.panic_status = Some(status);
        self
    }
}

impl From<StartTestCaseParams> for TestOptions {
    fn from(params: StartTestCaseParams) -> Self {
        Self::from_params(params)
    }
}

/// Reports a Rust test return value as an Allure outcome.
///
/// This mirrors the return shapes accepted by modern Rust test functions without consuming the
/// value before the test harness receives it.
pub trait AllureTestOutcome: Sized {
    /// Returns a successful value used when the test is filtered out before execution.
    fn successful() -> Self;

    /// Returns the Allure status represented by this value.
    fn status(&self) -> (Status, Option<StatusDetails>);
}

impl AllureTestOutcome for () {
    fn successful() -> Self {}

    fn status(&self) -> (Status, Option<StatusDetails>) {
        (Status::Passed, None)
    }
}

impl<T, E> AllureTestOutcome for Result<T, E>
where
    T: AllureTestOutcome,
    E: fmt::Debug,
{
    fn successful() -> Self {
        Ok(T::successful())
    }

    fn status(&self) -> (Status, Option<StatusDetails>) {
        match self {
            Ok(value) => value.status(),
            Err(error) => {
                let (status, details) = error_classifier::classify_message(format!("{error:?}"));
                (status, Some(details))
            }
        }
    }
}

impl AllureTestOutcome for ExitCode {
    fn successful() -> Self {
        ExitCode::SUCCESS
    }

    fn status(&self) -> (Status, Option<StatusDetails>) {
        if self == &ExitCode::SUCCESS {
            (Status::Passed, None)
        } else {
            (
                Status::Broken,
                Some(status_details_for_message(
                    "test returned unsuccessful ExitCode".to_string(),
                )),
            )
        }
    }
}

/// Outcome produced after interpreting a Rust test return value.
#[doc(hidden)]
pub struct AllureOutcomeReport {
    /// Exit code that should be returned to Rust's test harness.
    pub exit_code: ExitCode,
    /// Allure status represented by the return value.
    pub status: Status,
    /// Optional status details represented by the return value.
    pub details: Option<StatusDetails>,
}

/// Concrete return-value probe used by generated test wrappers.
#[doc(hidden)]
pub struct AllureOutcomeProbe<R> {
    value: Option<R>,
}

impl<R> AllureOutcomeProbe<R> {
    /// Creates a probe for a concrete Rust test return value.
    pub fn new(value: R) -> Self {
        Self { value: Some(value) }
    }
}

/// Finishes an [`AllureOutcomeProbe`] using the most specific known outcome contract.
#[doc(hidden)]
pub trait FinishAllureOutcome {
    /// Reports the probed value to Rust's test harness and returns the matching Allure outcome.
    fn finish_allure_outcome(self) -> std::thread::Result<AllureOutcomeReport>;
}

impl<R> FinishAllureOutcome for AllureOutcomeProbe<R>
where
    R: AllureTestOutcome + Termination,
{
    fn finish_allure_outcome(mut self) -> std::thread::Result<AllureOutcomeReport> {
        let (status, details) = self
            .value
            .as_ref()
            .expect("allure outcome value should be available")
            .status();
        let value = self
            .value
            .take()
            .expect("allure outcome value should be available");
        let exit_code = panic::catch_unwind(AssertUnwindSafe(|| value.report()))?;

        Ok(AllureOutcomeReport {
            exit_code,
            status,
            details,
        })
    }
}

impl<R> FinishAllureOutcome for &mut AllureOutcomeProbe<R>
where
    R: Termination,
{
    fn finish_allure_outcome(self) -> std::thread::Result<AllureOutcomeReport> {
        let value = self
            .value
            .take()
            .expect("allure outcome value should be available");
        let exit_code = panic::catch_unwind(AssertUnwindSafe(|| value.report()))?;
        let (status, details) = if exit_code == ExitCode::SUCCESS {
            (Status::Passed, None)
        } else {
            (
                Status::Broken,
                Some(status_details_for_message(
                    "test returned unsuccessful Termination status".to_string(),
                )),
            )
        };

        Ok(AllureOutcomeReport {
            exit_code,
            status,
            details,
        })
    }
}

/// Runs a synchronous test body with inferred Allure metadata.
pub fn test<R, F>(body: F) -> R
where
    F: FnOnce() -> R,
{
    test_with(TestOptions::inferred(), body)
}

/// Runs a synchronous test body with a custom display name.
pub fn test_named<R, F>(name: impl Into<String>, body: F) -> R
where
    F: FnOnce() -> R,
{
    let full_name = current_test_full_name();
    test_with(TestOptions::new(name).with_full_name(full_name), body)
}

/// Runs a synchronous test body with explicit options.
pub fn test_with<R, F>(options: impl Into<TestOptions>, body: F) -> R
where
    F: FnOnce() -> R,
{
    let runtime_test = start_runtime_test(options.into());
    let _current_allure = push_current_allure(&runtime_test.allure);
    let result = panic::catch_unwind(AssertUnwindSafe(body));
    finish_runtime_test(runtime_test, result)
}

/// Runs a synchronous test body and reports Result-like return values as Allure outcomes.
pub fn test_with_outcome<R, F>(options: impl Into<TestOptions>, body: F) -> R
where
    R: AllureTestOutcome,
    F: FnOnce() -> R,
{
    let runtime_test = start_runtime_test(options.into());
    let _current_allure = push_current_allure(&runtime_test.allure);
    let result = panic::catch_unwind(AssertUnwindSafe(body));
    finish_runtime_test_with_outcome(runtime_test, result)
}

/// Runs an async test future with inferred Allure metadata.
pub async fn test_async<R, F>(future: F) -> R
where
    F: Future<Output = R>,
{
    test_with_async(TestOptions::inferred(), future).await
}

/// Runs an async test future with a custom display name.
pub async fn test_named_async<R, F>(name: impl Into<String>, future: F) -> R
where
    F: Future<Output = R>,
{
    let full_name = current_test_full_name();
    test_with_async(TestOptions::new(name).with_full_name(full_name), future).await
}

/// Runs an async test future with explicit options.
pub async fn test_with_async<R, F>(options: impl Into<TestOptions>, future: F) -> R
where
    F: Future<Output = R>,
{
    let runtime_test = start_runtime_test(options.into());
    let result = RuntimeTestFuture {
        allure: runtime_test.allure.clone(),
        future: Box::pin(future),
    }
    .await;
    finish_runtime_test(runtime_test, result)
}

/// Runs an async test future and reports Result-like return values as Allure outcomes.
pub async fn test_with_outcome_async<R, F>(options: impl Into<TestOptions>, future: F) -> R
where
    R: AllureTestOutcome,
    F: Future<Output = R>,
{
    let runtime_test = start_runtime_test(options.into());
    let result = RuntimeTestFuture {
        allure: runtime_test.allure.clone(),
        future: Box::pin(future),
    }
    .await;
    finish_runtime_test_with_outcome(runtime_test, result)
}

/// In-progress runtime test state used by generated adapter code.
#[doc(hidden)]
pub struct RuntimeTest {
    allure: AllureFacade,
    panic_status: Option<Status>,
}

fn start_runtime_test(options: TestOptions) -> RuntimeTest {
    let writer = FileSystemResultsWriter::from_env().expect("allure writer should be created");
    let runtime = AllureRuntime::new(writer);
    let allure = AllureFacade::with_lifecycle(runtime.lifecycle());
    let TestOptions {
        params,
        manifest_dir,
        module_path,
        title_path,
        framework,
        synthetic_suite_labels,
        panic_status,
    } = options;
    let full_name = params.full_name.clone();

    allure.start_test_case(params);
    clear_last_assertion_failure();
    apply_common_runtime_labels(&allure);
    if let Some(framework) = framework {
        allure.label("framework", framework);
    }
    if synthetic_suite_labels {
        apply_synthetic_suite_labels(&allure, full_name.as_deref());
    }
    if let Some(title_path) = title_path {
        if let (Some(manifest_dir), Some(module_path)) = (&manifest_dir, &module_path) {
            apply_config_labels(&allure, manifest_dir, module_path, &title_path);
        }
        allure.title_path(title_path);
    } else if let (Some(manifest_dir), Some(module_path)) = (&manifest_dir, &module_path) {
        apply_config_labels(&allure, manifest_dir, module_path, &[]);
    }

    RuntimeTest {
        allure,
        panic_status,
    }
}

/// Starts a runtime test with explicit options for generated adapter code.
#[doc(hidden)]
pub fn start_runtime_test_with_options(options: impl Into<TestOptions>) -> RuntimeTest {
    start_runtime_test(options.into())
}

/// Pushes the current Allure context for generated adapter code.
#[doc(hidden)]
pub fn push_runtime_test_allure(runtime_test: &RuntimeTest) -> CurrentAllureGuard {
    push_current_allure(&runtime_test.allure)
}

/// Polls a future with the runtime test's Allure context installed.
#[doc(hidden)]
pub async fn run_runtime_test_future<R, F>(
    runtime_test: &RuntimeTest,
    future: F,
) -> std::thread::Result<R>
where
    F: Future<Output = R>,
{
    RuntimeTestFuture {
        allure: runtime_test.allure.clone(),
        future: Box::pin(future),
    }
    .await
}

/// Finishes a runtime test with an explicit status for generated adapter code.
#[doc(hidden)]
pub fn finish_runtime_test_status(
    runtime_test: RuntimeTest,
    status: Status,
    details: Option<StatusDetails>,
) {
    runtime_test.allure.end_test(status, details);
}

/// Finishes a runtime test for a panic and resumes unwinding.
#[doc(hidden)]
pub fn finish_runtime_test_panic(runtime_test: RuntimeTest, payload: Box<dyn Any + Send>) -> ! {
    let (status, details) = error_classifier::classify_panic(&payload);
    let status = runtime_test.panic_status.unwrap_or(status);
    let message = details.message.clone().unwrap_or_default();
    runtime_test
        .allure
        .end_test(status, Some(status_details_for_message(message)));
    panic::resume_unwind(payload);
}

fn finish_runtime_test<R>(runtime_test: RuntimeTest, result: std::thread::Result<R>) -> R {
    match result {
        Ok(value) => {
            runtime_test.allure.end_test(Status::Passed, None);
            value
        }
        Err(payload) => finish_runtime_test_panic(runtime_test, payload),
    }
}

fn finish_runtime_test_with_outcome<R>(
    runtime_test: RuntimeTest,
    result: std::thread::Result<R>,
) -> R
where
    R: AllureTestOutcome,
{
    match result {
        Ok(value) => {
            let (status, details) = value.status();
            runtime_test.allure.end_test(status, details);
            value
        }
        Err(payload) => finish_runtime_test_panic(runtime_test, payload),
    }
}

fn current_test_full_name() -> String {
    std::thread::current()
        .name()
        .map(ToString::to_string)
        .filter(|name| !name.trim().is_empty())
        .unwrap_or_else(|| format!("{:?}", std::thread::current().id()))
}

fn test_name_from_full_name(full_name: &str) -> String {
    full_name
        .rsplit("::")
        .next()
        .filter(|name| !name.is_empty())
        .unwrap_or(full_name)
        .to_string()
}

struct RuntimeTestFuture<F> {
    allure: AllureFacade,
    future: Pin<Box<F>>,
}

impl<F> Future for RuntimeTestFuture<F>
where
    F: Future,
{
    type Output = std::thread::Result<F::Output>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        let _current_allure = push_current_allure(&this.allure);
        match panic::catch_unwind(AssertUnwindSafe(|| this.future.as_mut().poll(cx))) {
            Ok(Poll::Ready(output)) => Poll::Ready(Ok(output)),
            Ok(Poll::Pending) => Poll::Pending,
            Err(payload) => Poll::Ready(Err(payload)),
        }
    }
}

/// Sets the markdown description on the current test.
pub fn description(description: impl Into<String>) {
    active_allure().description(description);
}

/// Sets the HTML description on the current test.
pub fn description_html(description: impl Into<String>) {
    active_allure().description_html(description);
}

/// Sets the display name of the current test.
pub fn display_name(name: impl Into<String>) {
    active_allure().display_name(name);
}

/// Adds a label to the current test.
pub fn label(name: impl Into<String>, value: impl Into<String>) {
    active_allure().label(name, value);
}

/// Adds multiple labels to the current test.
pub fn labels<I, K, V>(labels: I)
where
    I: IntoIterator<Item = (K, V)>,
    K: Into<String>,
    V: Into<String>,
{
    active_allure().labels(labels);
}

/// Adds a link to the current test.
pub fn link<U, N, T>(url: U, name: Option<N>, link_type: Option<T>)
where
    U: Into<String>,
    N: Into<String>,
    T: Into<String>,
{
    active_allure().link(url, name.map(Into::into), link_type.map(Into::into));
}

/// Adds multiple links to the current test.
pub fn links<I, U, N, T>(links: I)
where
    I: IntoIterator<Item = (U, Option<N>, Option<T>)>,
    U: Into<String>,
    N: Into<String>,
    T: Into<String>,
{
    active_allure().links(links);
}

/// Adds a parameter to the current test.
pub fn parameter(name: impl Into<String>, value: impl Into<String>) {
    active_allure().parameter(name, value);
}

/// Adds a parameter and controls whether it participates in history identity.
pub fn parameter_excluded(name: impl Into<String>, value: impl Into<String>, excluded: bool) {
    active_allure().parameter_excluded(name, value, excluded);
}

/// Adds a parameter with a display mode.
pub fn parameter_mode(name: impl Into<String>, value: impl Into<String>, mode: ParameterMode) {
    active_allure().parameter_mode(name, value, mode);
}

/// Adds a parameter with identity and display options.
pub fn parameter_with_options(
    name: impl Into<String>,
    value: impl Into<String>,
    excluded: Option<bool>,
    mode: Option<ParameterMode>,
) {
    active_allure().parameter_with_options(name, value, excluded, mode);
}

/// Sets the current test title path.
pub fn set_title_path<I, V>(title_path: I)
where
    I: IntoIterator<Item = V>,
    V: Into<String>,
{
    active_allure().title_path(title_path);
}

/// Sets the current test case identifier.
pub fn test_case_id(value: impl Into<String>) {
    active_allure().test_case_id(value);
}

/// Sets the current test history identifier.
pub fn history_id(value: impl Into<String>) {
    active_allure().history_id(value);
}

/// Adds an attachment as an ordered evidence step.
pub fn attachment(
    name: impl Into<String>,
    content_type: impl Into<String>,
    body: impl AsRef<[u8]>,
) {
    active_allure().attachment(name, content_type, body);
}

/// Adds a file attachment as an ordered evidence step.
pub fn attachment_path(
    name: impl Into<String>,
    content_type: impl Into<String>,
    path: impl AsRef<Path>,
) -> std::io::Result<()> {
    active_allure().attachment_path(name, content_type, path)
}

/// Adds a Playwright trace attachment named `trace.zip`.
pub fn attach_trace(path: impl AsRef<Path>) -> std::io::Result<()> {
    active_allure().attach_trace(path)
}

/// Adds a named Playwright trace attachment.
pub fn attach_trace_named(name: impl Into<String>, path: impl AsRef<Path>) -> std::io::Result<()> {
    active_allure().attach_trace_named(name, path)
}

/// Adds a run-level attachment.
pub fn global_attachment(
    name: impl Into<String>,
    content_type: impl Into<String>,
    body: impl AsRef<[u8]>,
) -> std::io::Result<()> {
    active_allure().global_attachment(name, content_type, body)
}

/// Adds a run-level file attachment.
pub fn global_attachment_path(
    name: impl Into<String>,
    content_type: impl Into<String>,
    path: impl AsRef<Path>,
) -> std::io::Result<()> {
    active_allure().global_attachment_path(name, content_type, path)
}

/// Adds a run-level error.
pub fn global_error(message: impl Into<String>) -> std::io::Result<()> {
    active_allure().global_error(message)
}

/// Adds a run-level error with a trace.
pub fn global_error_with_trace(
    message: impl Into<String>,
    trace: impl Into<String>,
) -> std::io::Result<()> {
    active_allure().global_error_with_trace(message, trace)
}

/// Adds an HTTP exchange as an ordered evidence step.
pub fn http_exchange(exchange: HttpExchange) {
    active_allure().http_exchange(exchange);
}

/// Adds a named HTTP exchange as an ordered evidence step.
pub fn http_exchange_named(name: impl Into<String>, exchange: HttpExchange) {
    active_allure().http_exchange_named(name, exchange);
}

/// Runs a lambda-style step.
pub fn step<T, F>(name: impl Into<String>, body: F) -> T
where
    F: FnOnce() -> T,
{
    active_allure().step(name, body)
}

/// Starts a semantic stage under the current owner.
pub fn stage(name: impl Into<String>) {
    active_allure().stage(name);
}

/// Records a passed log step.
pub fn log_step(name: impl Into<String>) {
    active_allure().log_step(name);
}

/// Records an instant log step with optional status and error details.
pub fn log_step_with<E>(name: impl Into<String>, status: Option<Status>, error: Option<E>)
where
    E: ToString,
{
    active_allure().log_step_with(name, status, error);
}

/// Adds an issue link to the current test.
pub fn issue(name: impl Into<String>, url: impl Into<String>) {
    active_allure().issue(name, url);
}

/// Adds a test-management-system link to the current test.
pub fn tms(name: impl Into<String>, url: impl Into<String>) {
    active_allure().tms(name, url);
}

/// Adds an `epic` label.
pub fn epic(value: impl Into<String>) {
    active_allure().epic(value);
}

/// Adds a `feature` label.
pub fn feature(value: impl Into<String>) {
    active_allure().feature(value);
}

/// Adds a `story` label.
pub fn story(value: impl Into<String>) {
    active_allure().story(value);
}

/// Sets the `suite` label.
pub fn suite(value: impl Into<String>) {
    active_allure().suite(value);
}

/// Sets the `parentSuite` label.
pub fn parent_suite(value: impl Into<String>) {
    active_allure().parent_suite(value);
}

/// Sets the `subSuite` label.
pub fn sub_suite(value: impl Into<String>) {
    active_allure().sub_suite(value);
}

/// Adds an `owner` label.
pub fn owner(value: impl Into<String>) {
    active_allure().owner(value);
}

/// Adds a `severity` label.
pub fn severity(value: impl Into<String>) {
    active_allure().severity(value);
}

/// Adds a `layer` label.
pub fn layer(value: impl Into<String>) {
    active_allure().layer(value);
}

/// Adds a `tag` label.
pub fn tag(value: impl Into<String>) {
    active_allure().tag(value);
}

/// Adds multiple `tag` labels.
pub fn tags<I, V>(tags: I)
where
    I: IntoIterator<Item = V>,
    V: Into<String>,
{
    active_allure().tags(tags);
}

/// Adds the Allure ID label.
pub fn id(value: impl Into<String>) {
    active_allure().id(value);
}

/// Adds the Allure ID label.
pub fn allure_id(value: impl Into<String>) {
    active_allure().allure_id(value);
}

impl Drop for CurrentAllureGuard {
    fn drop(&mut self) {
        CURRENT_ALLURE.with(|current| {
            current.replace(self.previous.take());
        });
    }
}

/// Explicit Allure runtime facade.
#[derive(Clone, Default)]
pub struct AllureFacade {
    lifecycle: Option<AllureLifecycle>,
}

impl AllureFacade {
    /// Creates a facade backed by a lifecycle owner.
    pub fn with_lifecycle(lifecycle: AllureLifecycle) -> Self {
        Self {
            lifecycle: Some(lifecycle),
        }
    }

    /// Replaces the lifecycle owner used by this facade.
    pub fn set_lifecycle(&mut self, lifecycle: AllureLifecycle) {
        self.lifecycle = Some(lifecycle);
    }

    pub(crate) fn lifecycle(&self) -> Option<&AllureLifecycle> {
        self.lifecycle.as_ref()
    }

    /// Starts a test case through the underlying lifecycle.
    pub fn start_test_case(&self, params: impl Into<StartTestCaseParams>) {
        if let Some(l) = &self.lifecycle {
            l.start_test_case(params);
        }
    }

    /// Stops the current test case through the underlying lifecycle.
    pub fn stop_test_case(&self, status: Status, details: Option<StatusDetails>) {
        if let Some(l) = &self.lifecycle {
            l.stop_test_case(status, details);
        }
    }

    /// Starts a test with a display name.
    pub fn start_test(&self, name: impl Into<String>) {
        self.start_test_case(name.into());
    }

    /// Starts a test with a display name and full name.
    pub fn start_test_with_full_name(&self, name: impl Into<String>, full_name: impl Into<String>) {
        self.start_test_case(StartTestCaseParams::new(name).with_full_name(full_name));
    }

    /// Ends the current test with a final status.
    pub fn end_test(&self, status: Status, details: Option<StatusDetails>) {
        self.stop_test_case(status, details);
    }

    /// Sets the markdown description on the current test.
    pub fn description(&self, description: impl Into<String>) {
        if let Some(l) = &self.lifecycle {
            l.update_test_case(|t| t.description = Some(description.into()));
        }
    }

    /// Sets the HTML description on the current test.
    pub fn description_html(&self, description: impl Into<String>) {
        if let Some(l) = &self.lifecycle {
            l.update_test_case(|t| t.description_html = Some(description.into()));
        }
    }

    /// Sets the display name of the current test.
    pub fn display_name(&self, name: impl Into<String>) {
        if let Some(l) = &self.lifecycle {
            l.update_test_case(|t| t.name = name.into());
        }
    }

    /// Adds a label to the current test.
    pub fn label(&self, name: impl Into<String>, value: impl Into<String>) {
        if let Some(l) = &self.lifecycle {
            l.add_label(name, value);
        }
    }

    /// Adds multiple labels to the current test.
    pub fn labels<I, K, V>(&self, labels: I)
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        for (k, v) in labels {
            self.label(k, v);
        }
    }

    /// Adds a link to the current test.
    pub fn link(&self, url: impl Into<String>, name: Option<String>, link_type: Option<String>) {
        if let Some(l) = &self.lifecycle {
            l.add_link(url, name, link_type);
        }
    }

    /// Adds multiple links to the current test.
    pub fn links<I, U, N, T>(&self, links: I)
    where
        I: IntoIterator<Item = (U, Option<N>, Option<T>)>,
        U: Into<String>,
        N: Into<String>,
        T: Into<String>,
    {
        for (url, name, link_type) in links {
            self.link(url, name.map(Into::into), link_type.map(Into::into));
        }
    }

    /// Adds a parameter to the current test.
    pub fn parameter(&self, name: impl Into<String>, value: impl Into<String>) {
        self.parameter_with_options(name, value, None, None);
    }

    /// Adds a parameter and controls whether it participates in history identity.
    pub fn parameter_excluded(
        &self,
        name: impl Into<String>,
        value: impl Into<String>,
        excluded: bool,
    ) {
        self.parameter_with_options(name, value, Some(excluded), None);
    }

    /// Adds a parameter with a display mode.
    pub fn parameter_mode(
        &self,
        name: impl Into<String>,
        value: impl Into<String>,
        mode: ParameterMode,
    ) {
        self.parameter_with_options(name, value, None, Some(mode));
    }

    /// Adds a parameter with identity and display options.
    pub fn parameter_with_options(
        &self,
        name: impl Into<String>,
        value: impl Into<String>,
        excluded: Option<bool>,
        mode: Option<ParameterMode>,
    ) {
        if let Some(l) = &self.lifecycle {
            l.add_parameter_with_options(name, value, excluded, mode);
        }
    }

    /// Sets the current test title path.
    pub fn title_path<I, V>(&self, title_path: I)
    where
        I: IntoIterator<Item = V>,
        V: Into<String>,
    {
        if let Some(l) = &self.lifecycle {
            let title_path = title_path.into_iter().map(Into::into).collect();
            l.update_test_case(|test| test.title_path = Some(title_path));
        }
    }

    /// Sets the current test case identifier.
    pub fn test_case_id(&self, value: impl Into<String>) {
        if let Some(l) = &self.lifecycle {
            l.set_test_case_id(value);
        }
    }

    /// Sets the current test history identifier.
    pub fn history_id(&self, value: impl Into<String>) {
        if let Some(l) = &self.lifecycle {
            l.set_history_id(value);
        }
    }

    /// Adds an attachment as an ordered evidence step.
    pub fn attachment(
        &self,
        name: impl Into<String>,
        content_type: impl Into<String>,
        body: impl AsRef<[u8]>,
    ) {
        let name = name.into();
        let content_type = content_type.into();
        let body = body.as_ref().to_vec();
        self.step(name.clone(), || {
            current_owner::add_attachment(self, name, content_type, body);
        });
    }

    /// Adds a file attachment as an ordered evidence step.
    pub fn attachment_path(
        &self,
        name: impl Into<String>,
        content_type: impl Into<String>,
        path: impl AsRef<Path>,
    ) -> std::io::Result<()> {
        let bytes = fs::read(path)?;
        self.attachment(name, content_type, bytes);
        Ok(())
    }

    /// Adds a Playwright trace attachment named `trace.zip`.
    pub fn attach_trace(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
        self.attach_trace_named("trace.zip", path)
    }

    /// Adds a named Playwright trace attachment.
    pub fn attach_trace_named(
        &self,
        name: impl Into<String>,
        path: impl AsRef<Path>,
    ) -> std::io::Result<()> {
        self.attachment_path(name, PLAYWRIGHT_TRACE_ATTACHMENT_MIME, path)
    }

    /// Adds a run-level attachment.
    pub fn global_attachment(
        &self,
        name: impl Into<String>,
        content_type: impl Into<String>,
        body: impl AsRef<[u8]>,
    ) -> std::io::Result<()> {
        let name = name.into();
        let content_type = content_type.into();
        if let Some(l) = &self.lifecycle {
            return l.add_global_attachment(name, content_type, body.as_ref());
        }

        let writer = FileSystemResultsWriter::from_env()?;
        let (source, _) = writer.write_attachment_auto(
            &facade_id(),
            Some(&name),
            Some(&content_type),
            body.as_ref(),
        )?;
        write_globals(Globals {
            attachments: vec![GlobalAttachment {
                name,
                source,
                content_type,
            }],
            errors: Vec::new(),
        })
    }

    /// Adds a run-level file attachment.
    pub fn global_attachment_path(
        &self,
        name: impl Into<String>,
        content_type: impl Into<String>,
        path: impl AsRef<Path>,
    ) -> std::io::Result<()> {
        let bytes = fs::read(path)?;
        self.global_attachment(name, content_type, bytes)
    }

    /// Adds a run-level error.
    pub fn global_error(&self, message: impl Into<String>) -> std::io::Result<()> {
        let message = message.into();
        if let Some(l) = &self.lifecycle {
            return l.add_global_error(message, None);
        }

        write_globals(Globals {
            attachments: Vec::new(),
            errors: vec![GlobalError {
                message,
                trace: None,
            }],
        })
    }

    /// Adds a run-level error with a trace.
    pub fn global_error_with_trace(
        &self,
        message: impl Into<String>,
        trace: impl Into<String>,
    ) -> std::io::Result<()> {
        let message = message.into();
        let trace = trace.into();
        if let Some(l) = &self.lifecycle {
            return l.add_global_error(message, Some(trace));
        }

        write_globals(Globals {
            attachments: Vec::new(),
            errors: vec![GlobalError {
                message,
                trace: Some(trace),
            }],
        })
    }

    /// Adds an HTTP exchange as an ordered evidence step.
    pub fn http_exchange(&self, exchange: HttpExchange) {
        self.http_exchange_named(HTTP_EXCHANGE_ATTACHMENT_NAME, exchange);
    }

    /// Adds a named HTTP exchange as an ordered evidence step.
    pub fn http_exchange_named(&self, name: impl Into<String>, exchange: HttpExchange) {
        let name = name.into();
        self.step(name.clone(), || {
            current_owner::add_http_exchange_named(self, name, exchange);
        });
    }

    fn start_step_scope(&self, name: impl Into<String>) -> StepScope {
        if let Some(l) = &self.lifecycle {
            l.start_step(name);
            StepScope {
                lifecycle: self.lifecycle.clone(),
                status: Some(Status::Passed),
                details: None,
            }
        } else {
            StepScope {
                lifecycle: None,
                status: None,
                details: None,
            }
        }
    }

    /// Runs a lambda-style step.
    pub fn step<T, F>(&self, name: impl Into<String>, body: F) -> T
    where
        F: FnOnce() -> T,
    {
        let guard = self.start_step_scope(name);
        let outcome = panic::catch_unwind(AssertUnwindSafe(body));
        match outcome {
            Ok(value) => {
                drop(guard);
                value
            }
            Err(payload) => {
                let (status, details) = error_classifier::classify_panic(&payload);
                drop(guard.with_status(status, Some(details)));
                panic::resume_unwind(payload);
            }
        }
    }

    /// Starts a semantic stage under the current owner.
    pub fn stage(&self, name: impl Into<String>) {
        if let Some(l) = &self.lifecycle {
            l.start_stage(name);
        }
    }

    /// Records a passed log step.
    pub fn log_step(&self, name: impl Into<String>) {
        self.log_step_with(name, None, None::<String>);
    }

    /// Records an instant log step with optional status and error details.
    pub fn log_step_with<E>(
        &self,
        name: impl Into<String>,
        status: Option<Status>,
        error: Option<E>,
    ) where
        E: ToString,
    {
        if let Some(l) = &self.lifecycle {
            let timestamp = l.start_step_at(name, None);
            let status = status.unwrap_or(Status::Passed);
            let details = error.map(|error| StatusDetails {
                message: Some(error.to_string()),
                trace: None,
                actual: None,
                expected: None,
            });
            l.stop_step_at(Some(timestamp), status, details);
        }
    }

    /// Adds an issue link to the current test.
    pub fn issue(&self, name: impl Into<String>, url: impl Into<String>) {
        self.link(url.into(), Some(name.into()), Some("issue".to_string()));
    }

    /// Adds a test-management-system link to the current test.
    pub fn tms(&self, name: impl Into<String>, url: impl Into<String>) {
        self.link(url.into(), Some(name.into()), Some("tms".to_string()));
    }

    /// Adds an `epic` label.
    pub fn epic(&self, value: impl Into<String>) {
        self.label("epic", value);
    }
    /// Adds a `feature` label.
    pub fn feature(&self, value: impl Into<String>) {
        self.label("feature", value);
    }
    /// Adds a `story` label.
    pub fn story(&self, value: impl Into<String>) {
        self.label("story", value);
    }
    /// Sets the `suite` label.
    pub fn suite(&self, value: impl Into<String>) {
        self.label("suite", value);
    }
    /// Sets the `parentSuite` label.
    pub fn parent_suite(&self, value: impl Into<String>) {
        self.label("parentSuite", value);
    }
    /// Sets the `subSuite` label.
    pub fn sub_suite(&self, value: impl Into<String>) {
        self.label("subSuite", value);
    }
    /// Adds an `owner` label.
    pub fn owner(&self, value: impl Into<String>) {
        self.label("owner", value);
    }
    /// Adds a `severity` label.
    pub fn severity(&self, value: impl Into<String>) {
        self.label("severity", value);
    }
    /// Adds a `layer` label.
    pub fn layer(&self, value: impl Into<String>) {
        self.label("layer", value);
    }
    /// Adds a `tag` label.
    pub fn tag(&self, value: impl Into<String>) {
        self.label("tag", value);
    }
    /// Adds multiple `tag` labels.
    pub fn tags<I, V>(&self, tags: I)
    where
        I: IntoIterator<Item = V>,
        V: Into<String>,
    {
        for tag in tags {
            self.tag(tag);
        }
    }
    /// Adds the Allure ID label.
    pub fn id(&self, value: impl Into<String>) {
        self.label("ALLURE_ID", value);
    }
    /// Adds the Allure ID label.
    pub fn allure_id(&self, value: impl Into<String>) {
        self.id(value);
    }
}

struct StepScope {
    lifecycle: Option<AllureLifecycle>,
    status: Option<Status>,
    details: Option<StatusDetails>,
}

impl StepScope {
    fn with_status(mut self, status: Status, details: Option<StatusDetails>) -> Self {
        self.status = Some(status);
        self.details = details;
        self
    }
}

impl Drop for StepScope {
    fn drop(&mut self) {
        if let (Some(l), Some(status)) = (&self.lifecycle, self.status.clone()) {
            l.stop_step(status, self.details.clone());
        }
    }
}

#[doc(hidden)]
pub mod __private {
    use super::*;

    pub struct StepScope {
        allure: AllureFacade,
        status: Status,
        details: Option<StatusDetails>,
    }

    pub fn begin_step_scope(allure: AllureFacade, name: impl Into<String>) -> StepScope {
        if let Some(lifecycle) = &allure.lifecycle {
            lifecycle.start_step(name);
        }
        StepScope {
            allure,
            status: Status::Passed,
            details: None,
        }
    }

    impl Drop for StepScope {
        fn drop(&mut self) {
            let status = if std::thread::panicking() && matches!(self.status, Status::Passed) {
                Status::Broken
            } else {
                self.status.clone()
            };
            if let Some(lifecycle) = &self.allure.lifecycle {
                lifecycle.stop_step(status, self.details.take());
            }
        }
    }
}