Skip to content
Snippets Groups Projects
Commit ccda501f authored by Michael Hauspie's avatar Michael Hauspie
Browse files

Initial commit with 'Plus' operation

parents
No related branches found
No related tags found
No related merge requests found
/target
This diff is collapsed.
[package]
name = "webcalc-rs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = { version = "0.5.0", features = ["json"] }
serde = { version = "1.0.197", features = ["derive"]}
use rocket::{get, launch, post, routes, serde::json::Json};
use serde::{Deserialize, Serialize};
const INDEX_TEXT: &str = r#"\
Cette application permet d'executer des calculs simple.
Pour l'utiliser, il faut envoyer le calcul à effectuer sous la forme d'un objet json dans une requete POST sur '/'
Le format à utiliser est un objet json qui a un attribu étant le nom
de l'operation à effectuer, dont la valeur est un tableau d'opérande
de taille 2
Exemple:
{
"Plus": [3, 4]
}
L'application retourne un résultat au format json avec le résultat (nombre) et l'opération effectuée (chaîne)
Exemple:
{
"operation": "3 + 4",
"resultat": 7,
}
Pour envoyer une requête avec curl:
curl -X POST http://monurl -H 'Content-Type: application/json' -d '{"Plus", [3, 4]}'
"#;
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
enum Operation {
Plus(i32,i32),
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
struct OperationResult {
operation: String,
resultat: i32,
}
#[get("/")]
fn index() -> &'static str {
INDEX_TEXT
}
#[post("/", data = "<operation>")]
fn do_calc(operation: Json<Operation>) -> Json<OperationResult> {
match operation.into_inner() {
Operation::Plus(op1, op2) => OperationResult {
operation: format!("{op1} + {op2}"),
resultat: op1 + op2,
}.into()
}
}
#[get("/test")]
fn test() -> Json<Operation> {
let t = Operation::Plus(1, 3);
t.into()
}
#[launch]
fn launch() -> _ {
rocket::build().mount("/", routes![index, do_calc, test])
}
#[cfg(test)]
mod tests {
use rocket::local::blocking::Client;
use rocket::http::Status;
use rocket::uri;
use super::*;
#[test]
fn index() {
let client = Client::tracked(launch()).expect("valid rocket instance");
let response = client.get(uri!(index)).dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.into_string().unwrap(), super::INDEX_TEXT);
}
#[test]
fn plus() {
let client = Client::tracked(launch()).expect("valid rocket instance");
let operation = Operation::Plus(3, 8);
let req = client.post(uri!(super::index)).json(&operation);
let response = req.dispatch();
assert_eq!(response.status(), Status::Ok);
let expected = OperationResult {
operation: "3 + 8".into(),
resultat: 11,
};
assert_eq!(response.into_json::<OperationResult>().unwrap(), expected);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment