allure-rust-commons 1.3.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
//! Low-level lifecycle owner for mutable Allure test state.

use std::{
    cell::RefCell,
    cmp,
    collections::HashMap,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc, Mutex,
    },
    time::{SystemTime, UNIX_EPOCH},
};

use crate::{
    config,
    http_exchange::{HttpExchange, HTTP_EXCHANGE_ATTACHMENT_MIME, HTTP_EXCHANGE_ATTACHMENT_NAME},
    md5::md5_hex,
    model::{
        Attachment, FixtureResult, GlobalAttachment, GlobalError, Globals, Label, Link, Parameter,
        ParameterMode, Stage, Status, StatusDetails, StepResult, TestResult, TestResultContainer,
    },
    writer::FileSystemResultsWriter,
};

thread_local! {
    static ACTIVE_TEST_ROOT: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    static ACTIVE_SCOPE_ROOT: RefCell<Option<String>> = const { RefCell::new(None) };
}

static ID_COUNTER: AtomicU64 = AtomicU64::new(1);

fn now_millis() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or_default()
}

fn next_id() -> String {
    format!(
        "{}-{}",
        now_millis(),
        ID_COUNTER.fetch_add(1, Ordering::Relaxed)
    )
}

fn round_millis(value: f64) -> i64 {
    value.round() as i64
}

fn normalize_times(
    start: Option<i64>,
    stop: Option<i64>,
    duration: Option<f64>,
    fallback_stop: i64,
) -> (Option<i64>, Option<i64>) {
    let rounded_duration = duration.map(round_millis).map(|value| cmp::max(value, 0));

    let (start, stop) = match (start, stop, rounded_duration) {
        (Some(start), Some(stop), _) => (start, cmp::max(stop, start)),
        (Some(start), None, Some(duration)) => (start, start.saturating_add(duration)),
        (None, Some(stop), Some(duration)) => (stop.saturating_sub(duration), stop),
        (Some(start), None, None) => (start, cmp::max(fallback_stop, start)),
        (None, Some(stop), None) => (stop, stop),
        (None, None, Some(duration)) => {
            let stop = fallback_stop;
            (stop.saturating_sub(duration), stop)
        }
        (None, None, None) => (fallback_stop, fallback_stop),
    };

    (Some(start), Some(stop))
}

fn normalize_step_result(step: &mut StepResult, fallback_stop: i64) {
    (step.start, step.stop) = normalize_times(step.start, step.stop, None, fallback_stop);
    for nested in &mut step.steps {
        normalize_step_result(nested, step.stop.unwrap_or(fallback_stop));
    }
}

fn normalize_fixture_result(fixture: &mut FixtureResult, fallback_stop: i64) {
    (fixture.start, fixture.stop) =
        normalize_times(fixture.start, fixture.stop, None, fallback_stop);
    let fixture_stop = fixture.stop.unwrap_or(fallback_stop);
    for step in &mut fixture.steps {
        normalize_step_result(step, fixture_stop);
    }
}

fn normalize_test_result(test: &mut TestResult, fallback_stop: i64) {
    (test.start, test.stop) = normalize_times(test.start, test.stop, None, fallback_stop);
    let test_stop = test.stop.unwrap_or(fallback_stop);
    for step in &mut test.steps {
        normalize_step_result(step, test_stop);
    }
}

fn normalize_container_times(container: &mut TestResultContainer, fallback_stop: i64) {
    (container.start, container.stop) =
        normalize_times(container.start, container.stop, None, fallback_stop);
    let container_stop = container.stop.unwrap_or(fallback_stop);
    for fixture in &mut container.befores {
        normalize_fixture_result(fixture, container_stop);
    }
    for fixture in &mut container.afters {
        normalize_fixture_result(fixture, container_stop);
    }
}

fn derive_test_case_id(test: &TestResult) -> Option<String> {
    test.test_case_id
        .clone()
        .or_else(|| test.full_name.clone().map(|full_name| md5_hex(&full_name)))
}

fn derive_history_id(test: &TestResult) -> Option<String> {
    let base = test
        .test_case_id
        .as_ref()
        .or(test.full_name.as_ref())
        .or(Some(&test.name))?;

    let mut parameters = test
        .parameters
        .iter()
        .filter(|parameter| parameter.excluded != Some(true))
        .map(|parameter| format!("{}:{}", parameter.name, parameter.value))
        .collect::<Vec<_>>();
    parameters.sort();
    let parameter_hash = md5_hex(&parameters.join(","));

    Some(md5_hex(&format!("{base}:{parameter_hash}")))
}

