-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathlight_rolling_stocks.rs
352 lines (309 loc) · 11.5 KB
/
light_rolling_stocks.rs
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use axum::extract::Json;
use axum::extract::Path;
use axum::extract::Query;
use axum::extract::State;
use axum::Extension;
use editoast_authz::BuiltinRole;
use editoast_models::DbConnection;
use editoast_models::DbConnectionPoolV2;
use editoast_schemas::rolling_stock::RollingStockLivery;
use itertools::Itertools;
use serde::Serialize;
use std::ops::DerefMut;
use utoipa::ToSchema;
use crate::error::Result;
use crate::modelsv2::rolling_stock_livery::RollingStockLiveryModel;
use crate::modelsv2::LightRollingStockModel;
use crate::modelsv2::Retrieve;
use crate::views::pagination::PaginatedList;
use crate::views::pagination::PaginationQueryParam;
use crate::views::pagination::PaginationStats;
use crate::views::rolling_stocks::light_rolling_stock::LightRollingStock;
use crate::views::rolling_stocks::RollingStockError;
use crate::views::rolling_stocks::RollingStockIdParam;
use crate::views::rolling_stocks::RollingStockKey;
use crate::views::rolling_stocks::RollingStockNameParam;
use crate::List;
use crate::SelectionSettings;
#[cfg(test)]
use serde::Deserialize;
use super::AuthorizationError;
use super::AuthorizerExt;
crate::routes! {
"/light_rolling_stock" => {
list,
"/name/{rolling_stock_name}" => get_by_name,
"/{rolling_stock_id}" => get,
},
}
editoast_common::schemas! {
LightRollingStockWithLiveries,
}
#[derive(Debug, Serialize, ToSchema)]
#[cfg_attr(test, derive(Deserialize))]
pub struct LightRollingStockWithLiveries {
#[serde(flatten)]
pub rolling_stock: LightRollingStock,
pub liveries: Vec<RollingStockLivery>,
}
impl LightRollingStockWithLiveries {
async fn try_fetch(
conn: &mut DbConnection,
light_rolling_stock: LightRollingStockModel,
) -> Result<Self> {
let light_rolling_stock_id = light_rolling_stock.id;
let liveries = RollingStockLiveryModel::list(
conn,
SelectionSettings::new().filter(move || {
RollingStockLiveryModel::ROLLING_STOCK_ID.eq(light_rolling_stock_id)
}),
)
.await?
.into_iter()
.map_into()
.collect();
Ok(Self {
rolling_stock: light_rolling_stock.into(),
liveries,
})
}
}
#[derive(Serialize, ToSchema)]
#[cfg_attr(test, derive(Deserialize))]
struct LightRollingStockWithLiveriesCountList {
#[schema(value_type = Vec<LightRollingStockWithLiveries>)]
results: Vec<LightRollingStockWithLiveries>,
#[serde(flatten)]
stats: PaginationStats,
}
/// Paginated list of rolling stock with a lighter response
#[utoipa::path(
get, path = "",
tag = "rolling_stock",
params(PaginationQueryParam),
responses(
(status = 200, body = inline(LightRollingStockWithLiveriesCountList)),
)
)]
async fn list(
State(db_pool): State<DbConnectionPoolV2>,
Extension(authorizer): AuthorizerExt,
Query(page_settings): Query<PaginationQueryParam>,
) -> Result<Json<LightRollingStockWithLiveriesCountList>> {
let authorized = authorizer
.check_roles([BuiltinRole::RollingStockCollectionRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Unauthorized.into());
}
let settings = page_settings
.validate(1000)?
.warn_page_size(100)
.into_selection_settings()
.order_by(|| LightRollingStockModel::ID.asc());
let (light_rolling_stocks, stats) =
LightRollingStockModel::list_paginated(db_pool.get().await?.deref_mut(), settings).await?;
let results = light_rolling_stocks
.into_iter()
.zip(db_pool.iter_conn())
.map(|(light_rolling_stock, conn)| async move {
LightRollingStockWithLiveries::try_fetch(conn.await?.deref_mut(), light_rolling_stock)
.await
});
let results = futures::future::try_join_all(results).await?;
Ok(Json(LightRollingStockWithLiveriesCountList {
results,
stats,
}))
}
/// Retrieve a rolling stock's light representation by its id
#[utoipa::path(
get, path = "",
tag = "rolling_stock",
params(RollingStockIdParam),
responses(
(status = 200, body = LightRollingStockWithLiveries, description = "The rolling stock with their simplified effort curves"),
)
)]
async fn get(
State(db_pool): State<DbConnectionPoolV2>,
Extension(authorizer): AuthorizerExt,
Path(light_rolling_stock_id): Path<i64>,
) -> Result<Json<LightRollingStockWithLiveries>> {
let authorized = authorizer
.check_roles([BuiltinRole::RollingStockCollectionRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Unauthorized.into());
}
let light_rolling_stock = LightRollingStockModel::retrieve_or_fail(
db_pool.get().await?.deref_mut(),
light_rolling_stock_id,
|| RollingStockError::KeyNotFound {
rolling_stock_key: RollingStockKey::Id(light_rolling_stock_id),
},
)
.await?;
let light_rolling_stock_with_liveries = LightRollingStockWithLiveries::try_fetch(
db_pool.get().await?.deref_mut(),
light_rolling_stock,
)
.await?;
Ok(Json(light_rolling_stock_with_liveries))
}
/// Retrieve a rolling stock's light representation by its name
#[utoipa::path(
get, path = "",
tag = "rolling_stock",
params(RollingStockNameParam),
responses(
(status = 200, body = LightRollingStockWithLiveries, description = "The rolling stock with their simplified effort curves"),
)
)]
async fn get_by_name(
State(db_pool): State<DbConnectionPoolV2>,
Extension(authorizer): AuthorizerExt,
Path(light_rolling_stock_name): Path<String>,
) -> Result<Json<LightRollingStockWithLiveries>> {
let authorized = authorizer
.check_roles([BuiltinRole::RollingStockCollectionRead].into())
.await
.map_err(AuthorizationError::AuthError)?;
if !authorized {
return Err(AuthorizationError::Unauthorized.into());
}
let light_rolling_stock = LightRollingStockModel::retrieve_or_fail(
db_pool.get().await?.deref_mut(),
light_rolling_stock_name.clone(),
|| RollingStockError::KeyNotFound {
rolling_stock_key: RollingStockKey::Name(light_rolling_stock_name),
},
)
.await?;
let light_rolling_stock_with_liveries = LightRollingStockWithLiveries::try_fetch(
db_pool.get().await?.deref_mut(),
light_rolling_stock,
)
.await?;
Ok(Json(light_rolling_stock_with_liveries))
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use std::ops::DerefMut;
use axum::http::StatusCode;
use pretty_assertions::assert_eq;
use rstest::*;
use super::LightRollingStockWithLiveries;
use crate::error::InternalError;
use crate::modelsv2::fixtures::create_fast_rolling_stock;
use crate::modelsv2::fixtures::create_rolling_stock_livery_fixture;
use crate::views::light_rolling_stocks::LightRollingStockWithLiveriesCountList;
use crate::views::test_app::TestAppBuilder;
fn is_sorted(data: &[i64]) -> bool {
for elem in data.windows(2) {
if elem[0] >= elem[1] {
return false;
}
}
true
}
#[rstest]
async fn list_light_rolling_stock() {
let app = TestAppBuilder::default_app();
let request = app.get("/light_rolling_stock");
app.fetch(request).assert_status(StatusCode::OK);
}
#[rstest]
async fn get_light_rolling_stock() {
// GIVEN
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let rs_name = "fast_rolling_stock_name";
let fast_rolling_stock =
create_fast_rolling_stock(db_pool.get_ok().deref_mut(), rs_name).await;
let request = app.get(format!("/light_rolling_stock/{}", fast_rolling_stock.id).as_str());
// WHEN
let response: LightRollingStockWithLiveries =
app.fetch(request).assert_status(StatusCode::OK).json_into();
// THEN
assert_eq!(response.rolling_stock.id, fast_rolling_stock.id);
}
#[rstest]
async fn get_light_rolling_stock_by_name() {
// GIVEN
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let rs_name = "fast_rolling_stock_name";
let fast_rolling_stock =
create_fast_rolling_stock(db_pool.get_ok().deref_mut(), rs_name).await;
let request = app.get(format!("/light_rolling_stock/name/{}", rs_name).as_str());
// WHEN
let response: LightRollingStockWithLiveries =
app.fetch(request).assert_status(StatusCode::OK).json_into();
// THEN
assert_eq!(response.rolling_stock.id, fast_rolling_stock.id);
assert_eq!(response.rolling_stock.name, fast_rolling_stock.name);
}
#[rstest]
async fn get_unexisting_light_rolling_stock() {
let app = TestAppBuilder::default_app();
let request = app.get(format!("/light_rolling_stock/{}", -1).as_str());
app.fetch(request).assert_status(StatusCode::NOT_FOUND);
}
#[rstest]
async fn list_light_rolling_stock_increasing_ids() {
let app = TestAppBuilder::default_app();
let db_pool = app.db_pool();
let generated_rolling_stock = (0..10)
.zip(std::iter::repeat(&db_pool).map(|p| p.get()))
.map(|(rs_id, conn)| async move {
let fixtures = create_rolling_stock_livery_fixture(
conn.await.unwrap().deref_mut(),
&format!("rs_name_{}", rs_id),
)
.await;
let fixtures: Result<_, InternalError> = Ok(fixtures);
fixtures
});
let generated_fixtures = futures::future::try_join_all(generated_rolling_stock)
.await
.unwrap();
let expected_rs_ids = generated_fixtures
.iter()
.map(|(_, rs, _)| rs.id)
.collect::<HashSet<_>>();
let request = app.get("/light_rolling_stock/");
let response: LightRollingStockWithLiveriesCountList =
app.fetch(request).assert_status(StatusCode::OK).json_into();
let count = response.stats.count;
let uri = format!("/light_rolling_stock/?page_size={count}");
let request = app.get(&uri);
let response: LightRollingStockWithLiveriesCountList =
app.fetch(request).assert_status(StatusCode::OK).json_into();
// Ensure that AT LEAST all the rolling stocks create above are returned, in order
let vec_ids = response
.results
.iter()
.map(|x| x.rolling_stock.id)
.collect::<Vec<_>>();
assert!(is_sorted(&vec_ids));
let ids = HashSet::from_iter(vec_ids.into_iter());
// Since tests are not properly isolated, some rolling stock fixture may "leak" from another test, so maybe ids.len() > expected_ids.len()
assert!(expected_rs_ids.is_subset(&ids));
}
#[rstest]
async fn light_rolling_stock_max_page_size() {
let app = TestAppBuilder::default_app();
let request = app.get("/light_rolling_stock/?page_size=1010");
let response: InternalError = app
.fetch(request)
.assert_status(StatusCode::BAD_REQUEST)
.json_into();
assert_eq!(response.error_type, "editoast:pagination:InvalidPageSize");
assert_eq!(response.context["provided_page_size"], 1010);
assert_eq!(response.context["max_page_size"], 1000);
}
}