fluent_asserter/
hashmap_asserter.rs

1use super::*;
2use std::collections::HashMap;
3use std::fmt::Display;
4use std::hash::Hash;
5
6//TODO: add trait
7
8pub struct ValueAssertions<'a, K, V> {
9    key: &'a K,
10    value: &'a V,
11    hash_map_name: String,
12}
13
14impl<'a, K, V> ValueAssertions<'a, K, V>
15where
16    V: PartialEq + Display,
17    K: Display,
18{
19    pub fn with_value(&'a self, expected_value: V) {
20        if *self.value != expected_value {
21            panic!(
22                "Expected {} to contain {} with value '{}', but it has the value '{}'.",
23                &self.hash_map_name, &self.key, expected_value, &self.value
24            )
25        }
26    }
27}
28
29impl<'a, K, V> Asserter<&HashMap<K, V>>
30where
31    K: Eq + Hash + Display,
32{
33    /// Checks the length of the HashMap
34    pub fn has_length(&self, expected_length: usize) {
35        if self.value.len() != expected_length {
36            panic!(
37                "Expected {} to have length {}, but it has {}",
38                &self.name,
39                expected_length,
40                self.value.len()
41            );
42        }
43    }
44
45    /// Checks if the HashMap is empty
46    pub fn is_empty(&self) {
47        if self.value.len() > 0 {
48            panic!(
49                "Expected {} to be empty, but it has length {}.",
50                &self.name,
51                self.value.len()
52            )
53        }
54    }
55
56    /// Checks if the HashMap is not empty
57    pub fn is_not_empty(&self) {
58        if self.value.is_empty() {
59            panic!("Expected {} to not to be empty, but it is.", &self.name)
60        }
61    }
62
63    /// Checks if the HashMap contains the specified key
64    pub fn contains_key(&'a self, expected_key: &'a K) -> ValueAssertions<'a, K, V> {
65        if !&self.value.contains_key(expected_key) {
66            panic!(
67                "Expected {} to contain {}, but it does not.",
68                &self.name, &expected_key
69            );
70        }
71
72        let value = &self.value.get(expected_key);
73        let value_for_key = value.unwrap();
74
75        ValueAssertions {
76            key: expected_key,
77            value: value_for_key,
78            hash_map_name: String::from(&self.name),
79        }
80    }
81
82    /// Checks if the HashMap does not contain the specified key
83    pub fn does_not_contain_key(&self, not_expected_key: K) {
84        if self.value.contains_key(&not_expected_key) {
85            panic!(
86                "Expected {} to not to contain {}, but it does.",
87                &self.name, &not_expected_key
88            );
89        }
90    }
91}