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
|
use std::{
env::args,
io::{stdin, stdout, IsTerminal},
};
use actix_web::{
get, http::header::ContentType, post, web, App, HttpResponse, HttpServer, Responder,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
struct Registration {
url: String,
}
trait IdGenerator {
fn next_id(&self) -> String;
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
enum RegistrationResult {
Success(RegistrationSuccess),
Failure(RegistrationFailure),
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
struct RegistrationSuccess {
id: String,
url: String,
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
enum RegistrationFailure {
UrlAlreadyRegistered { url: String },
}
#[post("/register")]
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(&RegistrationResult::Success(success)).unwrap())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(register))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
#[cfg(test)]
mod app_tests {
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_returns_success_with_unique_id() {
let id = "0123456789abcdef0123456789abcdef".to_string();
let id_generator: Arc<dyn IdGenerator> = Arc::new(ConstantIdGenerator::new(id.clone()));
// FIXME should only be called once, move to setup
// env_logger::init();
let app = test::init_service(
App::new()
.wrap(Logger::default())
.app_data(web::Data::from(id_generator))
.service(register),
)
.await;
let url = "http://192.168.1.1".to_string();
let req = test::TestRequest::post()
.uri("/register")
.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!(
RegistrationResult::Success(RegistrationSuccess { id, url }),
serde_json::from_slice(&bytes.unwrap()).unwrap()
);
}
#[actix_web::test]
async fn post_registration_fails_given_url_is_already_registered() {
let id = "0123456789abcdef0123456789abcdef".to_string();
let id_generator: Arc<dyn IdGenerator> = Arc::new(ConstantIdGenerator::new(id.clone()));
let app = test::init_service(
App::new()
.wrap(Logger::default())
.app_data(web::Data::from(id_generator))
.service(register),
)
.await;
let url = "http://192.168.1.1".to_string();
let _ = test::TestRequest::post()
.uri("/register")
.set_json(Registration { url: url.clone() })
.insert_header(ContentType::json())
.to_request();
// second request with the same URL
let req = test::TestRequest::post()
.uri("/register")
.set_json(Registration { url: url.clone() })
.insert_header(ContentType::json())
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_client_error());
let body = resp.into_body();
let bytes = body::to_bytes(body).await;
assert_eq!(
RegistrationResult::Failure(RegistrationFailure::UrlAlreadyRegistered { url }),
serde_json::from_slice(&bytes.unwrap()).unwrap()
);
}
}
|