/// Factory for lifecycle instances that share a results writer.
#[derive(Clone)]
pub struct AllureRuntime {
    writer: Arc<FileSystemResultsWriter>,
}

impl AllureRuntime {
    /// Creates a runtime backed by the given filesystem writer.
    pub fn new(writer: FileSystemResultsWriter) -> Self {
        Self {
            writer: Arc::new(writer),
        }
    }

    /// Creates an independent lifecycle owner that writes through this runtime.
    pub fn lifecycle(&self) -> AllureLifecycle {
        AllureLifecycle {
            writer: Arc::clone(&self.writer),
            state: Arc::new(Mutex::new(LifecycleState::default())),
        }
    }
}

/// Owns mutable in-progress Allure lifecycle state.
#[derive(Clone)]
pub struct AllureLifecycle {
    writer: Arc<FileSystemResultsWriter>,
    state: Arc<Mutex<LifecycleState>>,
}

/// Parameters used to start a test case.
#[derive(Debug, Clone, Default)]
pub struct StartTestCaseParams {
    /// Optional explicit test UUID.
    pub uuid: Option<String>,
    /// Test display name.
    pub name: String,
    /// Stable fully qualified test name.
    pub full_name: Option<String>,
    /// Optional explicit history identifier.
    pub history_id: Option<String>,
    /// Optional explicit logical test case identifier.
    pub test_case_id: Option<String>,
    /// Markdown description.
    pub description: Option<String>,
    /// HTML description.
    pub description_html: Option<String>,
    /// Initial status.
    pub status: Option<Status>,
    /// Initial status details.
    pub status_details: Option<StatusDetails>,
    /// Initial lifecycle stage.
    pub stage: Option<Stage>,
    /// Initial labels.
    pub labels: Vec<Label>,
    /// Initial links.
    pub links: Vec<Link>,
    /// Initial parameters.
    pub parameters: Vec<Parameter>,
    /// Initial steps.
    pub steps: Vec<StepResult>,
    /// Initial attachments.
    pub attachments: Vec<Attachment>,
    /// Optional title path.
    pub title_path: Option<Vec<String>>,
    /// Optional start timestamp in milliseconds since the Unix epoch.
    pub start: Option<i64>,
    /// Optional stop timestamp in milliseconds since the Unix epoch.
    pub stop: Option<i64>,
}

impl StartTestCaseParams {
    /// Creates start parameters with a display name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }

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

impl From<String> for StartTestCaseParams {
    fn from(name: String) -> Self {
        Self {
            name,
            ..Default::default()
        }
    }
}

impl From<&str> for StartTestCaseParams {
    fn from(name: &str) -> Self {
        Self::from(name.to_string())
    }
}

#[derive(Default)]
struct LifecycleState {
    tests: HashMap<String, TestState>,
    scopes: HashMap<String, ScopeState>,
}

struct TestState {
    test: TestResult,
    step_stack: Vec<RunningStep>,
    linked_scopes: Vec<String>,
}

struct ScopeState {
    container: TestResultContainer,
    running_fixture: Option<RunningFixture>,
}

struct RunningFixture {
    kind: FixtureKind,
    fixture: FixtureResult,
    step_stack: Vec<RunningStep>,
}

enum FixtureKind {
    Before,
    After,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RunningStepKind {
    Step,
    Stage,
}

struct RunningStep {
    result: StepResult,
    kind: RunningStepKind,
}

impl RunningStep {
    fn new(name: impl Into<String>, timestamp: i64, kind: RunningStepKind) -> Self {
        Self {
            result: StepResult {
                name: name.into(),
                stage: Some(Stage::Running),
                start: Some(timestamp),
                ..Default::default()
            },
            kind,
        }
    }
}

impl std::ops::Deref for RunningStep {
    type Target = StepResult;

