1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use super::{executor::run_test, CircuitsConfig, JsonStateTestBuilder, Results, StateTest};
use crate::{
    compiler::Compiler,
    config::{Config, TestSuite},
    statetest::{
        results::{ResultInfo, ResultLevel},
        YamlStateTestBuilder,
    },
};
use anyhow::{Context, Result};
use rayon::prelude::*;
use std::{
    panic::AssertUnwindSafe,
    sync::{Arc, RwLock},
};

pub fn load_statetests_suite(
    path: &str,
    config: Config,
    compiler: Compiler,
) -> Result<Vec<StateTest>> {
    let skip_paths: Vec<&String> = config.skip_paths.iter().flat_map(|t| &t.paths).collect();
    let skip_tests: Vec<&String> = config.skip_tests.iter().flat_map(|t| &t.tests).collect();

    let files = glob::glob(path)
        .context("failed to read glob")?
        .filter_map(|v| v.ok())
        .filter(|f| {
            !skip_paths
                .iter()
                .any(|e| f.as_path().to_string_lossy().contains(*e))
        });

    let mut tests = Vec::new();
    for file in files {
        if let Some(ext) = file.extension() {
            let ext = &*ext.to_string_lossy();
            if !["yml", "json"].contains(&ext) {
                continue;
            }
            let path = file.as_path().to_string_lossy();
            let src = std::fs::read_to_string(&file)?;
            log::debug!(target: "testool", "Reading file {:?}", file);
            let mut tcs = match ext {
                "yml" => YamlStateTestBuilder::new(&compiler).load_yaml(&path, &src)?,
                "json" => JsonStateTestBuilder::new(&compiler).load_json(&path, &src)?,
                _ => unreachable!(),
            };

            tcs.retain(|v| !skip_tests.contains(&&v.id));
            tests.append(&mut tcs);
        }
    }
    Ok(tests)
}

pub fn run_statetests_suite(
    tcs: Vec<StateTest>,
    circuits_config: &CircuitsConfig,
    suite: &TestSuite,
    results: &mut Results,
) -> Result<()> {
    // Filter already cached entries
    let all_test_count = tcs.len();
    let tcs: Vec<StateTest> = tcs
        .into_iter()
        .filter(|t| !results.contains(&format!("{}#{}", t.id, t.path)))
        .collect();

    log::info!(
        "{} test results cached, {} remaining",
        all_test_count - tcs.len(),
        tcs.len()
    );

    let results = Arc::new(RwLock::from(results));

    // for each test
    let test_count = tcs.len();
    tcs.into_par_iter().for_each(|ref tc| {
        let (test_id, path) = (tc.id.clone(), tc.path.clone());
        std::panic::set_hook(Box::new(|_info| {}));

        log::debug!(
            target : "testool",
            "🐕 running test (done {}/{}) {}#{}...",
            1 + results.read().unwrap().tests.len(),
            test_count,
            test_id,
            path,
        );
        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
            run_test(tc.clone(), suite.clone(), circuits_config.clone())
        }));

        // handle panic
        let result = match result {
            Ok(res) => res,
            Err(err) => {
                let panic_err = if let Some(s) = err.downcast_ref::<String>() {
                    s.to_string()
                } else if let Some(s) = err.downcast_ref::<&str>() {
                    s.to_string()
                } else {
                    "unable to get panic info".into()
                };

                let level = if panic_err.contains("circuit was not satisfied") {
                    ResultLevel::Fail
                } else if panic_err.contains("evm_unimplemented") {
                    ResultLevel::Ignored
                } else {
                    ResultLevel::Panic
                };
                results
                    .write()
                    .unwrap()
                    .insert(ResultInfo {
                        test_id,
                        level,
                        details: panic_err,
                        path,
                    })
                    .unwrap();
                return;
            }
        };

        // handle known error
        if let Err(err) = result {
            results
                .write()
                .unwrap()
                .insert(ResultInfo {
                    test_id,
                    level: if err.is_skip() {
                        ResultLevel::Ignored
                    } else {
                        ResultLevel::Fail
                    },
                    details: err.to_string(),
                    path,
                })
                .unwrap();
            return;
        }

        results
            .write()
            .unwrap()
            .insert(ResultInfo {
                test_id,
                level: ResultLevel::Success,
                details: String::default(),
                path,
            })
            .unwrap();
    });

    Ok(())
}