Skip to content

Commit

Permalink
Added tests and removed unneeded
Browse files Browse the repository at this point in the history
The tests convinced me that the removed methods were equivalent to `.contain`.
  • Loading branch information
jtk18 committed Jan 3, 2022
1 parent fa5d60b commit db0a6db
Showing 1 changed file with 55 additions and 17 deletions.
72 changes: 55 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<T: AsRef<Path>> 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()
Expand All @@ -35,3 +19,57 @@ impl<T: AsRef<Path>> 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);
}
}
}
}

0 comments on commit db0a6db

Please sign in to comment.