test_output_directory/
lib.rs

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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

mod macros;
pub mod testing;
mod v1;

use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::hash_map::Iter;
use std::collections::HashMap;
use std::fs::{DirBuilder, File};
use std::io::Error;
use std::path::{Path, PathBuf};
use test_list::TestTag;

/// Filename of the top level summary json.
pub const RUN_SUMMARY_NAME: &str = "run_summary.json";
pub const RUN_NAME: &str = "run";

enumerable_enum! {
    /// Schema version.
    #[derive(PartialEq, Eq, Debug, Clone, Copy, Hash)]
    SchemaVersion {
        V1,
    }
}

enumerable_enum! {
    /// A serializable version of a test outcome.
    #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Copy)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    Outcome {
        NotStarted,
        Passed,
        Failed,
        Inconclusive,
        Timedout,
        Error,
        Skipped,
    }
}

enumerable_enum! {
    /// Types of artifacts known to the test framework.
    #[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Copy, Hash)]
    #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
    ArtifactType {
        Syslog,
        /// Unexpected high severity logs that caused a test to fail.
        RestrictedLog,
        Stdout,
        Stderr,
        /// A directory containing custom artifacts produced by a component in the test.
        Custom,
        /// A human readable report generated by the test framework.
        Report,
        /// Debug data. For example, profraw or symbolizer output.
        Debug,
    }
}

/// A subdirectory of an output directory that contains artifacts for a test run,
/// test suite, or test case.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct ArtifactSubDirectory {
    version: SchemaVersion,
    root: PathBuf,
    artifacts: HashMap<PathBuf, ArtifactMetadata>,
}

/// Contains result information common to all results. It's useful to store
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct CommonResult {
    pub name: String,
    pub artifact_dir: ArtifactSubDirectory,
    pub outcome: MaybeUnknown<Outcome>,
    /// Approximate start time, as milliseconds since the epoch.
    pub start_time: Option<u64>,
    pub duration_milliseconds: Option<u64>,
}

/// A serializable test run result.
/// This contains overall results and artifacts scoped to a test run, and
/// a list of filenames for finding serialized suite results.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct TestRunResult<'a> {
    pub common: Cow<'a, CommonResult>,
    pub suites: Vec<SuiteResult<'a>>,
}

/// A serializable suite run result.
/// Contains overall results and artifacts scoped to a suite run, and
/// results and artifacts scoped to any test run within it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SuiteResult<'a> {
    pub common: Cow<'a, CommonResult>,
    pub cases: Vec<TestCaseResult<'a>>,
    pub tags: Cow<'a, Vec<TestTag>>,
}

/// A serializable test case result.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct TestCaseResult<'a> {
    pub common: Cow<'a, CommonResult>,
}

impl TestRunResult<'static> {
    pub fn from_dir(root: &Path) -> Result<Self, Error> {
        v1::parse_from_directory(root)
    }
}

/// Metadata associated with an artifact.
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Hash)]
pub struct ArtifactMetadata {
    /// The type of the artifact.
    pub artifact_type: MaybeUnknown<ArtifactType>,
    /// Moniker of the component which produced the artifact, if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub component_moniker: Option<String>,
}

#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Hash, Clone)]
#[serde(untagged)]
pub enum MaybeUnknown<T> {
    Known(T),
    Unknown(String),
}

impl<T> From<T> for MaybeUnknown<T> {
    fn from(other: T) -> Self {
        Self::Known(other)
    }
}

impl From<ArtifactType> for ArtifactMetadata {
    fn from(other: ArtifactType) -> Self {
        Self { artifact_type: MaybeUnknown::Known(other), component_moniker: None }
    }
}