    fn deref(&self) -> &Self::Target {
        &self.result
    }
}

impl std::ops::DerefMut for RunningStep {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.result
    }
}

impl AllureLifecycle {
    /// Starts a test case and makes it current on this thread.
    pub fn start_test_case(&self, params: impl Into<StartTestCaseParams>) {
        let params = params.into();
        let name = params.name;
        let uuid = params.uuid.unwrap_or_else(next_id);
        let full_name = params.full_name.or_else(|| Some(name.clone()));
        let mut labels = config::global_labels_from_environment()
            .into_iter()
            .map(|(name, value)| Label { name, value })
            .collect::<Vec<_>>();
        labels.extend(params.labels);

        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        lock.tests.insert(
            uuid.clone(),
            TestState {
                test: TestResult {
                    uuid: uuid.clone(),
                    name,
                    full_name,
                    history_id: params.history_id,
                    test_case_id: params.test_case_id,
                    description: params.description,
                    description_html: params.description_html,
                    status: params.status,
                    status_details: params.status_details,
                    stage: params.stage.or(Some(Stage::Running)),
                    labels,
                    links: params.links,
                    parameters: params.parameters,
                    steps: params.steps,
                    attachments: params.attachments,
                    title_path: params.title_path,
                    start: params.start.or_else(|| Some(now_millis())),
                    stop: params.stop,
                },
                step_stack: Vec::new(),
                linked_scopes: Vec::new(),
            },
        );
        ACTIVE_TEST_ROOT.with(|cell| cell.borrow_mut().push(uuid));
    }

    /// Returns the UUID of the current test on this thread.
    pub fn current_test_uuid(&self) -> Option<String> {
        ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned())
    }

    /// Stops and writes the current test case.
    pub fn stop_test_case(&self, status: Status, details: Option<StatusDetails>) {
        let Some(test_uuid) = ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned()) else {
            return;
        };

        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        if let Some(mut state) = lock.tests.remove(&test_uuid) {
            finalize_steps(
                &mut state.step_stack,
                &mut state.test.steps,
                status.clone(),
                details.clone(),
            );
            merge_before_scope_metadata(&lock, &mut state.test, &state.linked_scopes);

            state.test.status = Some(status);
            state.test.status_details = details;
            state.test.stage = Some(Stage::Finished);
            let fallback_stop = now_millis();
            if state.test.test_case_id.is_none() {
                state.test.test_case_id = derive_test_case_id(&state.test);
            }
            if state.test.history_id.is_none() {
                state.test.history_id = derive_history_id(&state.test);
            }
            normalize_test_result(&mut state.test, fallback_stop);
            let _ = self.writer.write_result(&state.test);
        }

        ACTIVE_TEST_ROOT.with(|cell| {
            let mut roots = cell.borrow_mut();
            if roots.last().is_some_and(|uuid| uuid == &test_uuid) {
                roots.pop();
            } else {
                roots.retain(|uuid| uuid != &test_uuid);
            }
        });
    }

    /// Mutates the current test result.
    pub fn update_test_case<F>(&self, update: F)
    where
        F: FnOnce(&mut TestResult),
    {
        let Some(test_uuid) = ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned()) else {
            return;
        };
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        if let Some(state) = lock.tests.get_mut(&test_uuid) {
            update(&mut state.test);
        }
    }

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

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

    /// Adds a label to the current test.
    pub fn add_label(&self, name: impl Into<String>, value: impl Into<String>) {
        let name = name.into();
        let value = value.into();
        self.update_test_case(|test| {
            if matches!(name.as_str(), "parentSuite" | "suite" | "subSuite") {
                test.labels.retain(|label| label.name != name);
            }
            test.labels.push(Label {
                name: name.clone(),
                value: value.clone(),
            });
        });
    }

    /// Adds a link to the current test.
    pub fn add_link(
        &self,
        url: impl Into<String>,
        name: Option<String>,
        link_type: Option<String>,
    ) {
        let url = url.into();
        self.update_test_case(|test| {
            test.links.push(Link {
                name,
                url,
                link_type,
            })
        });
    }

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

    /// Adds a parameter with identity and display options to the current test.
    pub fn add_parameter_with_options(
        &self,
        name: impl Into<String>,
        value: impl Into<String>,
        excluded: Option<bool>,
        mode: Option<ParameterMode>,
    ) {
        let name = name.into();
        let value = value.into();
        self.update_test_case(|test| {
            test.parameters.push(Parameter {
                name,
                value,
                excluded,
                mode,
            })
        });
    }

    /// Starts a fixture/test container scope.
    pub fn start_scope(&self, name: Option<String>) -> String {
        let uuid = next_id();
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        lock.scopes.insert(
            uuid.clone(),
            ScopeState {
                container: TestResultContainer {
                    uuid: uuid.clone(),
                    name,
                    start: Some(now_millis()),
                    ..Default::default()
                },
                running_fixture: None,
            },
        );
        uuid
    }

    /// Links an existing scope to an existing test.
    pub fn link_scope_to_test(&self, scope_uuid: &str, test_uuid: &str) {
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        let has_scope = lock.scopes.contains_key(scope_uuid);
        let has_test = lock.tests.contains_key(test_uuid);
        if !(has_scope && has_test) {
            return;
        }

        if let Some(scope) = lock.scopes.get_mut(scope_uuid) {
            if !scope
                .container
                .children
                .iter()
                .any(|child| child == test_uuid)
            {
                scope.container.children.push(test_uuid.to_string());
            }
        }
        if let Some(test) = lock.tests.get_mut(test_uuid) {
            if !test.linked_scopes.iter().any(|scope| scope == scope_uuid) {
                test.linked_scopes.push(scope_uuid.to_string());
            }
        }
    }

    /// Stops a scope and finalizes any running fixture inside it.
    pub fn stop_scope(&self, scope_uuid: &str) {
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        if let Some(scope) = lock.scopes.get_mut(scope_uuid) {
            finish_running_fixture(scope);
            normalize_container_times(&mut scope.container, now_millis());
        }
        ACTIVE_SCOPE_ROOT.with(|cell| {
            if cell.borrow().as_deref() == Some(scope_uuid) {
                *cell.borrow_mut() = None;
            }
        });
    }

    /// Writes and removes a stopped scope.
    pub fn write_scope(&self, scope_uuid: &str) {
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        if let Some(scope) = lock.scopes.remove(scope_uuid) {
            let _ = self.writer.write_container(&scope.container);
        }
    }

    /// Starts a before fixture inside a scope.
    pub fn start_before_fixture(&self, scope_uuid: &str, name: impl Into<String>) {
        self.start_fixture(scope_uuid, name.into(), FixtureKind::Before);
    }

    /// Stops the running before fixture inside a scope.
    pub fn stop_before_fixture(
        &self,
        scope_uuid: &str,
        status: Status,
        details: Option<StatusDetails>,
    ) {
        self.stop_fixture(scope_uuid, FixtureKind::Before, status, details);
    }

    /// Starts an after fixture inside a scope.
    pub fn start_after_fixture(&self, scope_uuid: &str, name: impl Into<String>) {
        self.start_fixture(scope_uuid, name.into(), FixtureKind::After);
    }

    /// Stops the running after fixture inside a scope.
    pub fn stop_after_fixture(
        &self,
        scope_uuid: &str,
        status: Status,
        details: Option<StatusDetails>,
    ) {
        self.stop_fixture(scope_uuid, FixtureKind::After, status, details);
    }

    /// Adds an attachment to the exact current owner.
    pub fn add_attachment(
        &self,
        name: impl Into<String>,
        content_type: impl Into<String>,
        bytes: &[u8],
    ) {
        let name = name.into();
        let content_type = content_type.into();
        let id = next_id();
        if let Ok((source, _)) =
            self.writer
                .write_attachment_auto(&id, Some(&name), Some(&content_type), bytes)
        {
            let attachment = Attachment {
                name,
                source,
                content_type,
            };
            let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
            if let Some(scope_uuid) = ACTIVE_SCOPE_ROOT.with(|cell| cell.borrow().clone()) {
                if let Some(scope) = lock.scopes.get_mut(&scope_uuid) {
                    if let Some(fixture) = scope.running_fixture.as_mut() {
                        if let Some(step) = fixture.step_stack.last_mut() {
                            step.attachments.push(attachment);
                        } else {
                            fixture.fixture.attachments.push(attachment);
                        }
                        return;
                    }
                }
            }

            if let Some(test_uuid) = ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned()) {
                if let Some(test_state) = lock.tests.get_mut(&test_uuid) {
                    if let Some(step) = test_state.step_stack.last_mut() {
                        step.attachments.push(attachment);
                    } else {
                        test_state.test.attachments.push(attachment);
                    }
                }
            }
        }
    }

    /// Adds an HTTP exchange attachment to the exact current owner.
    pub fn add_http_exchange(&self, exchange: HttpExchange) {
        self.add_http_exchange_named(HTTP_EXCHANGE_ATTACHMENT_NAME, exchange);
    }

    /// Adds a named HTTP exchange attachment to the exact current owner.
    pub fn add_http_exchange_named(&self, name: impl Into<String>, exchange: HttpExchange) {
        if let Ok(bytes) = serde_json::to_vec(&exchange) {
            self.add_attachment(name, HTTP_EXCHANGE_ATTACHMENT_MIME, &bytes);
        }
    }

    /// Writes a run-level attachment.
    pub fn add_global_attachment(
        &self,
        name: impl Into<String>,
        content_type: impl Into<String>,
        bytes: &[u8],
    ) -> std::io::Result<()> {
        let name = name.into();
        let content_type = content_type.into();
        let (source, _) = self.writer.write_attachment_auto(
            &next_id(),
            Some(&name),
            Some(&content_type),
            bytes,
        )?;
        self.writer
            .write_globals_typed(&Globals {
                attachments: vec![GlobalAttachment {
                    name,
                    source,
                    content_type,
                }],
                errors: Vec::new(),
            })
            .map(|_| ())
    }

    /// Writes a run-level error.
    pub fn add_global_error(
        &self,
        message: impl Into<String>,
        trace: Option<String>,
    ) -> std::io::Result<()> {
        self.writer
            .write_globals_typed(&Globals {
                attachments: Vec::new(),
                errors: vec![GlobalError {
                    message: message.into(),
                    trace,
                }],
            })
            .map(|_| ())
    }

    /// Starts a step under the current owner.
    pub fn start_step(&self, name: impl Into<String>) {
        self.start_step_at(name, None);
    }

    /// Starts a step under the current owner at an optional timestamp.
    pub fn start_step_at(&self, name: impl Into<String>, timestamp: Option<i64>) -> i64 {
        let timestamp = timestamp.unwrap_or_else(now_millis);
        let step = RunningStep::new(name, timestamp, RunningStepKind::Step);
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");

        if let Some(scope_uuid) = ACTIVE_SCOPE_ROOT.with(|cell| cell.borrow().clone()) {
            if let Some(scope) = lock.scopes.get_mut(&scope_uuid) {
                if let Some(fixture) = scope.running_fixture.as_mut() {
                    fixture.step_stack.push(step);
                    return timestamp;
                }
            }
        }

        if let Some(test_uuid) = ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned()) {
            if let Some(test_state) = lock.tests.get_mut(&test_uuid) {
                test_state.step_stack.push(step);
            }
        }

        timestamp
    }

    /// Starts a semantic stage under the current owner.
    pub fn start_stage(&self, name: impl Into<String>) {
        self.start_stage_at(name, None);
    }

    /// Starts a semantic stage under the current owner at an optional timestamp.
    pub fn start_stage_at(&self, name: impl Into<String>, timestamp: Option<i64>) -> i64 {
        let timestamp = timestamp.unwrap_or_else(now_millis);
        let name = name.into();
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");

        if let Some(scope_uuid) = ACTIVE_SCOPE_ROOT.with(|cell| cell.borrow().clone()) {
            if let Some(scope) = lock.scopes.get_mut(&scope_uuid) {
                if let Some(fixture) = scope.running_fixture.as_mut() {
                    start_stage_in_stack(
                        &mut fixture.step_stack,
                        &mut fixture.fixture.steps,
                        name,
                        timestamp,
                    );
                    return timestamp;
                }
            }
        }

        if let Some(test_uuid) = ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned()) {
            if let Some(test_state) = lock.tests.get_mut(&test_uuid) {
                start_stage_in_stack(
                    &mut test_state.step_stack,
                    &mut test_state.test.steps,
                    name,
                    timestamp,
                );
            }
        }

        timestamp
    }

    /// Stops the current step.
    pub fn stop_step(&self, status: Status, details: Option<StatusDetails>) {
        self.stop_step_at(None, status, details);
    }

    /// Stops the current step at an optional timestamp.
    pub fn stop_step_at(
        &self,
        timestamp: Option<i64>,
        status: Status,
        details: Option<StatusDetails>,
    ) {
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");

        if let Some(scope_uuid) = ACTIVE_SCOPE_ROOT.with(|cell| cell.borrow().clone()) {
            if let Some(scope) = lock.scopes.get_mut(&scope_uuid) {
                if let Some(fixture) = scope.running_fixture.as_mut() {
                    stop_one_step(
                        &mut fixture.step_stack,
                        &mut fixture.fixture.steps,
                        timestamp,
                        status,
                        details,
                    );
                    return;
                }
            }
        }

        if let Some(test_uuid) = ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned()) {
            if let Some(test_state) = lock.tests.get_mut(&test_uuid) {
                stop_one_step(
                    &mut test_state.step_stack,
                    &mut test_state.test.steps,
                    timestamp,
                    status,
                    details,
                );
            }
        }
    }

    /// Renames the current step.
    pub fn set_current_step_display_name(&self, name: impl Into<String>) {
        let name = name.into();
        self.update_current_step(
            move |step| step.name = name,
            "attempted to rename current step, but no step is active",
        );
    }

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

    /// Adds a parameter with identity and display options to the current step.
    pub fn add_current_step_parameter_with_options(
        &self,
        name: impl Into<String>,
        value: impl Into<String>,
        excluded: Option<bool>,
        mode: Option<ParameterMode>,
    ) {
        let parameter = Parameter {
            name: name.into(),
            value: value.into(),
            excluded,
            mode,
        };
        self.update_current_step(
            move |step| step.parameters.push(parameter),
            "attempted to add a parameter to the current step, but no step is active",
        );
    }

    fn start_fixture(&self, scope_uuid: &str, name: String, kind: FixtureKind) {
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        if let Some(scope) = lock.scopes.get_mut(scope_uuid) {
            finish_running_fixture(scope);
            scope.running_fixture = Some(RunningFixture {
                kind,
                fixture: FixtureResult {
                    name,
                    stage: Some(Stage::Running),
                    start: Some(now_millis()),
                    ..Default::default()
                },
                step_stack: Vec::new(),
            });
            ACTIVE_SCOPE_ROOT.with(|cell| *cell.borrow_mut() = Some(scope_uuid.to_string()));
        }
    }

    pub(crate) fn update_current_step<F>(&self, update: F, missing_step_message: &str)
    where
        F: FnOnce(&mut StepResult),
    {
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");

        if let Some(scope_uuid) = ACTIVE_SCOPE_ROOT.with(|cell| cell.borrow().clone()) {
            if let Some(scope) = lock.scopes.get_mut(&scope_uuid) {
                if let Some(fixture) = scope.running_fixture.as_mut() {
                    if let Some(step) = fixture.step_stack.last_mut() {
                        update(step);
                        return;
                    }
                }
            }
        }

        if let Some(test_uuid) = ACTIVE_TEST_ROOT.with(|cell| cell.borrow().last().cloned()) {
            if let Some(test_state) = lock.tests.get_mut(&test_uuid) {
                if let Some(step) = test_state.step_stack.last_mut() {
                    update(step);
                    return;
                }
            }
        }

        eprintln!("[allure-rust] {missing_step_message}");
    }

    fn stop_fixture(
        &self,
        scope_uuid: &str,
        expected_kind: FixtureKind,
        status: Status,
        details: Option<StatusDetails>,
    ) {
        let mut lock = self.state.lock().expect("poisoned allure lifecycle mutex");
        if let Some(scope) = lock.scopes.get_mut(scope_uuid) {
            if let Some(mut fixture) = scope.running_fixture.take() {
                if !matches!(
                    (&fixture.kind, &expected_kind),
                    (FixtureKind::Before, FixtureKind::Before)
                        | (FixtureKind::After, FixtureKind::After)
                ) {
                    scope.running_fixture = Some(fixture);
                    return;
                }

                finalize_steps(
                    &mut fixture.step_stack,
                    &mut fixture.fixture.steps,
                    status.clone(),
                    details.clone(),
                );
                fixture.fixture.status = Some(status);
                fixture.fixture.status_details = details;
                fixture.fixture.stage = Some(Stage::Finished);
                normalize_fixture_result(&mut fixture.fixture, now_millis());
                match fixture.kind {
                    FixtureKind::Before => scope.container.befores.push(fixture.fixture),
                    FixtureKind::After => scope.container.afters.push(fixture.fixture),
                }
            }
        }
        ACTIVE_SCOPE_ROOT.with(|cell| {
            if cell.borrow().as_deref() == Some(scope_uuid) {
                *cell.borrow_mut() = None;
            }
        });
    }
}

