allure-core 0.1.9

Core types and runtime for Allure test reporting
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
//! Runtime context management for tracking test execution state.
//!
//! This module provides thread-local storage for synchronous tests and
//! optional tokio task-local storage for async tests.

use std::backtrace::Backtrace;
use std::cell::RefCell;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::OnceLock;
#[cfg(feature = "tokio")]
use std::sync::{Arc, Mutex};

#[cfg(feature = "tokio")]
type SharedAsyncContext = Arc<Mutex<Option<TestContext>>>;
#[cfg(feature = "tokio")]
type GlobalAsyncContexts = Mutex<Vec<SharedAsyncContext>>;

use crate::enums::{ContentType, LabelName, LinkType, Severity, Status};
use crate::model::{Attachment, Label, Parameter, StepResult, TestResult, TestResultContainer};
use crate::writer::{compute_history_id, generate_uuid, AllureWriter};

/// Global configuration for the Allure runtime.
static CONFIG: OnceLock<AllureConfig> = OnceLock::new();

#[cfg(feature = "tokio")]
tokio::task_local! {
    static TOKIO_CONTEXT: RefCell<Option<SharedAsyncContext>>;
}

#[cfg(feature = "tokio")]
fn global_async_context() -> &'static GlobalAsyncContexts {
    static GLOBAL: OnceLock<GlobalAsyncContexts> = OnceLock::new();
    GLOBAL.get_or_init(|| Mutex::new(Vec::new()))
}

#[cfg(feature = "tokio")]
fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(|e| e.into_inner())
}

#[cfg(feature = "tokio")]
fn register_global_context(handle: SharedAsyncContext) {
    let mut handles = lock_unpoisoned(global_async_context());
    handles.push(handle);
}

#[cfg(feature = "tokio")]
fn unregister_global_context(handle: &SharedAsyncContext) {
    let mut handles = lock_unpoisoned(global_async_context());
    handles.retain(|candidate| !Arc::ptr_eq(candidate, handle));
}

#[cfg(feature = "tokio")]
fn current_global_context() -> Option<SharedAsyncContext> {
    let handles = lock_unpoisoned(global_async_context());
    if handles.len() == 1 {
        Some(handles[0].clone())
    } else {
        None
    }
}

#[cfg(feature = "tokio")]
struct GlobalContextRegistration {
    handle: SharedAsyncContext,
}

#[cfg(feature = "tokio")]
impl GlobalContextRegistration {
    fn new(handle: SharedAsyncContext) -> Self {
        register_global_context(handle.clone());
        Self { handle }
    }
}

#[cfg(feature = "tokio")]
impl Drop for GlobalContextRegistration {
    fn drop(&mut self) {
        unregister_global_context(&self.handle);
    }
}

/// Configuration for the Allure runtime.
#[derive(Debug, Clone)]
pub struct AllureConfig {
    /// Directory where results are written.
    pub results_dir: String,
    /// Whether to clean the results directory on init.
    pub clean_results: bool,
}

impl Default for AllureConfig {
    fn default() -> Self {
        Self {
            results_dir: crate::writer::DEFAULT_RESULTS_DIR.to_string(),
            clean_results: true,
        }
    }
}

/// Builder for configuring the Allure runtime.
#[derive(Debug, Default)]
pub struct AllureConfigBuilder {
    config: AllureConfig,
}

impl AllureConfigBuilder {
    /// Creates a new configuration builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the results directory.
    pub fn results_dir(mut self, path: impl Into<String>) -> Self {
        self.config.results_dir = path.into();
        self
    }

    /// Sets whether to clean the results directory.
    pub fn clean_results(mut self, clean: bool) -> Self {
        self.config.clean_results = clean;
        self
    }

    /// Initializes the Allure runtime with this configuration.
    pub fn init(self) -> std::io::Result<()> {
        let writer = AllureWriter::with_results_dir(&self.config.results_dir);
        writer.init(self.config.clean_results)?;
        CONFIG.set(self.config).ok();
        Ok(())
    }
}

/// Configures the Allure runtime.
pub fn configure() -> AllureConfigBuilder {
    AllureConfigBuilder::new()
}

/// Gets the current configuration or the default.
pub fn get_config() -> AllureConfig {
    CONFIG.get().cloned().unwrap_or_default()
}

/// Test context holding the current test result and step stack.
#[derive(Debug)]
pub struct TestContext {
    /// The current test result being built.
    pub result: TestResult,
    /// Stack of active steps (for nested steps).
    pub step_stack: Vec<StepResult>,
    /// The writer for this context.
    pub writer: AllureWriter,
}

