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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
use warp::{Rejection, Reply};

use crate::{
    db::queries::search::{search_count_db, search_db},
    v0::{context::SharedContext, result::HandlerResult},
};

use super::requests::{SearchCountQuery, SearchQuery};

pub(super) async fn search(
    query: SearchQuery,
    ctx: SharedContext,
) -> Result<impl Reply, Rejection> {
    let pool = ctx.read().await.db_connection_pool.clone();
    Ok(HandlerResult(search_db(query, &pool).await))
}

pub(super) async fn search_count(
    query: SearchCountQuery,
    ctx: SharedContext,
) -> Result<impl Reply, Rejection> {
    let pool = ctx.read().await.db_connection_pool.clone();
    Ok(HandlerResult(search_count_db(query, &pool).await))
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::db::models::challenges::Challenge;
    use crate::testing::filters::ResponseBytesExt;
    use crate::v0::context::test::new_test_shared_context_from_url;
    use crate::v0::endpoints::search::requests::{Column, Constraint, OrderBy, Table};
    use pretty_assertions::assert_eq;
    use vit_servicing_station_tests::common::{
        data::ArbitrarySnapshotGenerator, startup::db::DbBuilder,
    };
    use warp::Filter;

    #[tokio::test]
    async fn basic_search() {
        // build context
        let mut gen = ArbitrarySnapshotGenerator::default();

        let mut snapshot = gen.snapshot();
        let c = snapshot.challenges_mut();
        c[0].title = "abc1".to_string();

        let db_url = DbBuilder::new()
            .with_snapshot(&snapshot)
            .build_async()
            .await
            .unwrap();
        let shared_context = new_test_shared_context_from_url(&db_url);
        let filter_context = shared_context.clone();
        let with_context = warp::any().map(move || filter_context.clone());

        let challenge = snapshot.challenges().remove(0);

        let filter = warp::path!("search")
            .and(warp::post())
            .and(warp::body::json())
            .and(with_context.clone())
            .and_then(search);

        let body = serde_json::to_string(&SearchQuery {
            query: SearchCountQuery {
                table: Table::Challenges,
                filter: vec![Constraint::Text {
                    search: "1".to_string(),
                    column: Column::Title,
                }],
                order_by: vec![],
            },
            limit: None,
            offset: None,
        })
        .unwrap();

        let challenges: Vec<Challenge> = warp::test::request()
            .method("POST")
            .path("/search")
            .body(body)
            .reply(&filter)
            .await
            .as_json();

        assert_eq!(challenges.len(), 1);
        assert_eq!(
            serde_json::to_value(&challenges[0]).unwrap(),
            serde_json::to_value(&challenge).unwrap()
        );

        let body = serde_json::to_string(&SearchCountQuery {
            table: Table::Challenges,
            filter: vec![Constraint::Text {
                search: "1".to_string(),
                column: Column::Title,
            }],
            order_by: vec![],
        })
        .unwrap();

        let filter = warp::path!("search_count")
            .and(warp::post())
            .and(warp::body::json())
            .and(with_context)
            .and_then(search_count);

        let count: i64 = warp::test::request()
            .method("POST")
            .path("/search_count")
            .body(body)
            .reply(&filter)
            .await
            .as_json();

        assert_eq!(count, 1);
    }

    /* TODO: Find out why this fails, if we don't obsolete vitSS soon enough. */
    #[tokio::test]
    async fn multiple_item_search() {
        // build context
        let mut gen = ArbitrarySnapshotGenerator::default();

        let mut snapshot = gen.snapshot();
        let c = snapshot.challenges_mut();
        c[0].title = "abc1".to_string();
        c[1].title = "abcd1".to_string();
        c[2].title = "abcde1".to_string();

        let db_url = DbBuilder::new()
            .with_snapshot(&snapshot)
            .build_async()
            .await
            .unwrap();
        let shared_context = new_test_shared_context_from_url(&db_url);
        let filter_context = shared_context.clone();
        let with_context = warp::any().map(move || filter_context.clone());

        let filter_search = warp::path!("search")
            .and(warp::post())
            .and(warp::body::json())
            .and(with_context.clone())
            .and_then(search);

        let filter_search_count = warp::path!("search_count")
            .and(warp::post())
            .and(warp::body::json())
            .and(with_context)
            .and_then(search_count);

        let query = SearchQuery {
            query: SearchCountQuery {
                table: Table::Challenges,
                filter: vec![Constraint::Text {
                    column: Column::Title,
                    search: "1".to_string(),
                }],
                order_by: vec![OrderBy::Column {
                    column: Column::Title,
                    descending: false,
                }],
            },
            limit: None,
            offset: None,
        };

        let body = serde_json::to_string(&query).unwrap();

        let challenges: Vec<Challenge> = warp::test::request()
            .method("POST")
            .path("/search")
            .body(body)
            .reply(&filter_search)
            .await
            .as_json();

        let expected_challenges = snapshot
            .challenges()
            .into_iter()
            .take(3)
            .collect::<Vec<_>>();
        assert_eq!(
            serde_json::to_value(&expected_challenges).unwrap(),
            serde_json::to_value(&challenges).unwrap()
        );

        let body = serde_json::to_string(&SearchCountQuery {
            table: Table::Challenges,
            filter: vec![Constraint::Text {
                column: Column::Title,
                search: "1".to_string(),
            }],
            order_by: vec![OrderBy::Column {
                column: Column::Title,
                descending: false,
            }],
        })
        .unwrap();

        let count: i64 = warp::test::request()
            .method("POST")
            .path("/search_count")
            .body(body)
            .reply(&filter_search_count)
            .await
            .as_json();

        assert_eq!(count, 3);

        let body = serde_json::to_string(&SearchQuery {
            query: SearchCountQuery {
                order_by: vec![OrderBy::Column {
                    column: Column::Title,
                    descending: true,
                }],
                ..query.query
            },
            ..query
        })
        .unwrap();

        let reversed: Vec<Challenge> = warp::test::request()
            .method("POST")
            .path("/search")
            .body(body)
            .reply(&filter_search)
            .await
            .as_json();

        let expected_challenges = snapshot
            .challenges()
            .into_iter()
            .take(3)
            .rev()
            .collect::<Vec<_>>();
        assert_eq!(
            serde_json::to_value(&expected_challenges).unwrap(),
            serde_json::to_value(&reversed).unwrap()
        );

        let body = serde_json::to_string(&SearchCountQuery {
            order_by: vec![OrderBy::Column {
                column: Column::Title,
                descending: true,
            }],
            table: Table::Challenges,
            filter: vec![Constraint::Text {
                column: Column::Title,
                search: "1".to_string(),
            }],
        })
        .unwrap();

        let count: i64 = warp::test::request()
            .method("POST")
            .path("/search_count")
            .body(body)
            .reply(&filter_search_count)
            .await
            .as_json();

        assert_eq!(count, 3);
    }

    #[tokio::test]
    async fn limits_and_offset_item_search() {
        // build context
        let mut gen = ArbitrarySnapshotGenerator::default();

        let mut snapshot = gen.snapshot();
        let c = snapshot.challenges_mut();
        c[0].title = "abc1".to_string();
        c[1].title = "abcd1".to_string();
        c[2].title = "abcd1".to_string();
        c[3].title = "abcd1".to_string();
        c[4].title = "abcde1".to_string();

        let db_url = DbBuilder::new()
            .with_snapshot(&snapshot)
            .build_async()
            .await
            .unwrap();
        let shared_context = new_test_shared_context_from_url(&db_url);
        let filter_context = shared_context.clone();
        let with_context = warp::any().map(move || filter_context.clone());

        let filter = warp::path!("search")
            .and(warp::post())
            .and(warp::body::json())
            .and(with_context)
            .and_then(search);

        let query = SearchQuery {
            query: SearchCountQuery {
                table: Table::Challenges,
                filter: vec![Constraint::Text {
                    column: Column::Title,
                    search: "1".to_string(),
                }],
                order_by: vec![OrderBy::Column {
                    column: Column::Title,
                    descending: false,
                }],
            },
            limit: Some(4),
            offset: Some(1),
        };

        let body = serde_json::to_string(&query).unwrap();

        let challenges: Vec<Challenge> = warp::test::request()
            .method("POST")
            .path("/search")
            .body(body)
            .reply(&filter)
            .await
            .as_json();

        let expected_challenges = snapshot
            .challenges()
            .into_iter()
            .skip(1)
            .take(4)
            .collect::<Vec<_>>();
        assert_eq!(
            serde_json::to_value(expected_challenges).unwrap(),
            serde_json::to_value(challenges).unwrap()
        );
    }
}