use super::*;
use crate::pricing::Pricing;
use fleetwire_testkit::matchers::{header, method, path};
use fleetwire_testkit::{Mock, MockServer, ResponseTemplate};
use std::io::Read;
use std::time::{Duration, Instant};
fn client() -> ureq::Agent {
crate::net::agent(std::time::Duration::from_secs(10))
}
#[test]
fn get_carries_bearer_and_returns_body() {
let server = MockServer::start();
Mock::given(method("GET"))
.and(path("/api/1/vehicles"))
.and(header("authorization", "Bearer tok-abc"))
.respond_with(
ResponseTemplate::new(200)
.set_body_raw(br#"{"response":[]}"#.to_vec(), "application/json"),
)
.mount(&server);
let url = format!("{}/api/1/vehicles", server.uri()).parse().unwrap();
let r = execute_get(
&client(),
url,
"tok-abc",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap();
assert_eq!(r.status.as_u16(), 200);
assert_eq!(r.body, br#"{"response":[]}"#.to_vec());
assert_eq!(r.content_type.as_deref(), Some("application/json"));
}
#[test]
fn preserves_www_authenticate_on_empty_html_401() {
let server = MockServer::start();
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(401)
.insert_header("content-type", "text/html")
.insert_header(
"www-authenticate",
r#"Bearer realm="Doorkeeper", error="invalid_token", error_description="The access token is invalid""#,
)
.set_body_raw(Vec::new(), "text/html"),
)
.mount(&server);
let url = format!("{}/api/1/vehicles", server.uri()).parse().unwrap();
let r = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap();
assert_eq!(r.status.as_u16(), 401);
assert!(r.body.is_empty(), "실측상 body 는 0바이트여야 한다");
assert!(
r.www_authenticate
.unwrap()
.contains("The access token is invalid")
);
}
#[test]
fn parses_retry_after_delta_seconds() {
let server = MockServer::start();
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(429)
.insert_header("retry-after", "30")
.set_body_raw(b"{}".to_vec(), "application/json"),
)
.mount(&server);
let url = format!("{}/x", server.uri()).parse().unwrap();
let r = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap();
assert_eq!(r.retry_after, Some(std::time::Duration::from_secs(30)));
}
#[test]
fn parses_retry_after_http_date() {
assert_eq!(
parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"),
Some(std::time::Duration::ZERO)
);
assert_eq!(parse_retry_after("not-a-date"), None);
}
#[test]
fn redirect_status_becomes_api_error_not_decode() {
let server = MockServer::start();
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(302).insert_header("location", "https://evil.example/"))
.mount(&server);
let url = format!("{}/x", server.uri()).parse().unwrap();
let err = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap_err();
assert!(
matches!(err, crate::error::Error::Api { status, .. } if status.as_u16() == 302),
"실제: {err:?}"
);
}
#[test]
fn aborts_while_streaming_when_body_exceeds_cap() {
let server = MockServer::start();
let huge = vec![b'x'; MAX_RESPONSE_BYTES + 1024];
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(200).set_body_raw(huge, "application/json"))
.mount(&server);
let url = format!("{}/x", server.uri()).parse().unwrap();
let err = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(10),
)
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("response too large"), "실제: {msg}");
}
struct CountingChunks {
chunks: Vec<&'static [u8]>,
idx: usize,
reads: usize,
}
impl Read for CountingChunks {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.reads += 1;
match self.chunks.get(self.idx) {
Some(c) => {
let n = c.len().min(buf.len());
buf[..n].copy_from_slice(&c[..n]);
self.idx += 1;
Ok(n)
}
None => Ok(0),
}
}
}
#[test]
fn accumulate_capped_stops_polling_once_cap_is_crossed() {
let mut r = CountingChunks {
chunks: vec![b"AAAAA", b"BBBBB", b"CCCCC", b"DDDDD"],
idx: 0,
reads: 0,
};
let far = Instant::now() + Duration::from_secs(5);
let err = read_capped(&mut r, 10, far).unwrap_err();
assert!(matches!(err, ReadError::CapExceeded));
assert_eq!(
r.reads, 3,
"read count must prove early abort, not a full drain to the end of the body"
);
}
#[test]
fn accumulate_capped_exact_boundary_succeeds_one_byte_over_fails() {
let max = 4usize;
let far = Instant::now() + Duration::from_secs(5);
let mut ok: &[u8] = b"AAAA";
assert_eq!(read_capped(&mut ok, max, far).unwrap().len(), max);
let mut over: &[u8] = b"AAAAA";
assert!(matches!(
read_capped(&mut over, max, far),
Err(ReadError::CapExceeded)
));
}
fn unused_port() -> u16 {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
port
}
#[test]
fn connect_failure_is_transport_not_sent_not_unknown() {
let port = unused_port();
let url = format!("http://127.0.0.1:{port}/x").parse().unwrap();
let err = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap_err();
match err {
Error::TransportNotSent { .. } => {}
other => panic!("expected TransportNotSent, got: {other:?}"),
}
}
#[test]
fn connect_error_message_does_not_leak_vin_from_url() {
let port = unused_port();
let vin = "5YJ3E1EA7KF000000";
let url = format!("http://127.0.0.1:{port}/api/1/vehicles/{vin}/vehicle_data")
.parse()
.unwrap();
let err = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap_err();
let msg = err.to_string();
assert!(
!msg.contains(vin),
"VIN leaked in transport error message: {msg}"
);
}
#[test]
fn ureq_error_with_url_is_redacted() {
let vin = "5YJ3E1EA7KF000000";
let e = ureq::Error::BadUri(format!(
"https://x/api/1/vehicles/{vin}/vehicle_data?endpoints=location_data"
));
let msg = crate::net::redact_ureq_error(&e);
assert!(!msg.contains(vin), "VIN leaked: {msg}");
assert!(msg.contains("[VIN]"), "expected VIN marker, got: {msg}");
assert!(!msg.contains("location_data"), "query leaked: {msg}");
}
#[test]
fn get_cut_mid_body_is_unknown() {
let server = MockServer::start();
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(200)
.set_body_raw(b"{\"response\":[1,2,3]}".to_vec(), "application/json")
.cut_after_body_bytes(3),
)
.mount(&server);
let url = format!("{}/x", server.uri()).parse().unwrap();
let err = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
Duration::from_secs(5),
)
.unwrap_err();
assert!(
matches!(err, Error::TransportUnknown { .. }),
"expected TransportUnknown, got: {err:?}"
);
}
#[test]
fn get_trickling_body_times_out_as_unknown() {
let server = MockServer::start();
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(200)
.set_body_raw(vec![b' '; 1024], "application/json")
.trickle_body(1, Duration::from_millis(20)),
)
.mount(&server);
let url = format!("{}/x", server.uri()).parse().unwrap();
let t = Instant::now();
let err = execute_get(
&crate::net::agent(Duration::from_millis(200)),
url,
"t",
Pricing::NotCharged,
Duration::from_millis(200),
)
.unwrap_err();
assert!(
matches!(err, Error::TransportUnknown { .. }),
"expected TransportUnknown, got: {err:?}"
);
assert!(
t.elapsed() < Duration::from_millis(1_500),
"{:?}",
t.elapsed()
);
}
#[test]
fn rate_limit_is_some_when_all_three_headers_parse() {
let server = MockServer::start();
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(200)
.insert_header("ratelimit-device-data-per-vehicle-limit", "60")
.insert_header("ratelimit-device-data-per-vehicle-remaining", "59")
.insert_header("ratelimit-device-data-per-vehicle-reset", "57")
.set_body_raw(b"{}".to_vec(), "application/json"),
)
.mount(&server);
let url = format!("{}/x", server.uri()).parse().unwrap();
let r = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap();
assert_eq!(r.rate_limit, Some((60, 59, 57)));
}
#[test]
fn rate_limit_is_none_when_a_present_header_fails_to_parse() {
let server = MockServer::start();
Mock::given(method("GET"))
.respond_with(
ResponseTemplate::new(200)
.insert_header("ratelimit-device-data-per-vehicle-limit", "sixty")
.insert_header("ratelimit-device-data-per-vehicle-remaining", "59")
.insert_header("ratelimit-device-data-per-vehicle-reset", "57")
.set_body_raw(b"{}".to_vec(), "application/json"),
)
.mount(&server);
let url = format!("{}/x", server.uri()).parse().unwrap();
let r = execute_get(
&client(),
url,
"t",
Pricing::NotCharged,
std::time::Duration::from_secs(5),
)
.unwrap();
assert_eq!(
r.rate_limit, None,
"a present-but-unparsable header must not be defaulted to 0"
);
}