From 20a4ef59d9dd45fdd028f897e3270fbf57c5ae40 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Thu, 27 Jul 2023 21:39:55 +0100 Subject: [PATCH] add test for history::add --- src/history/add.rs | 72 +++++++++++++++++++++++++++++++++++++++++ src/test_utils.rs | 13 +++++++- test/data/downloads.txt | 2 ++ test/data/empty.txt | 0 4 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 test/data/downloads.txt create mode 100644 test/data/empty.txt diff --git a/src/history/add.rs b/src/history/add.rs index e904004..756edf2 100644 --- a/src/history/add.rs +++ b/src/history/add.rs @@ -15,3 +15,75 @@ pub fn add(link: &Link, file_name: &str) -> Result<()> { writeln!(file, "{}", link.href)?; Ok(()) } + +#[cfg(test)] +mod tests { + + use crate::{ + history::Link, + test_utils::{create_text_file, read_text_file}, + }; + + use super::*; + + #[test] + fn creates_file_if_missing() -> Result<()> { + //given + let (dir, file_name) = + create_text_file("download.txt", include_bytes!("../../test/data/empty.txt"))?; + std::fs::remove_file(&file_name)?; + + let link = Link { + href: "foo".to_string(), + rel: "bar".to_string(), + hreflang: None, + mime_type: None, + title: None, + length: None, + }; + //when + add(&link, &file_name)?; + + //then + let content: Vec = read_text_file(&file_name)?; + drop(dir); + + let expected = vec!["foo".to_string()]; + assert_eq!(content, expected); + + Ok(()) + } + + #[test] + fn appends_to_exising_file() -> Result<()> { + // given + let (dir, file_name) = create_text_file( + "download.txt", + include_bytes!("../../test/data/downloads.txt"), + )?; + + let link = Link { + href: "foo".to_string(), + rel: "bar".to_string(), + hreflang: None, + mime_type: None, + title: None, + length: None, + }; + //when + add(&link, &file_name)?; + + //then + let content: Vec = read_text_file(&file_name)?; + drop(dir); + + let expected = vec![ + "line-1".to_string(), + "line-2".to_string(), + "foo".to_string(), + ]; + assert_eq!(content, expected); + + Ok(()) + } +} diff --git a/src/test_utils.rs b/src/test_utils.rs index 36e67ff..305ae44 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -1,4 +1,8 @@ -use std::{fs::File, io::Write, str::from_utf8}; +use std::{ + fs::{read_to_string, File}, + io::Write, + str::from_utf8, +}; use tempfile::{tempdir, TempDir}; @@ -12,3 +16,10 @@ pub fn create_text_file(name: &str, data: &[u8]) -> Result<(TempDir, String)> { write!(&file, "{data}")?; Ok((dir, filename)) } + +pub fn read_text_file(file_name: &str) -> Result> { + Ok(read_to_string(file_name)? + .lines() + .map(String::from) + .collect()) +} diff --git a/test/data/downloads.txt b/test/data/downloads.txt new file mode 100644 index 0000000..1f26067 --- /dev/null +++ b/test/data/downloads.txt @@ -0,0 +1,2 @@ +line-1 +line-2 diff --git a/test/data/empty.txt b/test/data/empty.txt new file mode 100644 index 0000000..e69de29