Is it possible to change the whole panic message?

Viewed 533

NUnit is a C# unit-test framework that permits you to write code like this:

Assert.That(someInt, Is.EqualTo(42));
Assert.That(someList, Has.Member(someMember));

I like this kind of code because it is easily readable by looking like English.


I am playing with Rust to see if I can create a library that gives the same feelings:

use std::fmt::Debug;

struct Is;

enum Verb<T> {
    EqualTo(T),
}

impl Is {
    fn equal_to<T>(&self, obj: T) -> Verb<T> {
        Verb::EqualTo(obj)
    }
}

#[allow(non_upper_case_globals)]
const is: Is = Is{};

fn assert_that<T: Eq + Debug>(obj: T, verb: Verb<T>) {
    match verb {
        Verb::EqualTo(rhs)    => assert_eq!(obj, rhs),
    }
}

fn main() {
    assert_that(42, is.equal_to(42));
    assert_that(42, is.equal_to(0));
}

This is good, but for one thing: when the code panics at assert_that(42, is.equal_to(0)), the line given by the panic is the line of assert_eq!(obj, rhs) (i.e. in the library instead of user's code). I know this behavior is normal, but I would have a more useful message.

How to indicate the right line number in the panic?

2 Answers
Related