-
Notifications
You must be signed in to change notification settings - Fork 14
/
tests.rs
294 lines (270 loc) · 8.98 KB
/
tests.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
use crate::contexts::SimpleContext;
use crate::contexts::SimpleSession;
use crate::datasets::listing::Provenance;
use crate::datasets::storage::AddDataset;
use crate::datasets::storage::DatasetStore;
use crate::datasets::upload::UploadId;
use crate::datasets::upload::UploadRootPath;
use crate::handlers::ErrorResponse;
use crate::projects::{
CreateProject, Layer, LayerUpdate, ProjectDb, ProjectId, RasterSymbology, STRectangle,
Symbology, UpdateProject,
};
use crate::server::{configure_extractors, render_404, render_405};
use crate::util::user_input::UserInput;
use crate::util::Identifier;
use crate::workflows::registry::WorkflowRegistry;
use crate::workflows::workflow::{Workflow, WorkflowId};
use crate::{
contexts::{Context, InMemoryContext},
datasets::storage::{DatasetDefinition, MetaDataDefinition},
handlers,
};
use actix_web::dev::ServiceResponse;
use actix_web::{http, http::header, http::Method, middleware, test, web, App};
use flexi_logger::Logger;
use geoengine_datatypes::dataset::DatasetId;
use geoengine_datatypes::operations::image::Colorizer;
use geoengine_datatypes::spatial_reference::SpatialReferenceOption;
use geoengine_operators::engine::{RasterOperator, TypedOperator};
use geoengine_operators::source::{GdalSource, GdalSourceParameters};
use geoengine_operators::util::gdal::create_ndvi_meta_data;
use std::io::Write;
use std::path::PathBuf;
#[allow(clippy::missing_panics_doc)]
pub async fn create_project_helper<C: SimpleContext>(ctx: &C) -> (SimpleSession, ProjectId) {
let session = ctx.default_session_ref().await;
let project = ctx
.project_db()
.write()
.await
.create(
&session,
CreateProject {
name: "Test".to_string(),
description: "Foo".to_string(),
bounds: STRectangle::new(
SpatialReferenceOption::Unreferenced,
0.,
0.,
1.,
1.,
0,
1,
)
.unwrap(),
time_step: None,
}
.validated()
.unwrap(),
)
.await
.unwrap();
(session.clone(), project)
}
pub fn update_project_helper(project: ProjectId) -> UpdateProject {
UpdateProject {
id: project,
name: Some("TestUpdate".to_string()),
description: None,
layers: Some(vec![LayerUpdate::UpdateOrInsert(Layer {
workflow: WorkflowId::new(),
name: "L1".to_string(),
visibility: Default::default(),
symbology: Symbology::Raster(RasterSymbology {
opacity: 1.0,
colorizer: Colorizer::Rgba,
}),
})]),
plots: None,
bounds: None,
time_step: None,
}
}
#[allow(clippy::missing_panics_doc)]
pub async fn register_ndvi_workflow_helper(ctx: &InMemoryContext) -> (Workflow, WorkflowId) {
let dataset = add_ndvi_to_datasets(ctx).await;
let workflow = Workflow {
operator: TypedOperator::Raster(
GdalSource {
params: GdalSourceParameters { dataset },
}
.boxed(),
),
};
let id = ctx
.workflow_registry()
.write()
.await
.register(workflow.clone())
.await
.unwrap();
(workflow, id)
}
pub async fn add_ndvi_to_datasets(ctx: &InMemoryContext) -> DatasetId {
let ndvi = DatasetDefinition {
properties: AddDataset {
id: None,
name: "NDVI".to_string(),
description: "NDVI data from MODIS".to_string(),
source_operator: "GdalSource".to_string(),
symbology: None,
provenance: Some(Provenance {
citation: "Sample Citation".to_owned(),
license: "Sample License".to_owned(),
uri: "http://example.org/".to_owned(),
}),
},
meta_data: MetaDataDefinition::GdalMetaDataRegular(create_ndvi_meta_data()),
};
ctx.dataset_db_ref_mut()
.await
.add_dataset(
&SimpleSession::default(),
ndvi.properties
.validated()
.expect("valid dataset description"),
Box::new(ndvi.meta_data),
)
.await
.expect("dataset db access")
}
pub async fn check_allowed_http_methods2<T, TRes, P, PParam>(
test_helper: T,
allowed_methods: &[Method],
projector: P,
) where
T: Fn(Method) -> TRes,
TRes: futures::Future<Output = PParam>,
P: Fn(PParam) -> ServiceResponse,
{
const HTTP_METHODS: [Method; 9] = [
Method::GET,
Method::HEAD,
Method::POST,
Method::PUT,
Method::DELETE,
Method::CONNECT,
Method::OPTIONS,
Method::TRACE,
Method::PATCH,
];
for method in HTTP_METHODS {
if !allowed_methods.contains(&method) {
let res = test_helper(method).await;
let res = projector(res);
ErrorResponse::assert(res, 405, "MethodNotAllowed", "HTTP method not allowed.").await;
}
}
}
pub fn check_allowed_http_methods<'a, T, TRes>(
test_helper: T,
allowed_methods: &'a [Method],
) -> impl futures::Future + 'a
where
T: Fn(Method) -> TRes + 'a,
TRes: futures::Future<Output = ServiceResponse> + 'a,
{
check_allowed_http_methods2(test_helper, allowed_methods, |res| res)
}
pub async fn send_test_request<C: SimpleContext>(
req: test::TestRequest,
ctx: C,
) -> ServiceResponse {
let app = test::init_service(
App::new()
.app_data(web::Data::new(ctx))
.wrap(
middleware::ErrorHandlers::default()
.handler(http::StatusCode::NOT_FOUND, render_404)
.handler(http::StatusCode::METHOD_NOT_ALLOWED, render_405),
)
.wrap(middleware::NormalizePath::trim())
.configure(configure_extractors)
.configure(handlers::datasets::init_dataset_routes::<C>)
.configure(handlers::plots::init_plot_routes::<C>)
.configure(handlers::projects::init_project_routes::<C>)
.configure(handlers::session::init_session_routes::<C>)
.configure(handlers::spatial_references::init_spatial_reference_routes::<C>)
.configure(handlers::upload::init_upload_routes::<C>)
.configure(handlers::wcs::init_wcs_routes::<C>)
.configure(handlers::wfs::init_wfs_routes::<C>)
.configure(handlers::wms::init_wms_routes::<C>)
.configure(handlers::workflows::init_workflow_routes::<C>),
)
.await;
test::call_service(&app, req.to_request())
.await
.map_into_boxed_body()
}
pub async fn read_body_string(res: ServiceResponse) -> String {
let body = test::read_body(res).await;
String::from_utf8(body.to_vec()).expect("Body is utf 8 string")
}
/// Helper struct that removes all specified uploads on drop
#[derive(Default)]
pub struct TestDataUploads {
pub uploads: Vec<UploadId>,
}
impl Drop for TestDataUploads {
fn drop(&mut self) {
for upload in &self.uploads {
if let Ok(path) = upload.root_path() {
let _res = std::fs::remove_dir_all(path);
}
}
}
}
/// Initialize a basic logger within tests.
/// You should only use this for debugging.
///
/// # Panics
/// This function will panic if the logger cannot be initialized.
///
pub fn initialize_debugging_in_test() {
Logger::try_with_str("debug").unwrap().start().unwrap();
}
pub trait SetMultipartBody {
#[must_use]
fn set_multipart<B: Into<Vec<u8>>>(self, parts: Vec<(&str, B)>) -> Self;
#[must_use]
fn set_multipart_files(self, file_paths: &[PathBuf]) -> Self
where
Self: Sized,
{
self.set_multipart(
file_paths
.iter()
.map(|o| {
(
o.file_name().unwrap().to_str().unwrap(),
std::fs::read(o).unwrap(),
)
})
.collect(),
)
}
}
impl SetMultipartBody for test::TestRequest {
fn set_multipart<B: Into<Vec<u8>>>(self, parts: Vec<(&str, B)>) -> Self {
let mut body: Vec<u8> = Vec::new();
for (file_name, content) in parts {
write!(body, "--10196671711503402186283068890\r\n").unwrap();
write!(
body,
"Content-Disposition: form-data; name=\"files[]\"; filename=\"{}\"\r\n\r\n",
file_name
)
.unwrap();
body.append(&mut content.into());
write!(body, "\r\n").unwrap();
}
write!(body, "--10196671711503402186283068890--\r\n").unwrap();
self.append_header((header::CONTENT_LENGTH, body.len()))
.append_header((
header::CONTENT_TYPE,
"multipart/form-data; boundary=10196671711503402186283068890",
))
.set_payload(body)
}
}