Im trying to write some unit tests for the 3 routes of my Rocket app. So far the get index
function works fine but the two post requests arent working
Im getting confused because i keep getting a 404 request and i don't really know why
tests.rs:
use super::rocket;
use rocket::local::blocking::Client;
use rocket::http::Status;
use rocket::uri;
#[test]
fn index() {
let client = Client::tracked(rocket()).expect("valid rocket instance");
let response = client.get(uri!(super::index)).dispatch();
assert_eq!(response.status(), Status::Ok);
}
#[test]
fn add() {
let client = Client::tracked(rocket()).expect("valid rocket instance");
let response = client.post(uri!(super::add))
.body("note=This is a test")
.dispatch();
assert_eq!(response.status(), Status::Ok);
}
#[test]
fn delete() {
let client = Client::tracked(rocket()).expect("valid rocket instance");
let response = client.post(uri!(super::delete))
.body("noteid=1")
.dispatch();
assert_eq!(response.status(), Status::Ok);
}
main.rs (some code omitted for space reasons):
#[cfg(test)] mod tests;
use curl::easy::{Easy, List};
use rocket::form::Form;
use rocket::response::content::RawHtml;
use rocket::response::Redirect;
use rocket::{response::content::RawCss, *};
use rocket_dyn_templates::tera;
use rusqlite::{Connection, Result};
use std::io::Read;
#[derive(FromForm)]
struct NoteForm {
note: String,
}
#[derive(Debug)]
struct Note {
id: i32,
note: String,
}
#[derive(FromForm)]
struct NoteID {
noteid: i32,
}
#[get("/")]
fn index() -> RawHtml<String> {
let mut html: String = r#"
<link rel="stylesheet" href="style.css">
<h1>Rust Notebook</h1>
<form method='POST' action='/add'>
<label>Note: <input name='note' value=''></label>
<button>Add</button>
</form>
<ul class='notes'>"#
.to_owned();
let notes = get_notes().unwrap();
for note in notes {
let noteid: String = note.id.to_string();
html += "<li class='notes'>";
html += &tera::escape_html(¬e.note);
html += "<form method='POST' action='/delete'> <button name='noteid' value='";
html += ¬eid;
html += "' style='float: right;'>Delete</button></form></li>";
}
html += "</ul>";
RawHtml(html)
}
#[post("/delete", data = "<noteid>")]
fn delete(noteid: Form<NoteID>) -> Redirect {
let conn = Connection::open("notes.db").unwrap();
conn.execute(
"DELETE FROM notes WHERE rowid = ?",
&[noteid.noteid.to_string().as_str()],
)
.unwrap();
Redirect::to("/")
}
#[post("/add", data = "<note>")]
fn add(note: Form<NoteForm>) -> Redirect {
let conn = Connection::open("notes.db").unwrap();
conn.execute("INSERT INTO notes (note) VALUES (?)", &[note.note.as_str()])
.unwrap();
log_notes(¬e.note.as_str());
Redirect::to("/")
}
#[launch]
fn rocket() -> _ {
sqlite();
rocket::build().mount("/", routes![index, add, serve_css, delete])
}
any help would be great :)