/// A helper for accumulating results in an output directory.
///
/// |OutputDirectoryBuilder| handles details specific to the format of the test output
/// format, such as the locations of summaries and artifacts, while allowing the caller to
/// accumulate results separately. A typical usecase might look like this:
/// ```rust
/// let output_directory = OutputDirectoryBuilder::new("/path", SchemaVersion::V1)?;
/// let mut run_result = TestRunResult {
///     common: Cow::Owned(CommonResult{
///         name: "run".to_string(),
///         artifact_dir: output_directory.new_artifact_dir("run-artifacts")?,
///         outcome: Outcome::Inconclusive.into(),
///         start_time: None,
///         duration_milliseconds: None,
///     }),
///     suites: vec![],
/// };
///
/// // accumulate results in run_result over time... then save the summary.
/// output_directory.save_summary(&run_result)?;
/// ```
pub struct OutputDirectoryBuilder {
    version: SchemaVersion,
    root: PathBuf,
    /// Creation instant exists purely to make pseudo random directory names to discourage parsing
    /// methods that rely on unstable directory names and could be broken when internal
    /// implementation changes.
    creation_instant: std::time::Instant,
}

impl OutputDirectoryBuilder {
    /// Register a directory for use as an output directory using version |version|.
    pub fn new(dir: impl Into<PathBuf>, version: SchemaVersion) -> Result<Self, Error> {
        let root = dir.into();
        ensure_directory_exists(&root)?;
        Ok(Self { version, root, creation_instant: std::time::Instant::now() })
    }

    /// Create a new artifact subdirectory.
    ///
    /// The new |ArtifactSubDirectory| should be referenced from either the test run, suite, or
    /// case when a summary is saved in this OutputDirectoryBuilder with |save_summary|.
    pub fn new_artifact_dir(&self) -> Result<ArtifactSubDirectory, Error> {
        match self.version {
            SchemaVersion::V1 => {
                let subdir_root =
                    self.root.join(format!("{:?}", self.creation_instant.elapsed().as_nanos()));
                Ok(ArtifactSubDirectory {
                    version: self.version,
                    root: subdir_root,
                    artifacts: HashMap::new(),
                })
            }
        }
    }

    /// Save a summary of the test results in the directory.
    pub fn save_summary<'a, 'b>(&'a self, result: &'a TestRunResult<'b>) -> Result<(), Error> {
        match self.version {
            SchemaVersion::V1 => v1::save_summary(self.root.as_path(), result),
        }
    }

    /// Get the path to the root directory.
    pub fn path(&self) -> &Path {
        self.root.as_path()
    }
}

impl ArtifactSubDirectory {
    /// Create a new file based artifact.
    pub fn new_artifact(
        &mut self,
        metadata: impl Into<ArtifactMetadata>,
        name: impl AsRef<Path>,
    ) -> Result<File, Error> {
        ensure_directory_exists(self.root.as_path())?;
        match self.version {
            SchemaVersion::V1 => {
                // todo validate path
                self.artifacts.insert(name.as_ref().to_path_buf(), metadata.into());
                File::create(self.root.join(name))
            }
        }
    }

    /// Create a new directory based artifact.
    pub fn new_directory_artifact(
        &mut self,
        metadata: impl Into<ArtifactMetadata>,
        name: impl AsRef<Path>,
    ) -> Result<PathBuf, Error> {
        match self.version {
            SchemaVersion::V1 => {
                // todo validate path
                let subdir = self.root.join(name.as_ref());
                ensure_directory_exists(subdir.as_path())?;
                self.artifacts.insert(name.as_ref().to_path_buf(), metadata.into());
                Ok(subdir)
            }
        }
    }

    /// Get the absolute path of the artifact at |name|, if present.
    pub fn path_to_artifact(&self, name: impl AsRef<Path>) -> Option<PathBuf> {
        match self.version {
            SchemaVersion::V1 => match self.artifacts.contains_key(name.as_ref()) {
                true => Some(self.root.join(name.as_ref())),
                false => None,
            },
        }
    }

    /// Return a list of paths of artifacts in the directory, relative to the root of the artifact
    /// directory.
    pub fn contents(&self) -> Vec<PathBuf> {
        self.artifacts.keys().cloned().collect()
    }

    /// Return an iterator over the artifacts in the directory.
    ///
    /// Includes paths relative to the root of the artifact directory and the associated metadata.
    pub fn artifact_iter(&self) -> Iter<'_, PathBuf, ArtifactMetadata> {
        self.artifacts.iter()
    }
}

fn ensure_directory_exists(dir: &Path) -> Result<(), Error> {
    match dir.exists() {
        true => Ok(()),
        false => DirBuilder::new().recursive(true).create(&dir),
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Write;
    use tempfile::tempdir;

    fn validate_against_schema(version: SchemaVersion, root: &Path) {
        match version {
            SchemaVersion::V1 => v1::validate_against_schema(root),
        }
    }

    /// Run a round trip test against all known schema versions.
    fn round_trip_test_all_versions<F>(produce_run_fn: F)
    where
        F: Fn(&OutputDirectoryBuilder) -> TestRunResult<'static>,
    {
        for version in SchemaVersion::all_variants() {
            let dir = tempdir().expect("Create dir");
            let output_dir = OutputDirectoryBuilder::new(dir.path(), version).expect("create dir");

            let run_result = produce_run_fn(&output_dir);
            output_dir.save_summary(&run_result).expect("save summary");

            validate_against_schema(version, dir.path());

            let parsed = TestRunResult::from_dir(dir.path()).expect("parse output directory");
            assert_eq!(run_result, parsed, "version: {:?}", version);
        }
    }

    #[test]
    fn minimal() {
        round_trip_test_all_versions(|dir_builder| TestRunResult {
            common: Cow::Owned(CommonResult {
                name: RUN_NAME.to_string(),
                artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                outcome: Outcome::Passed.into(),
                start_time: None,
                duration_milliseconds: None,
            }),
            suites: vec![],
        });
        let _ = Outcome::all_variants();
    }

    #[test]
    fn artifact_types() {
        for artifact_type in ArtifactType::all_variants() {
            round_trip_test_all_versions(|dir_builder| {
                let mut run_artifact_dir = dir_builder.new_artifact_dir().expect("new dir");
                let mut run_artifact =
                    run_artifact_dir.new_artifact(artifact_type, "a.txt").expect("create artifact");
                write!(run_artifact, "run contents").unwrap();

                let mut suite_artifact_dir = dir_builder.new_artifact_dir().expect("new dir");
                let mut suite_artifact = suite_artifact_dir
                    .new_artifact(artifact_type, "a.txt")
                    .expect("create artifact");
                write!(suite_artifact, "suite contents").unwrap();

                let mut case_artifact_dir = dir_builder.new_artifact_dir().expect("new dir");
                let mut case_artifact = case_artifact_dir
                    .new_artifact(artifact_type, "a.txt")
                    .expect("create artifact");
                write!(case_artifact, "case contents").unwrap();

                TestRunResult {
                    common: Cow::Owned(CommonResult {
                        name: RUN_NAME.to_string(),
                        artifact_dir: run_artifact_dir,
                        outcome: Outcome::Passed.into(),
                        start_time: None,
                        duration_milliseconds: None,
                    }),
                    suites: vec![SuiteResult {
                        common: Cow::Owned(CommonResult {
                            name: "suite".to_string(),
                            artifact_dir: suite_artifact_dir,
                            outcome: Outcome::Passed.into(),
                            start_time: None,
                            duration_milliseconds: None,
                        }),
                        tags: Cow::Owned(vec![]),
                        cases: vec![TestCaseResult {
                            common: Cow::Owned(CommonResult {
                                name: "case".to_string(),
                                artifact_dir: case_artifact_dir,
                                outcome: Outcome::Passed.into(),
                                start_time: None,
                                duration_milliseconds: None,
                            }),
                        }],
                    }],
                }
            });
        }
    }

    #[test]
    fn artifact_types_moniker_specified() {
        for artifact_type in ArtifactType::all_variants() {
            round_trip_test_all_versions(|dir_builder| {
                let mut run_artifact_dir = dir_builder.new_artifact_dir().expect("new dir");
                let mut run_artifact = run_artifact_dir
                    .new_artifact(
                        ArtifactMetadata {
                            artifact_type: artifact_type.into(),
                            component_moniker: Some("moniker".to_string()),
                        },
                        "a.txt",
                    )
                    .expect("create artifact");
                write!(run_artifact, "run contents").unwrap();

                let mut suite_artifact_dir = dir_builder.new_artifact_dir().expect("new dir");
                let mut suite_artifact = suite_artifact_dir
                    .new_artifact(
                        ArtifactMetadata {
                            artifact_type: artifact_type.into(),
                            component_moniker: Some("moniker".to_string()),
                        },
                        "a.txt",
                    )
                    .expect("create artifact");
                write!(suite_artifact, "suite contents").unwrap();

                let mut case_artifact_dir = dir_builder.new_artifact_dir().expect("new dir");
                let mut case_artifact = case_artifact_dir
                    .new_artifact(
                        ArtifactMetadata {
                            artifact_type: artifact_type.into(),
                            component_moniker: Some("moniker".to_string()),
                        },
                        "a.txt",
                    )
                    .expect("create artifact");
                write!(case_artifact, "case contents").unwrap();

                TestRunResult {
                    common: Cow::Owned(CommonResult {
                        name: RUN_NAME.to_string(),
                        artifact_dir: run_artifact_dir,
                        outcome: Outcome::Passed.into(),
                        start_time: None,
                        duration_milliseconds: None,
                    }),
                    suites: vec![SuiteResult {
                        common: Cow::Owned(CommonResult {
                            name: "suite".to_string(),
                            artifact_dir: suite_artifact_dir,
                            outcome: Outcome::Passed.into(),
                            start_time: None,
                            duration_milliseconds: None,
                        }),
                        tags: Cow::Owned(vec![]),
                        cases: vec![TestCaseResult {
                            common: Cow::Owned(CommonResult {
                                name: "case".to_string(),
                                artifact_dir: case_artifact_dir,
                                outcome: Outcome::Passed.into(),
                                start_time: None,
                                duration_milliseconds: None,
                            }),
                        }],
                    }],
                }
            });
        }
    }

    #[test]
    fn outcome_types() {
        for outcome_type in Outcome::all_variants() {
            round_trip_test_all_versions(|dir_builder| TestRunResult {
                common: Cow::Owned(CommonResult {
                    name: RUN_NAME.to_string(),
                    artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                    outcome: outcome_type.into(),
                    start_time: None,
                    duration_milliseconds: None,
                }),
                suites: vec![SuiteResult {
                    common: Cow::Owned(CommonResult {
                        name: "suite".to_string(),
                        artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                        outcome: outcome_type.into(),
                        start_time: None,
                        duration_milliseconds: None,
                    }),
                    tags: Cow::Owned(vec![]),
                    cases: vec![TestCaseResult {
                        common: Cow::Owned(CommonResult {
                            name: "case".to_string(),
                            artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                            outcome: outcome_type.into(),
                            start_time: None,
                            duration_milliseconds: None,
                        }),
                    }],
                }],
            });
        }
    }

    #[test]
    fn timing_specified() {
        round_trip_test_all_versions(|dir_builder| TestRunResult {
            common: Cow::Owned(CommonResult {
                name: RUN_NAME.to_string(),
                artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                outcome: Outcome::Passed.into(),
                start_time: Some(1),
                duration_milliseconds: Some(2),
            }),
            suites: vec![SuiteResult {
                common: Cow::Owned(CommonResult {
                    name: "suite".to_string(),
                    artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                    outcome: Outcome::Passed.into(),
                    start_time: Some(3),
                    duration_milliseconds: Some(4),
                }),
                tags: Cow::Owned(vec![]),
                cases: vec![TestCaseResult {
                    common: Cow::Owned(CommonResult {
                        name: "case".to_string(),
                        artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                        outcome: Outcome::Passed.into(),
                        start_time: Some(5),
                        duration_milliseconds: Some(6),
                    }),
                }],
            }],
        });
    }

    #[test]
    fn tags_specified() {
        round_trip_test_all_versions(|dir_builder| TestRunResult {
            common: Cow::Owned(CommonResult {
                name: RUN_NAME.to_string(),
                artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                outcome: Outcome::Passed.into(),
                start_time: Some(1),
                duration_milliseconds: Some(2),
            }),
            suites: vec![SuiteResult {
                common: Cow::Owned(CommonResult {
                    name: "suite".to_string(),
                    artifact_dir: dir_builder.new_artifact_dir().expect("new dir"),
                    outcome: Outcome::Passed.into(),
                    start_time: Some(3),
                    duration_milliseconds: Some(4),
                }),
                tags: Cow::Owned(vec![
                    TestTag { key: "hermetic".to_string(), value: "false".to_string() },
                    TestTag { key: "realm".to_string(), value: "system".to_string() },
                ]),
                cases: vec![],
            }],
        });
    }
}