use num::ToPrimitive;
use std::{fmt::Debug, panic::Location};
#[macro_export]
macro_rules! expect {
($left_value:expr) => {{
jrest::Expectation::new($left_value)
}};
}
pub struct Expectation<L: Debug> {
at_path: &'static str,
at_line: u32,
left_value: L,
}
impl<L: Debug> Expectation<L> {
#[doc(hidden)]
#[track_caller]
pub fn new(left_value: L) -> Self {
let at_path = Location::caller().file();
let at_line = Location::caller().line();
Self {
at_line,
at_path,
left_value,
}
}
}
impl<L: Debug> Expectation<L> {
fn panic_with_assertion<R: Debug>(&self, right_value: R, comparator: &str) {
panic!(
"assertion failed: `(left {} right)`\n left: `{:?}`,\n right: `{:?}`\nat {}:{}\n\n",
comparator, self.left_value, right_value, self.at_path, self.at_line
);
}
}
impl<L: Debug + Eq + PartialEq> Expectation<L> {
pub fn to_be(&self, right_value: L) {
if !(self.left_value == right_value) {
self.panic_with_assertion(right_value, "===");
}
}
}
impl<T: ToPrimitive + Debug> Expectation<T> {
pub fn to_be_greater_than(&self, right_value: T) {
if !(self.left_value.to_f32() > right_value.to_f32()) {
self.panic_with_assertion(right_value, ">");
}
}
pub fn to_be_greater_than_or_equal(&self, right_value: T) {
if !(self.left_value.to_f32() >= right_value.to_f32()) {
self.panic_with_assertion(right_value, ">=");
}
}
pub fn to_be_less_than(&self, right_value: T) {
if !(self.left_value.to_f32() < right_value.to_f32()) {
self.panic_with_assertion(right_value, "<");
}
}
pub fn to_be_less_than_or_equal(&self, right_value: T) {
if !(self.left_value.to_f32() <= right_value.to_f32()) {
self.panic_with_assertion(right_value, "<=");
}
}
}
impl<T: AsRef<str> + Debug> Expectation<T> {
pub fn to_end_with<R: AsRef<str> + Debug>(&self, right_value: R) {
if !self.left_value.as_ref().ends_with(right_value.as_ref()) {
self.panic_with_assertion(right_value, "ends with");
}
}
pub fn to_start_with<R: AsRef<str> + Debug>(&self, right_value: R) {
if !self.left_value.as_ref().starts_with(right_value.as_ref()) {
self.panic_with_assertion(right_value, "starts with");
}
}
}