Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 45 additions & 16 deletions dropshot/src/test_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,11 +458,10 @@ where

/// Constructs a Logger for use by a test suite. If a file-based logger is
/// requested, the file will be put in a temporary directory and the name will be
/// unique for a given test name and is likely to be unique across multiple runs
/// of this test. The file will also be deleted if the test succeeds, indicated
/// by invoking [`LogContext::cleanup_successful`]. This way, you can debug a
/// test failure from the failed instance rather than hoping the failure is
/// reproducible.
/// collision-resistant across multiple runs of this test. The file will also be
/// deleted if the test succeeds, indicated by invoking
/// [`LogContext::cleanup_successful`]. This way, you can debug a test failure
/// from the failed instance rather than hoping the failure is reproducible.
///
/// ## Example
///
Expand Down Expand Up @@ -521,15 +520,15 @@ impl LogContext {
/// log (i.e., [`ConfigLogging::File`]), then the requested path _must_ be
/// the string `"UNUSED"` and it will be replaced with a file name (in a
/// temporary directory) containing `test_name` and other information to make
/// the filename likely to be unique across multiple runs (e.g., process id).
/// the filename collision-resistant across multiple runs.
pub fn new(
test_name: &str,
initial_config_logging: &ConfigLogging,
) -> LogContext {
// See above. If the caller requested a file path, assert that the path
// matches our sentinel (just to improve debuggability -- otherwise
// people might be pretty confused about where the logs went). Then
// override the path with one uniquely generated for this test.
// override the path with one generated for this test.
// TODO-developer allow keeping the logs in successful cases with an
// environment variable or other flag.
let (log_path, log_config) = match initial_config_logging {
Expand All @@ -538,7 +537,7 @@ impl LogContext {
dummy_path, "UNUSED",
"for test suite logging configuration, when mode = \
\"file\" is used, the path MUST be the sentinel string \
\"UNUSED\". It will be replaced with a unique path for \
\"UNUSED\". It will be replaced with a generated path for \
each test."
);
let new_path = log_file_for_test(test_name);
Expand All @@ -555,7 +554,12 @@ impl LogContext {
other_config => (None, other_config.clone()),
};

let log = log_config.to_logger(test_name).unwrap();
let log = log_config.to_logger(test_name).unwrap_or_else(|error| {
panic!(
"failed to create logger for {test_name:?} \
using {log_config:?}: {error}"
)
});
LogContext { log, test_name: test_name.to_owned(), log_path }
}

Expand Down Expand Up @@ -831,14 +835,16 @@ pub async fn iter_collection<T: Clone + DeserializeOwned>(

static TEST_SUITE_LOGGER_ID: AtomicU32 = AtomicU32::new(0);

/// Returns a unique prefix for log files generated by other processes.
/// Returns a collision-resistant prefix for log files generated by other processes.
///
/// The return value is a combination of:
///
/// - a directory path within which the logs should go
/// - a unique string prefix that identifies this test and process ID, along
/// with a counter that is atomically bumped each time this function is
/// called.
/// - a string prefix of the form `{executable}-{test_name}.{pid}.{counter}.{uuid}`,
/// where the counter is atomically bumped and a fresh UUIDv4 in simple
/// hexadecimal format is generated on each call.
///
/// This function does not create or reserve a filesystem entry.
pub fn log_prefix_for_test(test_name: &str) -> (Utf8PathBuf, String) {
let arg0 = {
let arg0path = Utf8PathBuf::from(std::env::args().next().unwrap());
Expand All @@ -850,11 +856,14 @@ pub fn log_prefix_for_test(test_name: &str) -> (Utf8PathBuf, String) {
.expect("temp dir is valid UTF-8");
let id = TEST_SUITE_LOGGER_ID.fetch_add(1, Ordering::SeqCst);
let pid = std::process::id();
(dir, format!("{arg0}-{test_name}.{pid}.{id}"))
let uuid = uuid::Uuid::new_v4().simple();
(dir, format!("{arg0}-{test_name}.{pid}.{id}.{uuid}"))
}

/// Returns a unique path name in a temporary directory that includes the given
/// `test_name`.
/// Returns a collision-resistant path name in a temporary directory that includes
/// the given `test_name` and ends in `.log`.
///
/// This function does not create or reserve a filesystem entry.
pub fn log_file_for_test(test_name: &str) -> Utf8PathBuf {
let (mut dir, prefix) = log_prefix_for_test(test_name);
dir.push(format!("{prefix}.log"));
Expand Down Expand Up @@ -963,11 +972,31 @@ mod test {

use super::BunyanLogRecord;
use super::BunyanLogRecordSpec;
use super::LogContext;
use super::verify_bunyan_records;
use super::verify_bunyan_records_sequential;
use crate::ConfigLogging;
use crate::ConfigLoggingIfExists;
use crate::ConfigLoggingLevel;
use chrono::DateTime;
use chrono::Utc;

#[test]
#[should_panic(
expected = "failed to create logger for \"test_log_context_creation_error\\0\""
)]
fn test_log_context_creation_error() {
// NUL is invalid in a filesystem path on every supported platform.
LogContext::new(
"test_log_context_creation_error\0",
&ConfigLogging::File {
level: ConfigLoggingLevel::Info,
path: "UNUSED".into(),
if_exists: ConfigLoggingIfExists::Fail,
},
);
}

fn make_dummy_record() -> BunyanLogRecord {
let t1: DateTime<Utc> =
DateTime::parse_from_rfc3339(T1_STR).unwrap().into();
Expand Down