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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use crate::parse::ResultParser;
use crate::parse_cl_cts::ClCtsResultParser;
use crate::timeout::{TimeoutChildStdout, Timer};
use crate::{
    runner_results::*, runner_thread_index, BinaryTest, FailCounter, SubRunConfig,
    TestConfiguration,
};
use crate::{CaselistResult, SingleBinaryTestCommand, SingleTestCommand, TestCase, TestCommand};
use anyhow::{Context, Result};
use log::*;
use serde::Deserialize;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use structopt::StructOpt;

// CL-specific Structure for configuring a CL CTS run
#[derive(Debug, Deserialize, StructOpt)]
pub struct ClCtsRunConfig {
    #[structopt(long, help = "path to CL CTS build directory")]
    pub cl_folder: PathBuf,

    #[structopt(
        long,
        help = "CL CTS test set to run (such as `opencl_conformance_tests_full.csv`)"
    )]
    pub profile: String,
}

// Structure for the CL CTS entry in a suite.toml file.
#[derive(Deserialize)]
pub struct ClCtsTomlConfig {
    #[serde(flatten)]
    pub sub_config: SubRunConfig,

    #[serde(flatten)]
    pub cl_cts_config: ClCtsRunConfig,

    #[serde(default)]
    pub prefix: String,
}

fn parse_caselist<R: Read>(caselist: R) -> Result<Vec<crate::TestCase>> {
    let mut tests = Vec::new();

    for line in std::io::BufReader::new(caselist).lines() {
        let line = line.context("Reading caselist")?;
        if line.starts_with('#') {
            continue;
        }
        if line.is_empty() {
            continue;
        }

        fn compat_rsplit_once(s: &str, pat: char) -> Option<(&str, &str)> {
            let mut splitter = s.rsplitn(2, pat);

            let right = splitter.next();
            let left = splitter.next();
            if let (Some(left), Some(right)) = (left, right) {
                Some((left, right))
            } else {
                None
            }
        }

        // rsplit because the csv is badly formatted and there are ','s in
        // test names.  Use rsplit_once when we upgrade to rustc 1.52.
        if let Some((name, command)) = compat_rsplit_once(&line, ',') {
            let mut command = command.split(' ');

            tests.push(
                BinaryTest {
                    name: name.to_string(),
                    binary: command
                        .next()
                        .with_context(|| format!("extracting binary from {}", &line))?
                        .to_string(),
                    args: command.map(|x| (*x).to_string()).collect(),
                }
                .into(),
            );
        } else {
            anyhow::bail!("Failed to parse caselist line {}", line);
        }
    }

    Ok(tests)
}

impl ClCtsTomlConfig {
    pub fn conformance_dir(&self) -> PathBuf {
        self.cl_cts_config.cl_folder.join("test_conformance")
    }

    pub fn test_groups<'d>(
        &self,
        cl_cts: &'d ClCtsCommand,
        filters: &[String],
    ) -> Result<Vec<(&'d dyn TestCommand, Vec<TestCase>)>> {
        let caselist_path = self.conformance_dir().join(&self.cl_cts_config.profile);
        let caselist = std::fs::File::open(&caselist_path)
            .with_context(|| format!("Opening caselist at {}", caselist_path.display()))?;
        let tests: Vec<TestCase> = parse_caselist(caselist)
            .with_context(|| format!("Reading caselist at {}", caselist_path.display()))?;

        cl_cts.test_groups(&self.sub_config, filters, tests)
    }
}

pub struct ClCtsCommand {
    pub config: TestConfiguration,
    pub conformance_dir: PathBuf,
    pub prefix: String,
}

impl SingleTestCommand for ClCtsCommand {}
impl SingleBinaryTestCommand for ClCtsCommand {}

impl TestCommand for ClCtsCommand {
    fn name(&self) -> &str {
        "CL CTS"
    }

    fn prepare(&self, _caselist_state: &CaselistState, tests: &[&TestCase]) -> Result<Command> {
        let test = self.current_test(tests);

        let mut command = Command::new(self.conformance_dir.join(Path::new(&test.binary)));
        command
            .current_dir(&self.conformance_dir)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::null())
            .args(&test.args)
            .env("DEQP_RUNNER_THREAD", runner_thread_index()?.to_string())
            .envs(self.config.env.iter());

        debug!("Begin test {}", test.name);
        Ok(command)
    }

    fn clean(
        &self,
        _caselist_state: &CaselistState,
        tests: &[&TestCase],
        _results: &[RunnerResult],
    ) -> Result<()> {
        let test = self.current_test(tests);
        debug!("End test {}", test.name);
        Ok(())
    }

    fn parse_results(
        &self,
        _caselist_state: &CaselistState,
        tests: &[&TestCase],
        stdout: TimeoutChildStdout,
        timer: Option<Timer>,
        fail_counter: Option<FailCounter>,
    ) -> Result<CaselistResult> {
        let test = self.current_test(tests);
        let parser = ClCtsResultParser::new(&test.name);
        parser.parse_with_timer(stdout, timer, fail_counter)
    }

    fn should_save_log(&self, _caselist_state: &CaselistState, tests: &[&TestCase]) -> bool {
        let test = self.current_test(tests);
        test.name.contains("glinfo")
    }

    fn log_path(&self, _caselist_state: &CaselistState, tests: &[&TestCase]) -> Result<PathBuf> {
        let test = self.current_test(tests);
        Ok(self
            .config
            .output_dir
            .join(format!("cl_cts.{}.log", test.name).as_str()))
    }

    fn see_more(&self, test_name: &str, _caselist_state: &CaselistState) -> String {
        let log_path = self
            .config
            .output_dir
            .join(format!("cl_cts.{}.log", test_name).as_str());
        format!("See {:?}", log_path)
    }

    fn config(&self) -> &TestConfiguration {
        &self.config
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn case(name: &str, binary: &str, args: Vec<&str>) -> TestCase {
        BinaryTest {
            name: name.to_string(),
            binary: binary.to_string(),
            args: args.iter().map(|x| (*x).to_string()).collect(),
        }
        .into()
    }

    #[test]
    fn parse_caselist_test() {
        // This test must be run without -fbo, or it fails.
        let caselist = r#"
# #########################################
# General operation
# #########################################
Atomics,atomics/test_atomics
Allocations (single maximum),allocations/test_allocations single 5 all

# #########################################
# CPU is required to pass linear and normalized image filtering
# #########################################
CL_DEVICE_TYPE_CPU, Images (Kernel CL_FILTER_LINEAR),images/kernel_read_write/test_image_streams CL_FILTER_LINEAR
"#;

        assert_eq!(
            parse_caselist(caselist.as_bytes()).unwrap(),
            [
                case("Atomics", "atomics/test_atomics", vec![]),
                case(
                    "Allocations (single maximum)",
                    "allocations/test_allocations",
                    vec!["single", "5", "all"]
                ),
                case(
                    "CL_DEVICE_TYPE_CPU, Images (Kernel CL_FILTER_LINEAR)",
                    "images/kernel_read_write/test_image_streams",
                    vec!["CL_FILTER_LINEAR"]
                ),
            ]
        );
    }
}