-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathremove.rs
More file actions
116 lines (101 loc) · 3.35 KB
/
remove.rs
File metadata and controls
116 lines (101 loc) · 3.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use crate::error::MocksError;
use crate::storage::operation::select_one::select_one;
use crate::storage::StorageData;
use serde_json::Value;
pub fn remove(
data: &mut StorageData,
resource_key: &str,
search_key: &str,
) -> Result<Value, MocksError> {
let values = data
.get(resource_key)
.and_then(Value::as_array)
.ok_or(MocksError::ResourceNotFound)?;
// Get the target to be removed
let removed = select_one(data, resource_key, search_key)?;
let filtered: Vec<Value> = values
.iter()
.filter(|&value| {
value
.get("id")
.and_then(|id| match id {
Value::Number(n) => Some(n.to_string() != search_key),
Value::String(s) => Some(s != search_key),
_ => None,
})
.unwrap_or(true)
})
.cloned()
.collect();
data[resource_key] = Value::Array(filtered);
Ok(removed)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_remove_with_string_id() {
let mut data = json!({"posts":[{"id":"test1","title":"first post","views":100}]});
match remove(&mut data, "posts", "test1") {
Ok(v) => {
assert_eq!(v, json!({"id":"test1","title":"first post","views":100}));
match &data["posts"].as_array() {
None => {
panic!("panic in test_remove_with_string_id");
}
Some(values) => {
assert_eq!(values.len(), 0);
}
}
}
Err(e) => {
panic!("panic in test_remove_with_string_id: {}", e.to_string());
}
}
}
#[test]
fn test_remove_with_number_id() {
let mut data = json!({"posts":[{"id":1,"title":"first post","views":100}]});
match remove(&mut data, "posts", "1") {
Ok(v) => {
assert_eq!(v, json!({"id":1,"title":"first post","views":100}));
match &data["posts"].as_array() {
None => {
panic!("panic in test_remove_with_number_id");
}
Some(values) => {
assert_eq!(values.len(), 0);
}
}
}
Err(e) => {
panic!("panic in test_remove_with_number_id: {}", e.to_string());
}
}
}
#[test]
fn test_remove_error_resource_not_found() {
let mut data = json!({"posts":[{"id":"test1","title":"first post","views":100}]});
match remove(&mut data, "errors", "test1") {
Ok(_v) => {
panic!("panic in test_remove_error_resource_not_found");
}
Err(e) => {
assert_eq!(e, MocksError::ResourceNotFound);
}
}
}
#[test]
fn test_remove_error_object_not_found() {
let mut data = json!({"posts":[{"id":"test1","title":"first post","views":100}]});
match remove(&mut data, "posts", "error") {
Ok(_v) => {
panic!("panic in test_remove_error_object_not_found");
}
Err(e) => {
assert_eq!(e, MocksError::ObjectNotFound);
}
}
}
}