summaryrefslogtreecommitdiff
path: root/rust/src/web.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rust/src/web.rs')
-rw-r--r--rust/src/web.rs68
1 files changed, 58 insertions, 10 deletions
diff --git a/rust/src/web.rs b/rust/src/web.rs
index 2614c06..9c1b2c2 100644
--- a/rust/src/web.rs
+++ b/rust/src/web.rs
@@ -13,11 +13,34 @@ struct Registration {
url: String,
}
+trait IdGenerator {
+ fn next_id(&self) -> String;
+}
+
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
+enum RegistrationResult {
+ Success(RegistrationSuccess),
+}
+
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
+struct RegistrationSuccess {
+ id: String,
+ url: String,
+}
+
#[post("/register")]
-async fn register(registration: web::Json<Registration>) -> impl Responder {
+async fn register(
+ id_gen: web::Data<dyn IdGenerator>,
+ registration: web::Json<Registration>,
+) -> impl Responder {
+ let id = id_gen.next_id();
+ let success = RegistrationSuccess {
+ id,
+ url: registration.url.clone(),
+ };
HttpResponse::Ok()
.content_type(ContentType::json())
- .body(serde_json::to_string(&registration).unwrap())
+ .body(serde_json::to_string(&RegistrationResult::Success(success)).unwrap())
}
#[actix_web::main]
@@ -30,27 +53,52 @@ async fn main() -> std::io::Result<()> {
#[cfg(test)]
mod app_tests {
- use actix_web::{body, http::header::ContentType, test, App};
+ use std::sync::Arc;
+
+ use actix_web::{body, http::header::ContentType, middleware::Logger, test, App};
use super::*;
+ struct ConstantIdGenerator {
+ id: String,
+ }
+
+ impl ConstantIdGenerator {
+ fn new(id: String) -> Self {
+ Self { id }
+ }
+ }
+
+ impl IdGenerator for ConstantIdGenerator {
+ fn next_id(&self) -> String {
+ self.id.clone()
+ }
+ }
+
#[actix_web::test]
- async fn post_registration_echoes_back_registration_data_with_unique_id() {
- let app = test::init_service(App::new().service(register)).await;
- let registration = Registration {
- url: "http://192.168.1.1".to_string(),
- };
+ async fn post_registration_returns_success_with_unique_id() {
+ let id = "0123456789abcdef0123456789abcdef".to_string();
+ let id_generator: Arc<dyn IdGenerator> = Arc::new(ConstantIdGenerator::new(id.clone()));
+ env_logger::init();
+ let logger = Logger::default();
+ let data = web::Data::from(id_generator);
+ let app =
+ test::init_service(App::new().wrap(logger).app_data(data).service(register)).await;
+ let url = "http://192.168.1.1".to_string();
let req = test::TestRequest::post()
.uri("/register")
- .set_json(registration.clone())
+ .set_json(Registration { url: url.clone() })
.insert_header(ContentType::json())
.to_request();
+
let resp = test::call_service(&app, req).await;
+
assert!(resp.status().is_success());
+
let body = resp.into_body();
let bytes = body::to_bytes(body).await;
assert_eq!(
- registration,
+ RegistrationResult::Success(RegistrationSuccess { id, url }),
serde_json::from_slice(&bytes.unwrap()).unwrap()
);
}