impl TestContext {
    /// Creates a new test context.
    pub fn new(name: impl Into<String>, full_name: impl Into<String>) -> Self {
        let config = get_config();
        let uuid = generate_uuid();
        let mut result = TestResult::new(uuid, name.into());
        result.full_name = Some(full_name.into());

        // Add default labels
        result.labels.push(Label::language("rust"));
        result.labels.push(Label::framework("allure-rs"));

        // Add host and thread labels
        if let Ok(hostname) = std::env::var("HOSTNAME") {
            result.labels.push(Label::host(hostname));
        } else if let Ok(hostname) = hostname::get() {
            if let Some(name) = hostname.to_str() {
                result.labels.push(Label::host(name));
            }
        }

        let thread_id = format!("{:?}", std::thread::current().id());
        result.labels.push(Label::thread(thread_id));

        Self {
            result,
            step_stack: Vec::new(),
            writer: AllureWriter::with_results_dir(config.results_dir),
        }
    }

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

    /// Adds a label using a reserved name.
    pub fn add_label_name(&mut self, name: LabelName, value: impl Into<String>) {
        self.result.add_label_name(name, value);
    }

    /// Adds a link to the current test.
    pub fn add_link(&mut self, url: impl Into<String>, name: Option<String>, link_type: LinkType) {
        self.result.add_link(url, name, link_type);
    }

    /// Adds a parameter to the current test or step.
    pub fn add_parameter(&mut self, name: impl Into<String>, value: impl Into<String>) {
        if let Some(step) = self.step_stack.last_mut() {
            step.add_parameter(name, value);
        } else {
            self.result.add_parameter(name, value);
        }
    }

    /// Adds a parameter with custom options (hidden/masked/excluded).
    pub fn add_parameter_struct(&mut self, parameter: Parameter) {
        if let Some(step) = self.step_stack.last_mut() {
            step.parameters.push(parameter);
        } else {
            self.result.parameters.push(parameter);
        }
    }

    /// Adds an attachment to the current test or step.
    pub fn add_attachment(&mut self, attachment: Attachment) {
        if let Some(step) = self.step_stack.last_mut() {
            step.add_attachment(attachment);
        } else {
            self.result.add_attachment(attachment);
        }
    }

    /// Starts a new step.
    pub fn start_step(&mut self, name: impl Into<String>) {
        let step = StepResult::new(name);
        self.step_stack.push(step);
    }

    /// Finishes the current step with the given status.
    pub fn finish_step(&mut self, status: Status, message: Option<String>, trace: Option<String>) {
        if let Some(mut step) = self.step_stack.pop() {
            match status {
                Status::Passed => step.pass(),
                Status::Failed => step.fail(message, trace),
                Status::Broken => step.broken(message, trace),
                _ => {
                    step.status = status;
                    step.stage = crate::enums::Stage::Finished;
                    step.stop = crate::model::current_time_ms();
                }
            }

            // Add the finished step to the parent (either another step or the test result)
            if let Some(parent_step) = self.step_stack.last_mut() {
                parent_step.add_step(step);
            } else {
                self.result.add_step(step);
            }
        }
    }

    /// Computes and sets the history ID based on the full name and parameters.
    pub fn compute_history_id(&mut self) {
        if let Some(ref full_name) = self.result.full_name {
            let history_id = compute_history_id(full_name, &self.result.parameters);
            self.result.history_id = Some(history_id);
        }
    }

    /// Finishes the test with the given status and writes the result.
    pub fn finish(&mut self, status: Status, message: Option<String>, trace: Option<String>) {
        // Finish any remaining open steps
        while !self.step_stack.is_empty() {
            self.finish_step(Status::Broken, Some("Step not completed".to_string()), None);
        }

        // Compute history ID before finishing
        self.compute_history_id();

        match status {
            Status::Passed => self.result.pass(),
            Status::Failed => self.result.fail(message, trace),
            Status::Broken => self.result.broken(message, trace),
            Status::Skipped => {
                if message.is_some() || trace.is_some() {
                    self.result.status_details = Some(crate::model::StatusDetails {
                        message,
                        trace,
                        ..Default::default()
                    });
                }
                self.result.status = status;
                self.result.finish();
            }
            _ => {
                self.result.status = status;
                self.result.finish();
            }
        }

        // Write the result
        if let Err(e) = self.writer.write_test_result(&self.result) {
            eprintln!("Failed to write Allure test result: {}", e);
        }

        // Emit a container linking this test (even if no fixtures are present yet)
        let mut container = TestResultContainer::new(generate_uuid());
        container.children.push(self.result.uuid.clone());
        container.start = Some(self.result.start);
        container.stop = Some(self.result.stop);
        if let Err(e) = self.writer.write_container(&container) {
            eprintln!("Failed to write Allure container: {}", e);
        }
    }

    /// Creates a text attachment.
    pub fn attach_text(&mut self, name: impl Into<String>, content: impl AsRef<str>) {
        match self.writer.write_text_attachment(name, content) {
            Ok(attachment) => self.add_attachment(attachment),
            Err(e) => eprintln!("Failed to write text attachment: {}", e),
        }
    }

