From 5f47e7b0613b7477ef91568f4a4ed1e10dc5f707 Mon Sep 17 00:00:00 2001 From: Rose Hogenson Date: Thu, 30 May 2024 20:25:59 -0700 Subject: Write tests for eval. --- src/eval.rs | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 1 deletion(-) (limited to 'src/eval.rs') diff --git a/src/eval.rs b/src/eval.rs index b08bf81..dce9d68 100644 --- a/src/eval.rs +++ b/src/eval.rs @@ -1,6 +1,6 @@ use std::fmt::{Display, Formatter}; -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum Num { Int(i128), Float(f64), @@ -211,3 +211,91 @@ impl Display for Num { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pow_positive_int() { + assert_eq!(int(2).pow(int(16)), int(65536)); + } + + #[test] + fn pow_negative_int() { + assert_eq!(int(2).pow(int(-3)), float(0.125)); + } + + #[test] + fn pow_float() { + assert_eq!(int(4).pow(float(0.5)), float(2.)); + } + + #[test] + fn pow_overflow() { + assert_eq!(int(2).pow(int(1 << 126)), float(f64::INFINITY)); + } + + #[test] + fn pow_underflow() { + assert_eq!(int(2).pow(int(-(1 << 126))), float(0.)); + } + + #[test] + fn modulo_pos() { + assert_eq!(int(5).modulo(int(3)), int(2)); + } + + #[test] + fn modulo_pos_neg() { + assert_eq!(int(5).modulo(int(-3)), int(-1)); + } + + #[test] + fn modulo_neg_pos() { + assert_eq!(int(-5).modulo(int(3)), int(1)); + } + + #[test] + fn modulo_neg() { + assert_eq!(int(-5).modulo(int(-3)), int(-2)); + } + + #[test] + fn modulo_float_pos() { + assert_eq!(float(5.).modulo(int(3)), float(2.)); + } + + #[test] + fn modulo_float_pos_neg() { + assert_eq!(float(5.).modulo(int(-3)), float(-1.)); + } + + #[test] + fn modulo_float_neg_pos() { + assert_eq!(float(-5.).modulo(int(3)), float(1.)); + } + + #[test] + fn modulo_float_neg() { + assert_eq!(float(-5.).modulo(int(-3)), float(-2.)); + } + + #[test] + fn sqrt() { + for n in 0..65536 { + assert_eq!( + int(n * n).sqrt(), + int(n), + "int({}).sqrt() is not equal to {}", + n * n, + n + ); + } + } + + #[test] + fn sqrt_big() { + assert_eq!(int(1 << 126).sqrt(), int(1 << 63)); + } +} -- cgit v1.3.1