From ff0b31cfe68b2bc7318a98827d812e32deff0b4c Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Fri, 22 Apr 2016 08:24:15 -0400 Subject: Alias#write_to_file: Fix append and ending newline Changed the test to use a file with multiple alias lines for a more real-world scenario. Achieving this by copying the `testdata/aliases` file into a new temporary test file instead of creating a new blank file. Then needed to change our assertion so that we get the correct line from the file to compare on. This is always the last line in the file. Note that `.len() - 2` is used because `.len() - 1` is the final newline. The test change revealed two errors in my code: 1. I needed to open the file for appending, not just for writing. 2. A newline needs to be appended to the end of the file (otherwise all our aliases get written to the same line). Fix the errors. --- src/main.rs | 4 ++-- src/tests.rs | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index d484e5e..77f230a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -51,8 +51,8 @@ impl Alias { } fn write_to_file>(&self, file: P) -> Result<(), io::Error> { - let mut f = try!(OpenOptions::new().write(true).open(file)); - try!(f.write_all(self.to_string().as_bytes())); + let mut f = try!(OpenOptions::new().append(true).open(file)); + try!(f.write_all(format!("{}\n", self.to_string()).as_bytes())); Ok(()) } diff --git a/src/tests.rs b/src/tests.rs index 1034bc6..2a6e264 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -130,13 +130,14 @@ fn alias_write_to_file_must_write_given_alias_to_file() { let alias = update_alias_id_sample_alias(); let test_file = "./testdata/write_to_file"; - File::create(test_file).unwrap(); + fs::copy("./testdata/aliases", test_file).unwrap(); alias.write_to_file(test_file).unwrap(); let mut f = File::open(test_file).unwrap(); let mut file_contents = String::new(); f.read_to_string(&mut file_contents).unwrap(); + let file_contents: Vec<&str> = file_contents.split('\n').collect(); fs::remove_file(test_file).unwrap(); - assert_eq!(alias.to_string(), file_contents); + assert_eq!(alias.to_string(), file_contents[file_contents.len() - 2]); } -- cgit v1.2.3