    /// Creates a JSON attachment.
    pub fn attach_json<T: serde::Serialize>(&mut self, name: impl Into<String>, value: &T) {
        match self.writer.write_json_attachment(name, value) {
            Ok(attachment) => self.add_attachment(attachment),
            Err(e) => eprintln!("Failed to write JSON attachment: {}", e),
        }
    }

    /// Creates a binary attachment.
    pub fn attach_binary(
        &mut self,
        name: impl Into<String>,
        content: &[u8],
        content_type: ContentType,
    ) {
        match self
            .writer
            .write_binary_attachment(name, content, content_type)
        {
            Ok(attachment) => self.add_attachment(attachment),
            Err(e) => eprintln!("Failed to write binary attachment: {}", e),
        }
    }

    /// Attaches a file from the filesystem.
    pub fn attach_file(
        &mut self,
        name: impl Into<String>,
        path: impl AsRef<std::path::Path>,
        content_type: Option<ContentType>,
    ) {
        match self.writer.copy_file_attachment(name, path, content_type) {
            Ok(attachment) => self.add_attachment(attachment),
            Err(e) => eprintln!("Failed to copy file attachment: {}", e),
        }
    }
}

// Thread-local storage for synchronous tests
thread_local! {
    static CURRENT_CONTEXT: RefCell<Option<TestContext>> = const { RefCell::new(None) };
}

/// Sets the current test context for the thread.
pub fn set_context(ctx: TestContext) {
    CURRENT_CONTEXT.with(|c| {
        *c.borrow_mut() = Some(ctx);
    });
}

/// Takes the current test context, leaving None in its place.
pub fn take_context() -> Option<TestContext> {
    #[cfg(feature = "tokio")]
    {
        if let Ok(context) = TOKIO_CONTEXT.try_with(|c| {
            let handle_opt = c.borrow().clone();
            handle_opt.and_then(|handle| {
                let mut guard = lock_unpoisoned(&handle);
                guard.take()
            })
        }) {
            if context.is_some() {
                return context;
            }
        }
    }

    let thread_local = CURRENT_CONTEXT.with(|c| c.borrow_mut().take());
    if thread_local.is_some() {
        return thread_local;
    }

    None
}

/// Executes a function with the current test context.
pub fn with_context<F, R>(f: F) -> Option<R>
where
    F: FnOnce(&mut TestContext) -> R,
{
    let mut f_opt = Some(f);

    #[cfg(feature = "tokio")]
    {
        if let Ok(result) = TOKIO_CONTEXT.try_with(|c| {
            let handle_opt = c.borrow().clone();
            if let Some(handle) = handle_opt {
                let mut guard = lock_unpoisoned(&handle);
                if let Some(ctx) = guard.as_mut() {
                    if let Some(func) = f_opt.take() {
                        return Some(func(ctx));
                    }
                }
            }
            None
        }) {
            if result.is_some() {
                return result;
            }
        }
    }

    let thread_local = CURRENT_CONTEXT
        .with(|c| {
            let mut ctx = c.borrow_mut();
            if let Some(ctx) = ctx.as_mut() {
                if let Some(func) = f_opt.take() {
                    return Some(func(ctx));
                }
            }
            None
        })
        .or_else(|| {
            #[cfg(feature = "tokio")]
            {
                if let Some(handle) = current_global_context() {
                    let mut guard = lock_unpoisoned(&handle);
                    if let Some(ctx) = guard.as_mut() {
                        if let Some(func) = f_opt.take() {
                            return Some(func(ctx));
                        }
                    }
                }
            }
            None
        });

    thread_local
}

/// Runs a test function with Allure tracking.
pub fn run_test<F>(name: &str, full_name: &str, f: F)
where
    F: FnOnce() + std::panic::UnwindSafe,
{
    let ctx = TestContext::new(name, full_name);
    set_context(ctx);

    let result = catch_unwind(AssertUnwindSafe(f));

    // Extract panic message if there was an error
    let (is_err, panic_payload) = match &result {
        Ok(()) => (false, None),
        Err(panic_info) => {
            let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
                Some(s.to_string())
            } else if let Some(s) = panic_info.downcast_ref::<String>() {
                Some(s.clone())
            } else {
                Some("Test panicked".to_string())
            };
            (true, msg)
        }
    };

    // Finish the test context
    if let Some(mut ctx) = take_context() {
        if is_err {
            let trace = capture_trace();
            ctx.finish(Status::Failed, panic_payload, trace);
        } else {
            ctx.finish(Status::Passed, None, None);
        }
    }

    // Re-panic if the test failed
    if let Err(e) = result {
        std::panic::resume_unwind(e);
    }
}

