-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmod.rs
789 lines (739 loc) · 27.1 KB
/
mod.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
mod electrical_profiles;
mod electrifications;
mod path_rangemap;
use std::collections::HashMap;
use std::collections::HashSet;
use actix_web::delete;
use actix_web::get;
use actix_web::post;
use actix_web::put;
use actix_web::web::Data;
use actix_web::web::Json;
use actix_web::web::Path;
use actix_web::HttpResponse;
use actix_web::Responder;
use chrono::DateTime;
use chrono::Utc;
use derivative::Derivative;
use diesel_async::AsyncPgConnection as PgConnection;
use editoast_derive::EditoastError;
use editoast_schemas::rolling_stock::RollingStock;
use geos::geojson::Geometry;
use geos::geojson::{self};
use geos::Geom;
use serde::Deserialize;
use serde::Serialize;
use thiserror::Error;
use utoipa::ToSchema;
use crate::core::pathfinding::PathfindingRequest as CorePathfindingRequest;
use crate::core::pathfinding::PathfindingResponse;
use crate::core::pathfinding::PathfindingWaypoints;
use crate::core::pathfinding::Waypoint as CoreWaypoint;
use crate::core::AsCoreRequest;
use crate::core::CoreClient;
use crate::error::Result;
use crate::models::Create;
use crate::models::Curve;
use crate::models::Delete;
use crate::models::PathWaypoint;
use crate::models::Pathfinding;
use crate::models::PathfindingChangeset;
use crate::models::PathfindingPayload;
use crate::models::Retrieve;
use crate::models::Slope;
use crate::models::Update;
use crate::modelsv2::infra_objects::TrackSectionModel;
use crate::modelsv2::Infra;
use crate::modelsv2::OperationalPointModel;
use crate::modelsv2::Retrieve as RetrieveV2;
use crate::modelsv2::RollingStockModel;
use crate::schema::ApplicableDirectionsTrackRange;
use crate::schema::OperationalPoint;
use crate::schema::TrackSection;
use crate::DbPool;
use editoast_common::geometry::diesel_linestring_to_geojson;
use editoast_common::geometry::geojson_to_diesel_linestring;
use editoast_schemas::infra::TrackRange;
crate::routes! {
"/pathfinding" => {
create_pf,
"/{pathfinding_id}" => {
get_pf,
del_pf,
update_pf,
electrifications::routes(),
electrical_profiles::routes(),
},
}
}
editoast_common::schemas! {
PathResponse,
PathfindingRequest,
PathfindingStep,
Waypoint,
WaypointLocation,
electrifications::schemas(),
electrical_profiles::schemas(),
}
#[derive(Debug, Error, EditoastError, Serialize)]
#[editoast_error(base_id = "pathfinding")]
#[allow(clippy::enum_variant_names)]
enum PathfindingError {
#[error("Pathfinding {pathfinding_id} does not exist")]
#[editoast_error(status = 404)]
NotFound { pathfinding_id: i64 },
#[error("Electrification {electrification_id} overlaps with other electrifications")]
#[editoast_error(status = 500)]
ElectrificationOverlap {
electrification_id: String,
overlapping_ranges: Vec<ApplicableDirectionsTrackRange>,
},
#[error("Electrical Profile overlaps with others")]
#[editoast_error(status = 500)]
ElectricalProfilesOverlap { overlapping_ranges: Vec<TrackRange> },
#[error("Infra {infra_id} does not exist")]
#[editoast_error(status = 404)]
InfraNotFound { infra_id: i64 },
#[error("Track sections do not exist: {track_sections:?}")]
#[editoast_error(status = 404)]
TrackSectionsNotFound { track_sections: HashSet<String> },
#[error("Operational points do not exist: {operational_points:?}")]
#[editoast_error(status = 404)]
OperationalPointsNotFound { operational_points: HashSet<String> },
#[error("Rolling stock with id {rolling_stock_id} doesn't exist")]
#[editoast_error(status = 404)]
RollingStockNotFound { rolling_stock_id: i64 },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
pub(super) struct PathResponse {
pub(super) id: i64,
pub(super) owner: uuid::Uuid,
pub(super) length: f64,
pub(super) created: DateTime<Utc>,
pub(super) slopes: Vec<Slope>,
pub(super) curves: Vec<Curve>,
#[schema(value_type = GeoJsonLineString)]
// #[derivative(Default(value = "Geometry::new(LineString(Default::default()))"))]
pub(super) geographic: Geometry,
#[schema(value_type = GeoJsonLineString)]
// #[derivative(Default(value = "Geometry::new(LineString(Default::default()))"))]
pub(super) schematic: Geometry,
pub(super) steps: Vec<PathWaypoint>,
}
impl From<Pathfinding> for PathResponse {
fn from(value: Pathfinding) -> Self {
let Pathfinding {
id,
owner,
length,
created,
slopes,
curves,
geographic,
schematic,
payload,
..
} = value;
Self {
id,
owner,
length,
created: DateTime::from_naive_utc_and_offset(created, Utc),
slopes: slopes.0,
curves: curves.0,
geographic: diesel_linestring_to_geojson(geographic),
schematic: diesel_linestring_to_geojson(schematic),
steps: payload.0.path_waypoints,
}
}
}
#[derive(Debug, Default, Deserialize, ToSchema)]
struct PathfindingRequest {
infra: i64,
steps: Vec<PathfindingStep>,
#[serde(default)]
rolling_stocks: Vec<i64>,
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone, ToSchema)]
pub struct PathfindingStep {
pub duration: f64,
pub waypoints: Vec<Waypoint>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, ToSchema)]
pub struct Waypoint {
/// A track section UUID
track_section: String,
/// The location of the waypoint on the track section
#[serde(flatten)]
location: WaypointLocation,
}
#[derive(Debug, Clone, Derivative, Serialize, Deserialize, PartialEq, ToSchema)]
#[derivative(Default)]
#[serde(rename_all = "snake_case")]
enum WaypointLocation {
/// Offset in meters from the start of the waypoint's track section
#[derivative(Default)]
Offset(f64),
/// A geographic coordinate (lon, lat)/WGS84 that will be projected onto the waypoint's track section
GeoCoordinate((f64, f64)),
}
impl Waypoint {
/// Projects the waypoint onto the tracksection and builds a bidirectional Core
/// waypoint payload
fn compute_waypoints(&self, track_map: &TrackMap) -> Vec<CoreWaypoint> {
let track = track_map.get(&self.track_section).unwrap();
let offset = match self.location {
WaypointLocation::GeoCoordinate((lon, lat)) => {
let point =
geos::Geometry::try_from(geojson::Geometry::new(geojson::Value::Point(vec![
lon, lat,
])))
.unwrap();
let normalized_offset = geos::Geometry::try_from(track.geo.clone())
.unwrap()
.project_normalized(&point)
.expect("could not compute the projection of the waypoint");
normalized_offset * track.length
}
WaypointLocation::Offset(offset) => offset,
};
let [wp, wp2] = CoreWaypoint::bidirectional(&track.id, offset);
vec![wp, wp2]
}
}
pub type TrackMap = HashMap<String, TrackSection>;
type OpMap = HashMap<String, OperationalPoint>;
/// Computes a hash map (obj_id => TrackSection) for each obj_id in an iterator
pub(in crate::views) async fn make_track_map<I: Iterator<Item = String> + Send>(
conn: &mut PgConnection,
infra_id: i64,
it: I,
) -> Result<TrackMap> {
use crate::modelsv2::prelude::*;
let ids = it.map(|id| (infra_id, id));
let track_sections: Vec<_> = TrackSectionModel::retrieve_batch_or_fail(conn, ids, |missing| {
PathfindingError::TrackSectionsNotFound {
track_sections: missing.into_iter().map(|(_, obj_id)| obj_id).collect(),
}
})
.await?;
Ok(track_sections
.into_iter()
.map(|TrackSectionModel { obj_id, schema, .. }| (obj_id, schema))
.collect())
}
async fn make_op_map<I: Iterator<Item = String> + Send>(
conn: &mut PgConnection,
infra_id: i64,
it: I,
) -> Result<OpMap> {
use crate::modelsv2::prelude::*;
let ids = it.map(|id| (infra_id, id));
let track_sections: Vec<_> =
OperationalPointModel::retrieve_batch_or_fail(conn, ids, |missing| {
PathfindingError::OperationalPointsNotFound {
operational_points: missing.into_iter().map(|(_, obj_id)| obj_id).collect(),
}
})
.await?;
Ok(track_sections
.into_iter()
.map(|OperationalPointModel { obj_id, schema, .. }| (obj_id, schema))
.collect())
}
impl PathfindingRequest {
/// Queries all track sections of the payload and builds a track hash map
async fn fetch_track_map(&self, conn: &mut PgConnection) -> Result<TrackMap> {
fetch_pathfinding_payload_track_map(conn, self.infra, &self.steps).await
}
/// Parses all payload waypoints into Core pathfinding request waypoints
fn parse_waypoints(&self, track_map: &TrackMap) -> Result<PathfindingWaypoints> {
parse_pathfinding_payload_waypoints(&self.steps, track_map)
}
/// Fetches all payload's rolling stocks
async fn parse_rolling_stocks(&self, conn: &mut PgConnection) -> Result<Vec<RollingStock>> {
use crate::modelsv2::RetrieveBatch;
let rolling_stock_batch: Vec<RollingStockModel> =
RollingStockModel::retrieve_batch_or_fail(
conn,
self.rolling_stocks.iter().copied(),
|missing| {
let first_missing_id = missing
.iter()
.next()
.expect("Retrieve batch fail without missing ids");
PathfindingError::RollingStockNotFound {
rolling_stock_id: *first_missing_id,
}
},
)
.await?;
let rolling_stocks = rolling_stock_batch
.into_iter()
.map(|rs| rs.into())
.collect();
Ok(rolling_stocks)
}
}
pub async fn fetch_pathfinding_payload_track_map(
conn: &mut PgConnection,
infra: i64,
steps: &[PathfindingStep],
) -> Result<TrackMap> {
make_track_map(
conn,
infra,
steps
.iter()
.flat_map(|step| step.waypoints.iter())
.map(|waypoint| waypoint.track_section.clone()),
)
.await
}
pub fn parse_pathfinding_payload_waypoints(
steps: &[PathfindingStep],
track_map: &TrackMap,
) -> Result<PathfindingWaypoints> {
let waypoints = steps
.iter()
.map(|step| {
step.waypoints
.iter()
.flat_map(|wp| wp.compute_waypoints(track_map))
.collect()
})
.collect();
Ok(waypoints)
}
impl PathfindingResponse {
pub async fn fetch_track_map(&self, infra: i64, conn: &mut PgConnection) -> Result<TrackMap> {
make_track_map(
conn,
infra,
self.path_waypoints
.iter()
.map(|wp| wp.location.track_section.0.clone()),
)
.await
}
pub async fn fetch_op_map(&self, infra: i64, conn: &mut PgConnection) -> Result<OpMap> {
make_op_map(
conn,
infra,
self.path_waypoints.iter().filter_map(|wp| wp.id.clone()),
)
.await
}
}
impl Pathfinding {
/// Post-processes the Core pathfinding reponse and build a [Pathfinding] model
pub fn from_core_response(
steps_duration: Vec<f64>,
response: PathfindingResponse,
track_map: &TrackMap,
op_map: &OpMap,
) -> Result<Self> {
let PathfindingResponse {
length,
geographic,
schematic,
route_paths,
path_waypoints,
slopes,
curves,
..
} = response;
let mut steps_duration = steps_duration.into_iter();
let path_waypoints = path_waypoints
.iter()
.map(|waypoint| {
let duration = if waypoint.suggestion {
0.0
} else {
steps_duration.next().unwrap()
};
let op_info = waypoint.id.as_ref().map(|op_id| {
let op = op_map.get(op_id).expect("unexpected OP id");
let name = op
.extensions
.identifier
.as_ref()
.map(|ident| ident.name.as_ref().to_owned());
let uic = op.extensions.identifier.as_ref().map(|ident| ident.uic);
let ch = op.extensions.sncf.as_ref().map(|sncf| sncf.ch.to_owned());
(name, uic, ch)
});
let (name, uic, ch) = op_info.unwrap_or_default();
let track = track_map
.get(&waypoint.location.track_section.0)
.expect("unexpected track id");
let normalized_offset = waypoint.location.offset / track.length;
let geo = geos::Geometry::try_from(&track.geo)
.unwrap()
.interpolate_normalized(normalized_offset)
.unwrap();
let sch = geos::Geometry::try_from(&track.sch)
.unwrap()
.interpolate_normalized(normalized_offset)
.unwrap();
let geo = geos::geojson::Geometry::try_from(geo).unwrap();
let sch = geos::geojson::Geometry::try_from(sch).unwrap();
PathWaypoint {
id: waypoint.id.clone(),
name,
location: waypoint.location.clone(),
duration,
path_offset: waypoint.path_offset,
suggestion: waypoint.suggestion,
geo,
sch,
uic,
ch,
}
})
.collect();
Ok(Pathfinding {
length,
payload: diesel_json::Json(PathfindingPayload {
route_paths: route_paths.to_vec(),
path_waypoints,
}),
slopes: diesel_json::Json(slopes.to_vec()),
curves: diesel_json::Json(curves.to_vec()),
geographic: geojson_to_diesel_linestring(&geographic),
schematic: geojson_to_diesel_linestring(&schematic),
..Default::default() // creation date, uuid, id, infra_id
})
}
}
/// Builds a Core pathfinding request, runs it, post-processes the response and stores it in the DB
async fn call_core_pf_and_save_result(
payload: Json<PathfindingRequest>,
db_pool: Data<DbPool>,
core: Data<CoreClient>,
update_id: Option<i64>,
) -> Result<Pathfinding> {
let conn = &mut db_pool.get().await?;
// Checks that the pf to update exists in the first place in order to fail early and avoid unnecessary core requests
if let Some(id) = update_id {
if Pathfinding::retrieve_conn(conn, id).await?.is_none() {
return Err(PathfindingError::NotFound { pathfinding_id: id }.into());
}
}
let payload = payload.into_inner();
let infra_id = payload.infra;
let infra = <Infra as RetrieveV2<_>>::retrieve_or_fail(conn, infra_id, || {
PathfindingError::InfraNotFound { infra_id }
})
.await?;
let track_map = payload.fetch_track_map(conn).await?;
let mut waypoints = payload.parse_waypoints(&track_map)?;
let mut rolling_stocks = payload.parse_rolling_stocks(conn).await?;
let mut path_request = CorePathfindingRequest::new(infra.id, infra.version, None);
path_request
.with_waypoints(&mut waypoints)
.with_rolling_stocks(&mut rolling_stocks);
let steps_duration = payload.steps.iter().map(|step| step.duration).collect();
let path_response = path_request.fetch(&core).await?;
save_core_pathfinding(path_response, conn, infra_id, update_id, steps_duration).await
}
/// Turn a core pathfinding response into a [Pathfinding] model and store it in the DB
/// If `update_id` is provided then update the corresponding path instead of creating a new one
pub async fn save_core_pathfinding(
core_response: PathfindingResponse,
conn: &mut PgConnection,
infra_id: i64,
update_id: Option<i64>,
steps_duration: Vec<f64>,
) -> Result<Pathfinding> {
let response_track_map = core_response.fetch_track_map(infra_id, conn).await?;
let response_op_map = core_response.fetch_op_map(infra_id, conn).await?;
let pathfinding = Pathfinding::from_core_response(
steps_duration,
core_response,
&response_track_map,
&response_op_map,
)?;
let changeset = PathfindingChangeset {
id: None,
infra_id: Some(infra_id),
..pathfinding.into()
};
let pathfinding: Pathfinding = if let Some(id) = update_id {
changeset
.update_conn(conn, id)
.await?
.expect("row should exist - checked earlier")
.into()
} else {
changeset.create_conn(conn).await?.into()
};
Ok(pathfinding)
}
/// Run a pathfinding between waypoints and store the resulting path in the DB
#[utoipa::path(
tag = "pathfinding",
request_body = PathfindingRequest,
responses(
(status = 201, body = PathResponse, description = "The created path")
)
)]
#[post("")]
async fn create_pf(
payload: Json<PathfindingRequest>,
db_pool: Data<DbPool>,
core: Data<CoreClient>,
) -> Result<Json<PathResponse>> {
let pathfinding = call_core_pf_and_save_result(payload, db_pool, core, None).await?;
Ok(Json(pathfinding.into()))
}
#[derive(Deserialize, utoipa::IntoParams)]
struct PathfindingIdParam {
/// A stored path ID
pathfinding_id: i64,
}
/// Updates an existing path with the result of a new pathfinding run
#[utoipa::path(
tag = "pathfinding",
request_body = PathfindingRequest,
params(PathfindingIdParam),
responses(
(status = 200, body = PathResponse, description = "The updated path"),
)
)]
#[put("")]
async fn update_pf(
params: Path<PathfindingIdParam>,
payload: Json<PathfindingRequest>,
db_pool: Data<DbPool>,
core: Data<CoreClient>,
) -> Result<Json<PathResponse>> {
let pathfinding =
call_core_pf_and_save_result(payload, db_pool, core, Some(params.pathfinding_id)).await?;
Ok(Json(pathfinding.into()))
}
/// Retrieves a stored path
#[utoipa::path(
tag = "pathfinding",
params(PathfindingIdParam),
responses(
(status = 200, body = PathResponse, description = "The requested path"),
)
)]
#[get("")]
async fn get_pf(
params: Path<PathfindingIdParam>,
db_pool: Data<DbPool>,
) -> Result<Json<PathResponse>> {
let pathfinding_id = params.pathfinding_id;
match Pathfinding::retrieve(db_pool, pathfinding_id).await? {
Some(pf) => Ok(Json(pf.into())),
None => Err(PathfindingError::NotFound { pathfinding_id }.into()),
}
}
/// Deletes a stored path
#[utoipa::path(
tag = "pathfinding",
params(PathfindingIdParam),
responses(
(status = 204, description = "The path was deleted"),
)
)]
#[delete("")]
async fn del_pf(params: Path<PathfindingIdParam>, db_pool: Data<DbPool>) -> Result<impl Responder> {
let pathfinding_id = params.pathfinding_id;
if Pathfinding::delete(db_pool, pathfinding_id).await? {
Ok(HttpResponse::NoContent())
} else {
Err(PathfindingError::NotFound { pathfinding_id }.into())
}
}
#[cfg(test)]
mod test {
use actix_http::StatusCode;
use actix_web::test::call_service;
use actix_web::test::TestRequest;
use serde_json::json;
use crate::assert_response_error_type_match;
use crate::assert_status_and_read;
use crate::core::mocking::MockingClient;
use crate::fixtures::tests::db_pool;
use crate::fixtures::tests::empty_infra;
use crate::fixtures::tests::named_fast_rolling_stock;
use crate::fixtures::tests::pathfinding;
use crate::fixtures::tests::small_infra;
use crate::fixtures::tests::TestFixture;
use crate::models::Pathfinding;
use crate::models::Retrieve;
use crate::modelsv2::Infra;
use crate::views::pathfinding::PathResponse;
use crate::views::pathfinding::PathfindingError;
use crate::views::tests::create_test_service;
use crate::views::tests::create_test_service_with_core_client;
#[rstest::rstest]
async fn test_get_pf(#[future] pathfinding: TestFixture<Pathfinding>) {
let pf = &pathfinding.await.model;
let app = create_test_service().await;
let req = TestRequest::get()
.uri(&format!("/pathfinding/{}", pf.id))
.to_request();
let response = call_service(&app, req).await;
let response: PathResponse = assert_status_and_read!(response, StatusCode::OK);
let expected_response = PathResponse::from(pf.clone());
assert_eq!(response, expected_response);
}
#[actix_web::test]
async fn test_get_not_found() {
let app = create_test_service().await;
let req = TestRequest::get().uri("/pathfinding/666").to_request();
let response = call_service(&app, req).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[rstest::rstest]
async fn test_delete_pf(#[future] pathfinding: TestFixture<Pathfinding>) {
let pf = &pathfinding.await.model;
let app = create_test_service().await;
let req = TestRequest::delete().uri(&format!("/pathfinding/{}", pf.id));
let response = call_service(&app, req.to_request()).await;
assert_eq!(response.status(), StatusCode::NO_CONTENT);
let req = TestRequest::delete().uri(&format!("/pathfinding/{}", pf.id));
let response = call_service(&app, req.to_request()).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[actix_web::test]
async fn test_delete_not_found() {
let app = create_test_service().await;
let req = TestRequest::delete().uri("/pathfinding/666").to_request();
let response = call_service(&app, req).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[rstest::rstest]
async fn test_post_ok() {
// GIVEN
// Avoid `Drop`ping the fixture
let rs = &named_fast_rolling_stock("fast_rolling_stock_test_post_ok", db_pool())
.await
.model;
let infra = small_infra(db_pool()).await;
let mut payload: serde_json::Value = serde_json::from_str(include_str!(
"../../tests/small_infra/pathfinding_post_payload.json"
))
.unwrap();
*payload.get_mut("infra").unwrap() = json!(infra.id);
*payload.get_mut("rolling_stocks").unwrap() = json!([rs.id]);
let mut core = MockingClient::new();
core.stub("/pathfinding/routes")
.method(reqwest::Method::POST)
.response(StatusCode::OK)
.body(include_str!(
"../../tests/small_infra/pathfinding_core_response.json"
))
.finish();
let app = create_test_service_with_core_client(core).await;
let req = TestRequest::post()
.uri("/pathfinding")
.set_json(payload)
.to_request();
// WHEN
let response = call_service(&app, req).await;
// THEN
let response: PathResponse = assert_status_and_read!(response, StatusCode::OK);
assert!(Pathfinding::retrieve(db_pool(), response.id).await.is_ok());
}
#[rstest::rstest]
async fn test_multiple_waypoints_ok() {
// GIVEN
// Avoid `Drop`ping the fixture
let rs =
&named_fast_rolling_stock("fast_rolling_stock_test_multiple_waypoints_ok", db_pool())
.await
.model;
let infra = small_infra(db_pool()).await;
let mut payload: serde_json::Value = serde_json::from_str(include_str!(
"../../tests/small_infra/pathfinding_post_multiple_waypoints_payload.json"
))
.unwrap();
*payload.get_mut("infra").unwrap() = json!(infra.id);
*payload.get_mut("rolling_stocks").unwrap() = json!([rs.id]);
let mut core = MockingClient::new();
core.stub("/pathfinding/routes")
.method(reqwest::Method::POST)
.response(StatusCode::OK)
.body(include_str!(
"../../tests/small_infra/pathfinding_core_response.json"
))
.finish();
let app = create_test_service_with_core_client(core).await;
let req = TestRequest::post()
.uri("/pathfinding")
.set_json(payload)
.to_request();
// WHEN
let response = call_service(&app, req).await;
// THEN
let response: PathResponse = assert_status_and_read!(response, StatusCode::OK);
assert!(Pathfinding::retrieve(db_pool(), response.id).await.is_ok());
}
#[rstest::rstest]
async fn test_infra_not_found() {
let payload: serde_json::Value = serde_json::from_str(include_str!(
"../../tests/small_infra/pathfinding_post_payload.json"
))
.unwrap();
let app = create_test_service().await;
let req = TestRequest::post()
.uri("/pathfinding")
.set_json(payload)
.to_request();
let response = call_service(&app, req).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_response_error_type_match!(
response,
PathfindingError::InfraNotFound { infra_id: 0 }
);
}
#[rstest::rstest]
async fn test_rolling_stock_not_found(#[future] small_infra: TestFixture<Infra>) {
let infra = small_infra.await;
let mut payload: serde_json::Value = serde_json::from_str(include_str!(
"../../tests/small_infra/pathfinding_post_payload.json"
))
.unwrap();
*payload.get_mut("infra").unwrap() = json!(infra.id);
let app = create_test_service().await;
let req = TestRequest::post()
.uri("/pathfinding")
.set_json(payload)
.to_request();
let response = call_service(&app, req).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_response_error_type_match!(
response,
PathfindingError::RollingStockNotFound {
rolling_stock_id: 0
}
);
}
#[rstest::rstest]
async fn test_track_section_not_found(#[future] empty_infra: TestFixture<Infra>) {
let infra = empty_infra.await;
let mut payload: serde_json::Value = serde_json::from_str(include_str!(
"../../tests/small_infra/pathfinding_post_payload.json"
))
.unwrap();
*payload.get_mut("infra").unwrap() = json!(infra.id);
let app = create_test_service().await;
let req = TestRequest::post()
.uri("/pathfinding")
.set_json(payload)
.to_request();
let response = call_service(&app, req).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_response_error_type_match!(
response,
PathfindingError::TrackSectionsNotFound {
track_sections: Default::default()
}
);
}
}