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;
}
};
self.data
.insert(name, doc["template"].as_str().unwrap().to_string());
self.queue.send(msg.reply(MsgType::ActionOk)).unwrap();
let reply = match doc["template"].as_str() {
Some(content) => {
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) {
@ -245,27 +250,36 @@ pub mod documents {
#[test]
fn invalid_json() {
let (queue, rx) = setup_document();
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("action", ActionType::Add);
msg.add_data("name", "doc");
msg.add_data("doc", "Invalid json request.");
queue.send(msg.clone()).unwrap();
let reply = rx.recv_timeout(TIMEOUT).unwrap();
assert_eq!(reply.get_id(), msg.get_id());
match reply.get_msg_type() {
MsgType::Error => {}
_ => unreachable!(
"got '{:?}': should have received document",
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"),
let inputs = ["Invalid json request.", "{}"];
for input in inputs.into_iter() {
let (queue, rx) = setup_document();
let mut msg = Message::new(MsgType::DocumentRequest);
msg.add_data("action", ActionType::Add);
msg.add_data("name", "doc");
msg.add_data("doc", input);
queue.send(msg.clone()).unwrap();
let reply = match rx.recv_timeout(TIMEOUT) {
Ok(data) => data,
Err(err) => {
assert!(false, "got '{}' with the following json: '{}'", err, input);
Message::new(MsgType::Error)
}
};
assert_eq!(reply.get_id(), msg.get_id());
match reply.get_msg_type() {
MsgType::Error => {}
_ => unreachable!(
"got '{:?}': should have received document",
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"
);
}
#[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"
);
}
}