/// Executes a closure with a temporary test context for documentation examples.
///
/// This function is useful for running doc tests that use runtime functions
/// like `step()`, `label()`, etc. without needing the full test infrastructure.
/// No test results are written to disk.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, step, epic};
///
/// with_test_context(|| {
///     epic("My Epic");
///     step("Do something", || {
///         // test code
///     });
/// });
/// ```
#[doc(hidden)]
pub fn with_test_context<F, R>(f: F) -> R
where
    F: FnOnce() -> R,
{
    let ctx = TestContext::new("doctest", "doctest::example");
    set_context(ctx);
    let result = f();
    let _ = take_context(); // cleanup without writing
    result
}

// === Public API functions ===

/// Adds a label to the current test.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, label};
///
/// with_test_context(|| {
///     label("environment", "staging");
///     label("browser", "chrome");
/// });
/// ```
pub fn label(name: impl Into<String>, value: impl Into<String>) {
    with_context(|ctx| ctx.add_label(name, value));
}

/// Adds an epic label to the current test.
///
/// Epics represent high-level business capabilities in the BDD hierarchy.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, epic};
///
/// with_test_context(|| {
///     epic("User Management");
/// });
/// ```
pub fn epic(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::Epic, name));
}

/// Adds a feature label to the current test.
///
/// Features represent specific functionality under an epic.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, feature};
///
/// with_test_context(|| {
///     feature("User Registration");
/// });
/// ```
pub fn feature(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::Feature, name));
}

/// Adds a story label to the current test.
///
/// Stories represent user stories under a feature.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, story};
///
/// with_test_context(|| {
///     story("User can register with email");
/// });
/// ```
pub fn story(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::Story, name));
}

/// Adds a suite label to the current test.
pub fn suite(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::Suite, name));
}

/// Adds a parent suite label to the current test.
pub fn parent_suite(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::ParentSuite, name));
}

/// Adds a sub-suite label to the current test.
pub fn sub_suite(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::SubSuite, name));
}

/// Adds a severity label to the current test.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, severity};
/// use allure_core::Severity;
///
/// with_test_context(|| {
///     severity(Severity::Critical);
/// });
/// ```
pub fn severity(severity: Severity) {
    with_context(|ctx| ctx.add_label_name(LabelName::Severity, severity.as_str()));
}

/// Adds an owner label to the current test.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, owner};
///
/// with_test_context(|| {
///     owner("platform-team");
/// });
/// ```
pub fn owner(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::Owner, name));
}

/// Adds a tag label to the current test.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, tag};
///
/// with_test_context(|| {
///     tag("smoke");
///     tag("regression");
/// });
/// ```
pub fn tag(name: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::Tag, name));
}

/// Adds multiple tag labels to the current test.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, tags};
///
/// with_test_context(|| {
///     tags(&["smoke", "regression", "api"]);
/// });
/// ```
pub fn tags(names: &[&str]) {
    with_context(|ctx| {
        for name in names {
            ctx.add_label_name(LabelName::Tag, *name);
        }
    });
}

/// Adds an Allure ID label to the current test.
pub fn allure_id(id: impl Into<String>) {
    with_context(|ctx| ctx.add_label_name(LabelName::AllureId, id));
}

/// Sets a custom title for the current test.
///
/// This overrides the test name displayed in the Allure report.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, title};
///
/// with_test_context(|| {
///     title("User can login with valid credentials");
/// });
/// ```
pub fn title(name: impl Into<String>) {
    with_context(|ctx| ctx.result.name = name.into());
}

/// Sets the test description (markdown).
pub fn description(text: impl Into<String>) {
    with_context(|ctx| ctx.result.description = Some(text.into()));
}

/// Sets the test description (HTML).
pub fn description_html(html: impl Into<String>) {
    with_context(|ctx| ctx.result.description_html = Some(html.into()));
}

/// Adds an issue link to the current test.
pub fn issue(url: impl Into<String>, name: Option<String>) {
    with_context(|ctx| ctx.add_link(url, name, LinkType::Issue));
}

/// Adds a TMS link to the current test.
pub fn tms(url: impl Into<String>, name: Option<String>) {
    with_context(|ctx| ctx.add_link(url, name, LinkType::Tms));
}

/// Adds a generic link to the current test.
pub fn link(url: impl Into<String>, name: Option<String>) {
    with_context(|ctx| ctx.add_link(url, name, LinkType::Default));
}

/// Adds a parameter to the current test or step.
///
/// Parameters are displayed in the Allure report and can be used
/// to understand what inputs were used for a test run.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, parameter};
///
/// with_test_context(|| {
///     parameter("username", "john_doe");
///     parameter("count", 42);
/// });
/// ```
pub fn parameter(name: impl Into<String>, value: impl ToString) {
    with_context(|ctx| ctx.add_parameter(name, value.to_string()));
}

/// Adds a parameter hidden from display (value not shown in the report).
pub fn parameter_hidden(name: impl Into<String>, value: impl ToString) {
    with_context(|ctx| ctx.add_parameter_struct(Parameter::hidden(name, value.to_string())));
}

