Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
Prev Previous commit
Next Next commit
Add tests for get_modification_time function
  • Loading branch information
TanmayPatil105 committed Apr 13, 2024
commit 0a77fe12b9f4c9794a25dfe3e2ac89ba335e2dcc
38 changes: 38 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub fn do_write_line(
}
}

/// Retrieves the modification time of the input file specified by file path
/// If an error occurs, it returns the current system time
pub fn get_modification_time(file_path: &str) -> String {
Comment thread
oSoMoN marked this conversation as resolved.
Comment thread
oSoMoN marked this conversation as resolved.
use chrono::{DateTime, Local};
use std::fs;
Expand Down Expand Up @@ -132,4 +134,40 @@ mod tests {
assert_line_written("foo bar\tbaz", true, 8, "foo bar baz");
}
}

mod modification_time {
use super::*;

#[test]
fn set_time() {
use chrono::{DateTime, Local};
use std::fs::File;
use std::time::SystemTime;

let>
let _ = std::fs::create_dir(target);
let filename = &format!("{target}/foo");
let temp = File::create(filename).unwrap();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use a tempfile.NamedTempFile instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think there are APIs to set modification time for a NamedTempFile.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NamedTempFile::as_file() exposes a reference to the underlying file, so you could do something like this:

use tempfile::NamedTempFile;
let temp = NamedTempFile::new().unwrap();
let current = SystemTime::now();
let _ = temp.as_file().set_modified(current);
…
assert_eq!(current, get_modification_time(&temp.path().to_string_lossy()));


// set file modification time equal to current time
let current = SystemTime::now();
let _ = temp.set_modified(current);

// format current time
let current: DateTime<Local> = current.into();
let current: String = current.format("%Y-%m-%d %H:%M:%S%.9f %z").to_string();

// verify
assert_eq!(current, get_modification_time(filename));
}

#[test]
fn invalid_file() {
let invalid_file = "target/utils/invalid-file";

let m_time = get_modification_time(invalid_file);

assert!(!m_time.is_empty());
Comment thread
TanmayPatil105 marked this conversation as resolved.
Outdated
}
}
}