lundi 18 janvier 2021

Rust macro to generate multiple individual tests

Is it possible to have a macro that generates standalone tests? I have two text files, one with an input and another with an output. Each new line in the text file represents a new test. Currently, this is how I run my tests:

    #[test]
    fn it_works() {
        let input = read_file("input.txt").expect("failed to read input");
        let input = input.split("\n").collect::<Vec<_>>();

        let output = read_file("output.txt").expect("failed to read output");
        let output = output.split("\n").collect::<Vec<_>>();

        input.iter().zip(output).for_each(|(a, b)| {
            println!("a: {}, b: {}", a, b);
            assert_eq!(b, get_result(a));
        })

But, as you can see, if one test fail, all of them fail, since there's a loop inside a single test. And I need each iteration to be a single and isolated test, without having to repeat myself.

So I was wondering if it's possible to achieve that by using macros?

The macro ideally would output something like:

    #[test]
    fn it_works_1() {
        let input = read_file("input.txt").expect("failed to read input");
        let input = input.split("\n").collect::<Vec<_>>();

        let output = read_file("output.txt").expect("failed to read output");
        let output = output.split("\n").collect::<Vec<_>>();

        assert_eq!(output[0], get_result(input[0])); // first test
    }

    #[test]
    fn it_works_2() {
        let input = read_file("input.txt").expect("failed to read input");
        let input = input.split("\n").collect::<Vec<_>>();

        let output = read_file("output.txt").expect("failed to read output");
        let output = output.split("\n").collect::<Vec<_>>();

        assert_eq!(output[1], get_result(input[1])); // second test
    }

    // ... the N remaining tests: it_works_n() 

Aucun commentaire:

Enregistrer un commentaire