/// Adds a parameter with a masked value (e.g., passwords).
pub fn parameter_masked(name: impl Into<String>, value: impl ToString) {
    with_context(|ctx| ctx.add_parameter_struct(Parameter::masked(name, value.to_string())));
}

/// Adds a parameter excluded from history ID calculation.
pub fn parameter_excluded(name: impl Into<String>, value: impl ToString) {
    with_context(|ctx| ctx.add_parameter_struct(Parameter::excluded(name, value.to_string())));
}

/// Executes a step with the given name and body.
///
/// Steps are the building blocks of test reports. They provide
/// a hierarchical view of what the test is doing and can be nested.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, step};
///
/// with_test_context(|| {
///     step("Login to application", || {
///         step("Enter credentials", || {
///             // Enter username and password
///         });
///         step("Click submit", || {
///             // Click the submit button
///         });
///     });
/// });
/// ```
///
/// Steps can also return values:
///
/// ```
/// use allure_core::runtime::{with_test_context, step};
///
/// with_test_context(|| {
///     let result = step("Calculate result", || {
///         2 + 2
///     });
///     assert_eq!(result, 4);
/// });
/// ```
pub fn step<F, R>(name: impl Into<String>, body: F) -> R
where
    F: FnOnce() -> R,
{
    let step_name = name.into();

    with_context(|ctx| ctx.start_step(&step_name));

    let result = catch_unwind(AssertUnwindSafe(body));

    match &result {
        Ok(_) => {
            with_context(|ctx| ctx.finish_step(Status::Passed, None, None));
        }
        Err(panic_info) => {
            let message = if let Some(s) = panic_info.downcast_ref::<&str>() {
                Some(s.to_string())
            } else if let Some(s) = panic_info.downcast_ref::<String>() {
                Some(s.clone())
            } else {
                Some("Step panicked".to_string())
            };
            let trace = capture_trace();
            with_context(|ctx| ctx.finish_step(Status::Failed, message, trace));
        }
    }

    match result {
        Ok(value) => value,
        Err(e) => std::panic::resume_unwind(e),
    }
}

/// Logs a step without a body (for simple logging).
///
/// This is useful for logging actions that don't have a body,
/// such as noting an event or state.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, log_step};
/// use allure_core::Status;
///
/// with_test_context(|| {
///     log_step("Database connection established", Status::Passed);
///     log_step("Cache was cleared", Status::Passed);
/// });
/// ```
pub fn log_step(name: impl Into<String>, status: Status) {
    with_context(|ctx| {
        ctx.start_step(name);
        ctx.finish_step(status, None, None);
    });
}

/// Attaches text content to the current test or step.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, attach_text};
///
/// with_test_context(|| {
///     attach_text("API Response", r#"{"status": "ok"}"#);
///     attach_text("Log Output", "Test completed successfully");
/// });
/// ```
pub fn attach_text(name: impl Into<String>, content: impl AsRef<str>) {
    with_context(|ctx| ctx.attach_text(name, content));
}

/// Attaches JSON content to the current test or step.
///
/// The value is serialized to JSON using serde.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, attach_json};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct User {
///     name: String,
///     email: String,
/// }
///
/// with_test_context(|| {
///     let user = User {
///         name: "John".to_string(),
///         email: "john@example.com".to_string(),
///     };
///     attach_json("User Data", &user);
/// });
/// ```
pub fn attach_json<T: serde::Serialize>(name: impl Into<String>, value: &T) {
    with_context(|ctx| ctx.attach_json(name, value));
}

/// Attaches binary content to the current test or step.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, attach_binary};
/// use allure_core::ContentType;
///
/// with_test_context(|| {
///     let png_data: &[u8] = &[0x89, 0x50, 0x4E, 0x47]; // PNG header
///     attach_binary("Screenshot", png_data, ContentType::Png);
/// });
/// ```
pub fn attach_binary(name: impl Into<String>, content: &[u8], content_type: ContentType) {
    with_context(|ctx| ctx.attach_binary(name, content, content_type));
}

/// Marks the current test as flaky.
///
/// Flaky tests are tests that can fail intermittently due to
/// external factors like network issues or timing problems.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, flaky};
///
/// with_test_context(|| {
///     flaky();
///     // Test code that sometimes fails due to network issues
/// });
/// ```
pub fn flaky() {
    with_context(|ctx| {
        let details = ctx
            .result
            .status_details
            .get_or_insert_with(Default::default);
        details.flaky = Some(true);
    });
}

/// Marks the current test as muted.
///
/// Muted tests are tests whose results will not affect the statistics
/// in the Allure report. The test is still executed and documented,
/// but won't impact pass/fail metrics.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, muted};
///
/// with_test_context(|| {
///     muted();
///     // Test code that shouldn't affect statistics
/// });
/// ```
pub fn muted() {
    with_context(|ctx| {
        let details = ctx
            .result
            .status_details
            .get_or_insert_with(Default::default);
        details.muted = Some(true);
    });
}

