| 1 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
// file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
//! Utilities for recording when testing APIs have been called on specific |
| 6 |
//! metrics. |
| 7 |
//! |
| 8 |
//! Testing coverage is enabled by setting the GLEAN_TEST_COVERAGE environment |
| 9 |
//! variable to the name of an output file. This output file must run through a |
| 10 |
//! post-processor (in glean_parser's `coverage` command) to convert to a format |
| 11 |
//! understood by third-party coverage reporting tools. |
| 12 |
//! |
| 13 |
//! While running a unit test suite, Glean records which database keys were |
| 14 |
//! accessed by the testing APIs, with one entry per line. Database keys are |
| 15 |
//! usually, but not always, the same as metric identifiers, but it is the |
| 16 |
//! responsibility of the post-processor to resolve that difference. |
| 17 |
//! |
| 18 |
//! This functionality has no runtime overhead unless the testing API is used. |
| 19 |
|
| 20 |
use std::env; |
| 21 |
use std::fs::{File, OpenOptions}; |
| 22 |
use std::io::Write; |
| 23 |
use std::sync::Mutex; |
| 24 |
|
| 25 |
use once_cell::sync::Lazy; |
| 26 |
|
| 27 |
static COVERAGE_FILE: Lazy<Option<Mutex<File>>> = Lazy::new(|| { |
| 28 |
if let Some(filename) = env::var_os("GLEAN_TEST_COVERAGE") { |
| 29 |
match OpenOptions::new().append(true).create(true).open(filename) { |
| 30 |
Ok(file) => { |
| 31 |
return Some(Mutex::new(file)); |
| 32 |
} |
| 33 |
Err(err) => { |
| 34 |
log::error!("Couldn't open file for coverage results: {:?}", err); |
| 35 |
} |
| 36 |
} |
| 37 |
} |
| 38 |
None |
| 39 |
}); |
| 40 |
|
| 41 |
pub(crate) fn record_coverage(metric_id: &str) { |
| 42 |
if let Some(file_mutex) = &*COVERAGE_FILE { |
| 43 |
let mut file = file_mutex.lock().unwrap(); |
| 44 |
writeln!(&mut file, "{}", metric_id).ok(); |
| 45 |
file.flush().ok(); |
| 46 |
} |
| 47 |
} |