#![cfg(feature = "backtrace")]
use serde_json::Value;
use flareapp::Level;
use flareapp_core::test_support;
fn stack_trace_of<F: FnOnce()>(report: F) -> Value {
let transport = test_support::run_with(flareapp::config!().api_key("secret"), report);
let report = transport
.bodies("/v1/errors")
.into_iter()
.next()
.unwrap_or_default();
report.get("stacktrace").cloned().unwrap_or_default()
}
fn assert_starts_at(frames: &Value, function: &str) {
let first = &frames[0];
assert_eq!(first["method"], function, "{frames:#}");
assert_eq!(first["isApplicationFrame"], true, "{frames:#}");
assert!(
first["file"]
.as_str()
.unwrap_or_default()
.ends_with("stack_trace.rs"),
"{frames:#}"
);
assert!(first["lineNumber"].as_u64().unwrap_or(0) > 0, "{frames:#}");
}
fn report_an_error() {
flareapp::report_error(&std::io::Error::other("disk full"));
}
fn report_a_message() {
flareapp::report_message("stock low", Level::Warning);
}
#[test]
fn report_error_starts_at_the_calling_function() {
assert_starts_at(&stack_trace_of(report_an_error), "report_an_error");
}
#[test]
fn report_message_starts_at_the_calling_function() {
assert_starts_at(&stack_trace_of(report_a_message), "report_a_message");
}
fn parse_address(address: &Value) -> Option<u64> {
let digits = address.as_str()?.strip_prefix("0x")?;
u64::from_str_radix(digits, 16).ok()
}
fn addresses_of(frames: &Value) -> Vec<u64> {
frames
.as_array()
.into_iter()
.flatten()
.filter_map(|frame| frame.get("instructionAddr"))
.filter_map(parse_address)
.collect()
}
#[test]
fn frames_send_their_address() {
assert_ne!(
addresses_of(&stack_trace_of(report_an_error)),
Vec::<u64>::new()
);
}
#[test]
#[cfg(target_os = "macos")]
fn every_address_is_inside_a_debug_image() {
let transport = test_support::run_with(flareapp::config!().api_key("secret"), report_an_error);
let report = transport.bodies("/v1/errors").remove(0);
let images: Vec<(u64, u64)> = report["debugImages"]
.as_array()
.unwrap()
.iter()
.map(|image| {
(
parse_address(&image["imageAddr"]).unwrap(),
image["imageSize"].as_u64().unwrap(),
)
})
.collect();
for address in addresses_of(&report["stacktrace"]) {
assert!(
images
.iter()
.any(|(start, size)| address.wrapping_sub(*start) < *size),
"{address:#x} is in no image of {images:x?}"
);
}
}