/// Marks the current test as having a known issue.
///
/// This adds an issue link and marks the test status as having a known issue.
///
/// # Example
///
/// ```
/// use allure_core::runtime::{with_test_context, known_issue};
///
/// with_test_context(|| {
///     known_issue("https://github.com/example/project/issues/123");
/// });
/// ```
pub fn known_issue(issue_id: impl Into<String>) {
    let id = issue_id.into();
    with_context(|ctx| {
        let details = ctx
            .result
            .status_details
            .get_or_insert_with(Default::default);
        details.known = Some(true);
        // Also add as an issue link
        ctx.add_link(&id, Some(id.clone()), LinkType::Issue);
    });
}

/// Marks the current test as skipped and finalizes the result.
pub fn skip(reason: impl Into<String>) {
    let reason = reason.into();
    if let Some(mut ctx) = take_context() {
        ctx.finish(Status::Skipped, Some(reason), None);
    }
}

/// Sets the display name for the current test.
///
/// This overrides the test name that was set when the test context was created.
pub fn display_name(name: impl Into<String>) {
    with_context(|ctx| ctx.result.name = name.into());
}

/// Sets the test case ID for the current test.
///
/// This is used to link the test to a test case in a test management system.
pub fn test_case_id(id: impl Into<String>) {
    with_context(|ctx| ctx.result.test_case_id = Some(id.into()));
}

/// Attaches a file from the filesystem to the current test or step.
///
/// The file is copied to the Allure results directory.
pub fn attach_file(
    name: impl Into<String>,
    path: impl AsRef<std::path::Path>,
    content_type: Option<ContentType>,
) {
    with_context(|ctx| ctx.attach_file(name, path, content_type));
}

/// Captures a backtrace as a string when available.
fn capture_trace() -> Option<String> {
    let bt = Backtrace::force_capture();
    let snapshot = format!("{bt:?}");
    if snapshot.contains("disabled") {
        return None;
    }
    Some(snapshot)
}

/// Executes an async block with a task-local test context (tokio only).
#[cfg(feature = "tokio")]
pub async fn with_async_context<F, R>(ctx: TestContext, fut: F) -> R
where
    F: std::future::Future<Output = R>,
{
    let handle = Arc::new(Mutex::new(Some(ctx)));
    let _registration = GlobalContextRegistration::new(handle.clone());

    let cell = RefCell::new(Some(handle));
    TOKIO_CONTEXT.scope(cell, fut).await
}

