Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Single item contains #4

Merged
merged 2 commits into from Oct 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -148,7 +148,8 @@ assert_that!(Some(1), not(none::<u8>()));

```rust
assert_that!(&vec!(1, 2, 3), contains(vec!(1, 2)));
assert_that!(&vec!(1, 2, 3), not(contains(vec!(4i))));
assert_that!(&vec!(1, 2, 3), contains(1));
assert_that!(&vec!(1, 2, 3), not(contains(4i)));

assert_that!(&vec!(1, 2, 3), contains(vec!(1, 2, 3)).exactly());
assert_that!(&vec!(1, 2, 3), not(contains(vec!(1, 2)).exactly()));
Expand Down
34 changes: 28 additions & 6 deletions src/matchers/contains.rs
Expand Up @@ -25,6 +25,16 @@ pub struct Contains<T> {
}

impl<T> Contains<T> {
/// Constructs new `Contains` matcher with the default options: order is not checked and
/// actual vector can have more items.
pub fn new(items: Vec<T>) -> Self {
Self {
items,
exactly: false,
in_order: false,
}
}

pub fn exactly(mut self) -> Contains<T> {
self.exactly = true;
self
Expand All @@ -36,6 +46,18 @@ impl<T> Contains<T> {
}
}

impl<T> From<Vec<T>> for Contains<T> {
fn from(items: Vec<T>) -> Contains<T> {
Contains::new(items)
}
}

impl<T> From<T> for Contains<T> {
fn from(item: T) -> Contains<T> {
Contains::new(vec![item])
}
}

impl<T: fmt::Debug> fmt::Display for Contains<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.exactly {
Expand Down Expand Up @@ -102,10 +124,10 @@ fn is_next_index(current_index: usize, previous_index: &Option<usize>) -> bool {
true
}

pub fn contains<T>(items: Vec<T>) -> Contains<T> {
Contains {
items,
exactly: false,
in_order: false,
}
/// Creates matcher that checks if actual data contains give item(s).
pub fn contains<T, I>(item: I) -> Contains<T>
where
I: Into<Contains<T>>,
{
item.into()
}
6 changes: 6 additions & 0 deletions tests/contain.rs
Expand Up @@ -26,6 +26,12 @@ mod contains {
assert_that!(slice, not(contains(vec![4])));
}

#[test]
fn single_item_contains() {
assert_that!(&vec![1, 2, 3], contains(2));
assert_that!(&vec![1, 2, 3], not(contains(4)));
}

#[test]
fn vec_contains_exactly() {
assert_that!(&vec![1, 2, 3], contains(vec![1, 2, 3]).exactly());
Expand Down