我试图为我的火箭应用程序的3条路线写一些单元测试。到目前为止,get index
函数工作正常,但两个post请求不工作
我越来越困惑,因为我一直得到一个404请求,我真的不知道为什么
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代码省略空间的原因):
#[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])
}
任何帮助都会很好:)
1条答案
按热度按时间dnph8jn41#
您需要传入的不仅仅是端点。Client结构的get方法期望整个url作为字符串传递,而不仅仅是端点。如果您试图向本地运行在端口8000上的服务器的“apples”端点发出get请求,并将结果响应保存在名为response的变量中,则该请求看起来如下所示:
然后,要Assert状态代码为OK(200):
您收到404的原因是因为您正在向没有主机的端点发出请求,例如。“/apples”而不是“http://127.0.0.1:8000“,并且因为该端点上没有任何内容,所以超时后返回404。