fn stop_one_step(
    stack: &mut Vec<RunningStep>,
    root_steps: &mut Vec<StepResult>,
    timestamp: Option<i64>,
    status: Status,
    details: Option<StatusDetails>,
) {
    close_active_stages(
        stack,
        root_steps,
        timestamp,
        status.clone(),
        details.clone(),
    );
    if stack.is_empty() {
        return;
    }
    stop_top_step(stack, root_steps, timestamp, status, details);
}

fn start_stage_in_stack(
    stack: &mut Vec<RunningStep>,
    root_steps: &mut Vec<StepResult>,
    name: impl Into<String>,
    timestamp: i64,
) {
    if matches!(
        stack.last().map(|step| step.kind),
        Some(RunningStepKind::Stage)
    ) {
        stop_top_step(stack, root_steps, Some(timestamp), Status::Passed, None);
    }
    stack.push(RunningStep::new(name, timestamp, RunningStepKind::Stage));
}

fn close_active_stages(
    stack: &mut Vec<RunningStep>,
    root_steps: &mut Vec<StepResult>,
    timestamp: Option<i64>,
    status: Status,
    details: Option<StatusDetails>,
) {
    while matches!(
        stack.last().map(|step| step.kind),
        Some(RunningStepKind::Stage)
    ) {
        stop_top_step(
            stack,
            root_steps,
            timestamp,
            status.clone(),
            details.clone(),
        );
    }
}

fn stop_top_step(
    stack: &mut Vec<RunningStep>,
    root_steps: &mut Vec<StepResult>,
    timestamp: Option<i64>,
    status: Status,
    details: Option<StatusDetails>,
) {
    if let Some(mut step) = stack.pop() {
        finish_step_result(&mut step.result, timestamp, status, details);
        if let Some(parent) = stack.last_mut() {
            parent.steps.push(step.result);
        } else {
            root_steps.push(step.result);
        }
    }
}

fn finish_step_result(
    step: &mut StepResult,
    timestamp: Option<i64>,
    status: Status,
    details: Option<StatusDetails>,
) {
    step.status.get_or_insert(status);
    if step.status_details.is_none() {
        step.status_details = details;
    }
    step.stage = Some(Stage::Finished);
    normalize_step_result(step, timestamp.unwrap_or_else(now_millis));
    if let Some(stop) = timestamp {
        step.stop = Some(stop);
        if step.start.is_none() {
            step.start = Some(stop);
        }
    }
}

fn finalize_steps(
    stack: &mut Vec<RunningStep>,
    root_steps: &mut Vec<StepResult>,
    context_status: Status,
    context_details: Option<StatusDetails>,
) {
    while let Some(mut step) = stack.pop() {
        let status = match step.kind {
            RunningStepKind::Step => Status::Broken,
            RunningStepKind::Stage => context_status.clone(),
        };
        let details = match step.kind {
            RunningStepKind::Step => None,
            RunningStepKind::Stage => context_details.clone(),
        };
        finish_step_result(&mut step.result, None, status, details);
        if let Some(parent) = stack.last_mut() {
            parent.steps.push(step.result);
        } else {
            root_steps.push(step.result);
        }
    }
}

fn finish_running_fixture(scope: &mut ScopeState) {
    if let Some(mut fixture) = scope.running_fixture.take() {
        finalize_steps(
            &mut fixture.step_stack,
            &mut fixture.fixture.steps,
            Status::Broken,
            None,
        );
        fixture.fixture.status.get_or_insert(Status::Broken);
        fixture.fixture.stage = Some(Stage::Finished);
        normalize_fixture_result(&mut fixture.fixture, now_millis());
        match fixture.kind {
            FixtureKind::Before => scope.container.befores.push(fixture.fixture),
            FixtureKind::After => scope.container.afters.push(fixture.fixture),
        }
    }
}

fn merge_before_scope_metadata(
    lock: &LifecycleState,
    test: &mut TestResult,
    linked_scopes: &[String],
) {
    for scope_uuid in linked_scopes {
        if let Some(scope) = lock.scopes.get(scope_uuid) {
            for link in &scope.container.links {
                test.links.push(link.clone());
            }
            for fixture in &scope.container.befores {
                for parameter in &fixture.parameters {
                    test.parameters.push(parameter.clone());
                }
            }
        }
    }
}

#[cfg(test)]
#[path = "lifecycle_tests.rs"]
mod lifecycle_tests;