/// Executes an async block with a thread-local test context (non-tokio fallback).
#[cfg(not(feature = "tokio"))]
pub async fn with_async_context<F, R>(ctx: TestContext, fut: F) -> R
where
    F: std::future::Future<Output = R>,
{
    set_context(ctx);
    let result = fut.await;
    let _ = take_context();
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use std::path::PathBuf;

    #[test]
    fn test_config_builder() {
        let config = AllureConfigBuilder::new()
            .results_dir("custom-results")
            .clean_results(false)
            .config;

        assert_eq!(config.results_dir, "custom-results");
        assert!(!config.clean_results);
    }

    #[test]
    fn test_context_creation() {
        let ctx = TestContext::new("My Test", "tests::my_test");
        assert_eq!(ctx.result.name, "My Test");
        assert_eq!(ctx.result.full_name, Some("tests::my_test".to_string()));
        assert!(ctx
            .result
            .labels
            .iter()
            .any(|l| l.name == "language" && l.value == "rust"));
    }

    #[test]
    fn test_step_nesting() {
        let mut ctx = TestContext::new("Test", "test::test");

        ctx.start_step("Step 1");
        ctx.start_step("Step 1.1");
        ctx.finish_step(Status::Passed, None, None);
        ctx.finish_step(Status::Passed, None, None);

        assert_eq!(ctx.result.steps.len(), 1);
        assert_eq!(ctx.result.steps[0].name, "Step 1");
        assert_eq!(ctx.result.steps[0].steps.len(), 1);
        assert_eq!(ctx.result.steps[0].steps[0].name, "Step 1.1");
    }

    #[test]
    fn test_thread_local_context() {
        let ctx = TestContext::new("Test", "test::test");
        set_context(ctx);

        with_context(|ctx| {
            ctx.add_label("custom", "value");
        });

        let ctx = take_context().unwrap();
        assert!(ctx
            .result
            .labels
            .iter()
            .any(|l| l.name == "custom" && l.value == "value"));
    }

    #[test]
    fn test_capture_trace_runs() {
        // We only assert that it does not panic and returns an Option.
        let _maybe_trace = capture_trace();
    }

    #[test]
    fn test_run_test_writes_results_and_container_on_panic() {
        let desired_dir = PathBuf::from("target/allure-runtime-tests");
        let _ = std::fs::remove_dir_all(&desired_dir);

        let config_ref = CONFIG.get_or_init(|| AllureConfig {
            results_dir: desired_dir.to_string_lossy().to_string(),
            clean_results: true,
        });
        let dir = PathBuf::from(&config_ref.results_dir);
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let outcome = std::panic::catch_unwind(|| {
            run_test("panic_test", "runtime::panic_test", || {
                panic!("runtime boom");
            });
        });
        assert!(outcome.is_err());

        let mut result_files = Vec::new();
        let mut container_files = Vec::new();
        for entry in std::fs::read_dir(&dir).unwrap() {
            let path = entry.unwrap().path();
            if path.extension().and_then(|e| e.to_str()) == Some("json") {
                let name = path.file_name().unwrap().to_string_lossy().to_string();
                if name.contains("-result.json") {
                    result_files.push(path.clone());
                } else if name.contains("-container.json") {
                    container_files.push(path.clone());
                }
            }
        }

        assert!(!result_files.is_empty());
        assert!(!container_files.is_empty());

        let panic_result_json = result_files
            .iter()
            .find_map(|path| {
                let result_json: Value =
                    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()?;
                (result_json["name"] == "panic_test").then_some(result_json)
            })
            .expect("panic_test result json should exist");

        assert_eq!(panic_result_json["status"], "failed");
        assert!(panic_result_json["statusDetails"]["message"]
            .as_str()
            .unwrap()
            .contains("runtime boom"));
    }

    #[cfg(feature = "tokio")]
    #[tokio::test(flavor = "current_thread")]
    async fn test_take_context_reads_tokio_task_local() {
        let ctx = TestContext::new("tokio_ctx", "module::tokio_ctx");
        let taken = with_async_context(ctx, async {
            let inner = take_context();
            assert!(inner.is_some());
            inner.unwrap().result.name
        })
        .await;
        assert_eq!(taken, "tokio_ctx");
    }

    #[cfg(feature = "tokio")]
    #[tokio::test(flavor = "current_thread")]
    async fn test_with_context_uses_tokio_task_local() {
        let ctx = TestContext::new("tokio_ctx", "module::tokio_ctx");
        with_async_context(ctx, async {
            let mut seen = None;
            with_context(|c| {
                seen = Some(c.result.name.clone());
            });
            assert_eq!(seen.as_deref(), Some("tokio_ctx"));
        })
        .await;
    }

    #[cfg(feature = "tokio")]
    #[test]
    fn test_global_context_avoids_ambiguous_assignment() {
        let launch_barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
        let probe_barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
        let settle_barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));

        let run_in_runtime =
            |name: &'static str,
             launch_barrier: std::sync::Arc<tokio::sync::Barrier>,
             probe_barrier: std::sync::Arc<tokio::sync::Barrier>,
             settle_barrier: std::sync::Arc<tokio::sync::Barrier>| {
                std::thread::spawn(move || {
                    let rt = tokio::runtime::Builder::new_current_thread()
                        .enable_all()
                        .build()
                        .unwrap();

                    rt.block_on(async move {
                        let ctx = TestContext::new(name, format!("module::{name}"));
                        with_async_context(ctx, async move {
                            launch_barrier.wait().await;
                            tokio::spawn(async move {
                                probe_barrier.wait().await;
                                let mut seen = None;
                                with_context(|c| {
                                    seen = Some(c.result.name.clone());
                                });
                                settle_barrier.wait().await;
                                seen
                            })
                            .await
                            .unwrap()
                        })
                        .await
                    })
                })
            };

        let t1 = run_in_runtime(
            "ctx-one",
            launch_barrier.clone(),
            probe_barrier.clone(),
            settle_barrier.clone(),
        );
        let t2 = run_in_runtime("ctx-two", launch_barrier, probe_barrier, settle_barrier);

        let seen1 = t1.join().unwrap();
        let seen2 = t2.join().unwrap();

        assert!(seen1.is_none());
        assert!(seen2.is_none());
    }

    #[test]
    fn test_with_test_context_clears_after_use() {
        with_test_context(|| {
            label("temp", "value");
        });
        assert!(take_context().is_none());
    }

    #[test]
    fn test_tags_and_metadata_helpers() {
        let ctx = TestContext::new("meta", "module::meta");
        set_context(ctx);

        label("env", "staging");
        tags(&["smoke", "api"]);
        title("Custom Title");
        description("Markdown");
        description_html("<p>HTML</p>");
        test_case_id("TC-1");

        let ctx = take_context().unwrap();
        assert_eq!(ctx.result.name, "Custom Title");
        assert_eq!(ctx.result.description.as_deref(), Some("Markdown"));
        assert_eq!(ctx.result.description_html.as_deref(), Some("<p>HTML</p>"));
        assert_eq!(ctx.result.test_case_id.as_deref(), Some("TC-1"));
        assert!(ctx.result.labels.iter().any(|l| l.value == "staging"));
        assert!(ctx.result.labels.iter().any(|l| l.value == "smoke"));
        assert!(ctx.result.labels.iter().any(|l| l.value == "api"));
    }

    #[test]
    fn test_step_failure_records_message_and_rethrows() {
        let ctx = TestContext::new("step_fail", "module::step_fail");
        set_context(ctx);

        let result = std::panic::catch_unwind(|| {
            step("will panic", || panic!("boom step"));
        });
        assert!(result.is_err());

        let ctx = take_context().unwrap();
        assert_eq!(ctx.result.steps.len(), 1);
        let step = &ctx.result.steps[0];
        assert_eq!(step.status, Status::Failed);
        assert!(step
            .status_details
            .as_ref()
            .unwrap()
            .message
            .as_ref()
            .unwrap()
            .contains("boom step"));
    }

    #[test]
    fn test_finish_step_skipped_branch() {
        let mut ctx = TestContext::new("skip_step", "module::skip_step");
        ctx.start_step("inner");
        ctx.finish_step(
            Status::Skipped,
            Some("not run".into()),
            Some("trace".into()),
        );
        assert_eq!(ctx.result.steps[0].status, Status::Skipped);
        assert_eq!(ctx.result.steps[0].stage, crate::enums::Stage::Finished);
    }

    #[test]
    fn test_finish_step_broken_and_unknown_branches() {
        let mut ctx = TestContext::new("broken_step", "module::broken_step");
        ctx.start_step("broken");
        ctx.finish_step(Status::Broken, Some("oops".into()), None);
        assert_eq!(ctx.result.steps[0].status, Status::Broken);
        assert!(ctx.result.steps[0]
            .status_details
            .as_ref()
            .unwrap()
            .message
            .as_ref()
            .unwrap()
            .contains("oops"));

        ctx.start_step("unknown");
        ctx.finish_step(Status::Unknown, None, None);
        assert_eq!(ctx.result.steps[1].status, Status::Unknown);
        assert_eq!(ctx.result.steps[1].stage, crate::enums::Stage::Finished);
    }

    #[test]
    fn test_muted_sets_flag() {
        let ctx = TestContext::new("muted_test", "module::muted_test");
        set_context(ctx);
        muted();
        let ctx = take_context().unwrap();
        let details = ctx.result.status_details.unwrap();
        assert_eq!(details.muted, Some(true));
    }

    #[test]
    fn test_host_env_override_used_in_context_creation() {
        std::env::set_var("HOSTNAME", "test-host");
        let ctx = TestContext::new("hosted", "module::hosted");
        assert!(ctx
            .result
            .labels
            .iter()
            .any(|l| l.name == "host" && l.value == "test-host"));
    }

    #[test]
    fn test_add_parameter_struct_applies_to_steps() {
        let mut ctx = TestContext::new("params", "module::params");
        ctx.start_step("outer");
        ctx.add_parameter_struct(crate::model::Parameter::excluded("k", "v"));
        assert_eq!(ctx.step_stack[0].parameters.len(), 1);
        assert_eq!(ctx.step_stack[0].parameters[0].excluded, Some(true));
    }

    #[test]
    fn test_finish_writes_and_breaks_unfinished_steps() {
        let temp = tempfile::tempdir().unwrap();
        CONFIG.get_or_init(|| AllureConfig {
            results_dir: temp.path().to_string_lossy().to_string(),
            clean_results: true,
        });
        let mut ctx = TestContext::new("unclosed", "module::unclosed");
        ctx.start_step("still running");
        ctx.finish(Status::Passed, None, None);
        assert_eq!(ctx.result.steps[0].status, Status::Broken);
        assert!(ctx.result.steps[0]
            .status_details
            .as_ref()
            .unwrap()
            .message
            .as_ref()
            .unwrap()
            .contains("Step not completed"));
    }

    #[test]
    fn test_finish_handles_broken_status_with_details() {
        let temp = tempfile::tempdir().unwrap();
        CONFIG.get_or_init(|| AllureConfig {
            results_dir: temp.path().to_string_lossy().to_string(),
            clean_results: true,
        });
        let mut ctx = TestContext::new("broken_test", "module::broken_test");
        ctx.finish(Status::Broken, Some("fail".into()), Some("trace".into()));
        assert_eq!(ctx.result.status, Status::Broken);
        let details = ctx.result.status_details.as_ref().unwrap();
        assert_eq!(details.message.as_deref(), Some("fail"));
        assert_eq!(details.trace.as_deref(), Some("trace"));
    }

    #[test]
    fn test_context_creation_uses_hostname_when_env_missing() {
        // Temporarily remove HOSTNAME to exercise hostname crate path
        let original = std::env::var("HOSTNAME").ok();
        std::env::remove_var("HOSTNAME");
        let ctx = TestContext::new("host", "module::host");
        if let Some(orig) = original {
            std::env::set_var("HOSTNAME", orig);
        }
        assert!(ctx.result.labels.iter().any(|l| l.name == "host"));
    }
}