98 lines
2.6 KiB
Rust
98 lines
2.6 KiB
Rust
use http::Method;
|
|
use http::StatusCode;
|
|
use raspa::request::{Request, RequestBase};
|
|
use raspa::selector::{Selector, SelectorBase};
|
|
use serde_json::Value;
|
|
|
|
#[test]
|
|
fn plain_text_selector() {
|
|
let html = "
|
|
<html>
|
|
<body>
|
|
<h1>hello world</h1>
|
|
<p id='text'>good bye</p>
|
|
<a>simple text</a>
|
|
</body>
|
|
</html>
|
|
"
|
|
.to_string();
|
|
let sel = Selector::from_html(html);
|
|
assert_eq!(sel.css::<Selector>("h1")[0].html(), "<h1>hello world</h1>");
|
|
assert_eq!(sel.css::<Selector>("#text")[0].content(), "good bye");
|
|
assert_eq!(
|
|
sel.css_once::<Selector>("body > a").unwrap().content(),
|
|
"simple text"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn simple_request() {
|
|
let req: Request = RequestBase::new("https://httpbin.org/").unwrap();
|
|
let resp = req.launch();
|
|
assert_eq!(resp.status_code, StatusCode::OK);
|
|
assert!(resp.css::<Selector>("h2")[0].html().contains("httpbin.org"));
|
|
}
|
|
|
|
#[test]
|
|
fn complex_selectors() {
|
|
let html = "
|
|
<html>
|
|
<body>
|
|
<p id='text'>good bye</p>
|
|
<a href='http://google.com'>simple text</a>
|
|
<ul>
|
|
<li class='item' id='item-1'>1</li>
|
|
<li class='item' id='item-2'>2</li>
|
|
<li class='item' id='item-3'>3</li>
|
|
</ul>
|
|
<div>
|
|
<a href='#'>non link</a>
|
|
<a href='http://localhost'>link</a>
|
|
<a href='#'>non link</a>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
"
|
|
.to_string();
|
|
let sel = Selector::from_html(html);
|
|
assert_eq!(
|
|
sel.css_once::<Selector>("p").unwrap().attr("id").unwrap(),
|
|
"text"
|
|
);
|
|
assert_eq!(
|
|
sel.css::<Selector>("a")[0].attr("href").unwrap(),
|
|
"http://google.com"
|
|
);
|
|
for node in sel.css::<Selector>("ul li").iter() {
|
|
let text = node.content();
|
|
assert_eq!(node.attr("class").unwrap(), "item");
|
|
assert!(node.attr("id").unwrap().contains(&text));
|
|
}
|
|
|
|
let div = sel.css_once::<Selector>("div").unwrap();
|
|
for node in div.css::<Selector>("a").iter() {
|
|
if node.attr("href").unwrap() == "#" {
|
|
assert_eq!(node.content(), "non link");
|
|
} else {
|
|
assert_eq!(node.content(), "link");
|
|
}
|
|
}
|
|
assert!(sel.css_once::<Selector>("h1").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn simple_json_test() {
|
|
let req = Request::new("https://httpbin.org/json").unwrap();
|
|
let resp: Value = req.launch().to_json().expect("cannot parse json");
|
|
|
|
assert_eq!(resp["slideshow"]["title"], "Sample Slide Show");
|
|
}
|
|
|
|
#[test]
|
|
fn simple_post_request() {
|
|
let mut req = Request::new("https://httpbin.org/post").unwrap();
|
|
req.method(Method::POST);
|
|
let resp: Value = req.launch().to_json().expect("cannot parse json");
|
|
assert_eq!(resp["url"].as_str().unwrap(), "https://httpbin.org/post");
|
|
}
|