From db0a6db4e67cb2945899420e33d2b9c75cd73d1c Mon Sep 17 00:00:00 2001 From: Jason Kiniry Date: Mon, 3 Jan 2022 15:10:42 -0600 Subject: [PATCH] Added tests and removed unneeded The tests convinced me that the removed methods were equivalent to `.contain`. --- src/lib.rs | 72 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 55 insertions(+), 17 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index df40c33..9f50d67 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,27 +1,11 @@ -use std::path::{Path, PathBuf}; +use std::path::Path; pub trait PathExt { - fn contains_or_ends_with(&self, pattern: &str) -> bool; - fn contains_or_starts_with(&self, pattern: &str) -> bool; fn starts_or_ends_with(&self, pattern: &str) -> bool; fn has_component(&self, component: &str) -> bool; } impl> PathExt for T { - fn contains_or_ends_with(&self, pattern: &str) -> bool { - self.as_ref() - .to_str() - .map(|s| s.contains(pattern) || s.ends_with(pattern)) - == Some(true) - } - - fn contains_or_starts_with(&self, pattern: &str) -> bool { - self.as_ref() - .to_str() - .map(|s| s.contains(pattern) || s.starts_with(pattern)) - == Some(true) - } - fn starts_or_ends_with(&self, pattern: &str) -> bool { self.as_ref() .to_str() @@ -35,3 +19,57 @@ impl> PathExt for T { .any(|c| c.as_os_str().eq(component)) } } + +#[cfg(test)] +mod tests { + use super::PathExt; + use std::path::{Path, PathBuf}; + + #[test] + fn test_has_component() { + let tests = &[( + "/opt/somewhere/someplace/", + vec![ + ("opt", true), + ("somewhere", true), + ("someplace/", false), + ("root", false), + ], + )]; + + for test_case in tests { + for test in test_case.1.iter() { + assert_eq!(test_case.0.has_component(test.0), test.1); + let p = Path::new(test_case.0); + assert_eq!(p.has_component(test.0), test.1); + let pb = PathBuf::from(test_case.0); + assert_eq!(pb.has_component(test.0), test.1); + } + } + } + + #[test] + fn test_starts_or_ends_with() { + let tests = &[( + "/opt/somewhere/someplace/somehow/", + vec![ + ("opt", false), + ("/opt", true), + ("somewhere", false), + ("someplace/somehow", false), + ("someplace/somehow/", true), + ("root", false), + ], + )]; + + for test_case in tests { + for test in test_case.1.iter() { + assert_eq!(test_case.0.starts_or_ends_with(test.0), test.1); + let p = Path::new(test_case.0); + assert_eq!(p.starts_or_ends_with(test.0), test.1); + let pb = PathBuf::from(test_case.0); + assert_eq!(pb.starts_or_ends_with(test.0), test.1); + } + } + } +}