Skip to content

Instantly share code, notes, and snippets.

@hikilaka
Created September 24, 2021 03:29
Show Gist options
  • Save hikilaka/d74f25e048a871cc077d1b97a151d752 to your computer and use it in GitHub Desktop.
Save hikilaka/d74f25e048a871cc077d1b97a151d752 to your computer and use it in GitHub Desktop.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_addition() {
let program = vec![
Operation::Store(0, 45),
Operation::Store(1, 30),
Operation::Add(0, 1, 0),
];
let mut vm = VM::new(program);
assert_eq!(vm.registers[0], 0);
assert_eq!(vm.registers[1], 0);
assert_eq!(vm.run(), RuntimeError::Success);
assert_eq!(vm.registers[0], 75);
assert_eq!(vm.registers[1], 30)
}
#[test]
fn test_store() {
let program = vec![Operation::Store(0, 45)];
let mut vm = VM::new(program);
assert_eq!(vm.registers[0], 0);
assert_eq!(vm.run(), RuntimeError::Success);
assert_eq!(vm.registers[0], 45);
}
#[test]
fn test_stack_push_pop() {
let program = vec![
Operation::Push(42),
Operation::Push(56),
Operation::Pop(3),
Operation::Pop(0),
];
let mut vm = VM::new(program);
assert_eq!(vm.stack[0], 0);
assert_eq!(vm.stack[3], 0);
assert_eq!(vm.run(), RuntimeError::Success);
assert_eq!(vm.registers[3], 56);
assert_eq!(vm.registers[0], 42);
}
#[test]
fn test_stack_underflow() {
let program = vec![Operation::Pop(0)];
let mut vm = VM::new(program);
assert_eq!(vm.run(), RuntimeError::StackUnderflow(0));
}
#[test]
fn test_stack_overflow() {
let mut program = vec![];
for i in 0..=STACK_SIZE {
program.push(Operation::Push(i as u32));
}
let mut vm = VM::new(program);
assert_eq!(vm.run(), RuntimeError::StackOverflow(STACK_SIZE));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment