我在我的网络爬虫中使用 Reqwest,我正在尝试为主循环添加测试以确保我得到正确的输出。我正在尝试将 Iron 用于带有预设响应的假 HTTP 服务器。但是,在我的main_loop
函数中,let client = Client::new();
是挂起的。
的前几行_main_loop
:
fn _main_loop(starton: String, panic: bool) {
//panic("test") // calls as normal
let client = Client::new(); // <-- problem!
panic("test") // doesn't call
let mut future_urls: Vec<String>;
// ...
}
我的测试mod
:
#[cfg(test)]
mod tests {
use iron::{Iron, IronResult, Headers};
use iron::response::Response;
use iron::request::Request;
use iron::status;
use iron::middleware::Chain;
use iron::headers::ContentType;
use iron::mime::{Mime, TopLevel, SubLevel};
use iron::typemap::TypeMap;
use std;
use *;
#[test]
fn __main_loop() {
fn handler(req: &mut Request) -> IronResult<Response> {
let mut mime = Headers::new();
mime.set(ContentType(Mime(TopLevel::Text, SubLevel::Html, Vec::new())));
Ok(Response {
headers: mime,
status: Some(status::Ok),
body: Some(Box::new(match req.url.path().join("/").as_str() {
"" => "<a href='file'></a><a href='file1'></a>",
"file" => "<a href='/file1'></a>",
"file1" => "<a href='/file'></a>",
_ => "not found"
})),
extensions: TypeMap::new()
})
}
let child = std::thread::spawn(|| Iron::new(Chain::new(handler)).http("localhost:9999").unwrap());
let f: Vec<String> = Vec::new();
assert_eq!(_main_loop("http://localhost:9999/".to_string(), false), f);
}
}
终端输出:
$ cargo test
Compiling crawler v1.0.0 (file:///home/*******/crawler)
warning: unreachable statement
--> src/main.rs:82:5
|
82 | let mut future_urls: Vec<String>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unreachable_code)] on by default
warning: unused variable: `client`
--> src/main.rs:80:9
|
80 | let client = Client::new();
| ^^^^^^ help: consider using `_client` instead
|
= note: #[warn(unused_variables)] on by default
warning: unused variable: `starton`
--> src/main.rs:79:15
|
79 | fn _main_loop(starton: String, _panic: bool) -> Vec<String> {
| ^^^^^^^ help: consider using `_starton` instead
warning: unused variable: `child`
--> src/main.rs:239:13
|
239 | let child = std::thread::spawn(|| Iron::new(Chain::new(handler)).http("localhost:9999").unwrap());
| ^^^^^ help: consider using `_child` instead
Finished dev [unoptimized + debuginfo] target(s) in 4.24 secs
Running target/debug/deps/crawler-9c5de394eb85849d
running 9 tests
test html::tests::_get_attribute_for_elem ... ok
test html::tests::_html_token_sink ... ok
test url_utils::tests::_add_url_to_vec ... ok
test url_utils::tests::_get_root_domain ... ok
test html::tests::_find_urls_in_html ... ok
test url_utils::tests::_check_if_is_in_url_list ... ok
test url_utils::tests::_remove_get_params ... ok
test url_utils::tests::_repair_suggested_url ... ok
运行测试单线程 ( -- --test-threads 1
) 时,它以 . 结尾test tests::__main_loop ...
。