Checked json data.

This commit is contained in:
Jeff Baskin 2025-05-04 08:18:55 -04:00
parent ce3400e353
commit cb7526dd45
2 changed files with 59 additions and 24 deletions

View File

@ -70,9 +70,14 @@ impl Document {
return; return;
} }
}; };
self.data let reply = match doc["template"].as_str() {
.insert(name, doc["template"].as_str().unwrap().to_string()); Some(content) => {
self.queue.send(msg.reply(MsgType::ActionOk)).unwrap(); self.data.insert(name, content.to_string());
msg.reply(MsgType::ActionOk)
}
None => msg.reply_with_error(ErrorType::DocumentInvalidRequest),
};
self.queue.send(reply).unwrap();
} }
fn get(&self, msg: Message) { fn get(&self, msg: Message) {
@ -245,27 +250,36 @@ pub mod documents {
#[test] #[test]
fn invalid_json() { fn invalid_json() {
let (queue, rx) = setup_document(); let inputs = ["Invalid json request.", "{}"];
let mut msg = Message::new(MsgType::DocumentRequest); for input in inputs.into_iter() {
msg.add_data("action", ActionType::Add); let (queue, rx) = setup_document();
msg.add_data("name", "doc"); let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("doc", "Invalid json request."); msg.add_data("action", ActionType::Add);
queue.send(msg.clone()).unwrap(); msg.add_data("name", "doc");
let reply = rx.recv_timeout(TIMEOUT).unwrap(); msg.add_data("doc", input);
assert_eq!(reply.get_id(), msg.get_id()); queue.send(msg.clone()).unwrap();
match reply.get_msg_type() { let reply = match rx.recv_timeout(TIMEOUT) {
MsgType::Error => {} Ok(data) => data,
_ => unreachable!( Err(err) => {
"got '{:?}': should have received document", assert!(false, "got '{}' with the following json: '{}'", err, input);
reply.get_msg_type() Message::new(MsgType::Error)
), }
} };
match reply.get_data("error_type") { assert_eq!(reply.get_id(), msg.get_id());
Some(err) => match err.to_error_type().unwrap() { match reply.get_msg_type() {
ErrorType::DocumentInvalidRequest => {} MsgType::Error => {}
_ => unreachable!("got {:?}: should have been bad request'", err), _ => unreachable!(
}, "got '{:?}': should have received document",
None => unreachable!("should contain error type"), reply.get_msg_type()
),
}
match reply.get_data("error_type") {
Some(err) => match err.to_error_type().unwrap() {
ErrorType::DocumentInvalidRequest => {}
_ => unreachable!("got {:?}: should have been bad request'", err),
},
None => unreachable!("should contain error type"),
}
} }
} }
} }

View File

@ -284,4 +284,25 @@ mod servers {
"do not allow post to existing documents" "do not allow post to existing documents"
); );
} }
#[tokio::test]
async fn post_with_missing_document() {
let app = create_app(MoreThanText::new()).await;
let response = app
.clone()
.oneshot(
Request::builder()
.method(Method::POST)
.uri("/api/something")
.body("{}".to_string())
.unwrap(),
)
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::BAD_REQUEST,
"do not allow post to existing documents"
);
}
} }