quicktest 0.3.0

Command Line Interface (CLI) for stress testing in competitive programming contest
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
 *  Quick Test: CLI for stress testing in competitive programming
 *  Copyright (C) 2021 - Luis Miguel Báez
 *  License: MIT (See the LICENSE file in the repository root directory)
 */

use std::collections::VecDeque;
use std::path::Path;
use std::path::PathBuf;
use std::fs;
use std::env;
use std::time::Duration;
use std::io::Write;

use crate::runner::types::Language;
use crate::util::file::file_exists;

// Constants
use crate::constants::CACHE_FOLDER;
use crate::constants::TARGET_BINARY_FILE;
use crate::constants::CORRECT_BINARY_FILE;
use crate::constants::GEN_BINARY_FILE;
use crate::constants::QTEST_INPUT_FILE;
use crate::constants::QTEST_OUTPUT_FILE;
use crate::constants::QTEST_ERROR_FILE;
use crate::constants::QTEST_EXPECTED_FILE;
use crate::util::lang::{
    get_language_by_ext_default,
    get_language_by_ext_set_output
};

use failure::ResultExt;
use exitfailure::ExitFailure;
use colored::*;
use glob::glob;

pub fn run(target_file: PathBuf, correct_file: PathBuf,
        gen_file: PathBuf, timeout: u32, test_cases: u32, wa_break: bool,
        save_cases: bool) -> Result<(), ExitFailure>  {

    // Check if the CACHE_FOLDER folder is already created
    match fs::read_dir(CACHE_FOLDER) {
        Ok(_) => (),
        Err(_) => match fs::create_dir(CACHE_FOLDER) {
            Ok(_) => (),
            Err(_) => {
                // If not, create the folder
                let error: Result<(), failure::Error> = Err(failure::err_msg(format!("Can't create internal cache files")));
                return Ok(error.context("Error creating internal cache files".to_string())?);
            }
        },
    }
    
    // verify that the target file exists
    let file_name = target_file.to_str().unwrap();
    match file_exists(file_name) {
        Ok(_) => (),
        Err(_) => {
            let error: Result<(), failure::Error> = Err(failure::err_msg(format!("Can't open the file '{}'", file_name)));
            return Ok(error.context("<target-file> Not found".to_string())?);
        }
    }

    // verify that the correct file exists
    let file_name = correct_file.to_str().unwrap();
    match file_exists(file_name) {
        Ok(_) => (),
        Err(_) => {
            let error: Result<(), failure::Error> = Err(failure::err_msg(format!("Can't open the file '{}'", file_name)));
            return Ok(error.context("<correct-file> Not found".to_string())?);
        }
    }

    // verify that the generator file exists
    let file_name = gen_file.to_str().unwrap();
    match file_exists(file_name) {
        Ok(_) => (),
        Err(_) => {
            let error: Result<(), failure::Error> = Err(failure::err_msg(format!("Can't open the file '{}'", file_name)));
            return Ok(error.context("<gen-file> Not found".to_string())?);
        }
    }

    // get root path
    let root: PathBuf = match env::current_dir() {
        Ok(path) => path,
        _ => unreachable!(),
    };

    let root: &str = match root.to_str() {
        Some(root_path) => root_path,
        _ => unreachable!(),
    };

    // Get the language depending on the extension of the correct_file
    let any_correct: Option<Box<dyn Language>> = get_language_by_ext_default(
        root,
        correct_file,
        &CORRECT_BINARY_FILE,
        &QTEST_INPUT_FILE,
        &QTEST_EXPECTED_FILE,
        &QTEST_ERROR_FILE
    );
    let any_correct: Box<dyn Language> = any_correct.unwrap();
    let correct_file_lang: &dyn Language = any_correct.as_ref();

    // Get the language depending on the extension of the target_file
    let any_target: Option<Box<dyn Language>> = get_language_by_ext_default(
        root,
        target_file,
        &TARGET_BINARY_FILE,
        &QTEST_INPUT_FILE,
        &QTEST_OUTPUT_FILE,
        &QTEST_ERROR_FILE
    );
    let any_target: Box<dyn Language> = any_target.unwrap();
    let target_file_lang: &dyn Language = any_target.as_ref();

    // Get the language depending on the extension of the gen_file
    let any_gen: Option<Box<dyn Language>> = get_language_by_ext_set_output(
        root,
        gen_file,
        &GEN_BINARY_FILE,
        &QTEST_INPUT_FILE,
    );
    let any_gen: Box<dyn Language> = any_gen.unwrap();
    let generator_file_lang: &dyn Language = any_gen.as_ref();


    correct_file_lang.build();

    target_file_lang.build();

    generator_file_lang.build();

    if save_cases {
        // remove test cases prefixed with testcase_wa*.txt
        let paths = glob("test_cases/testcase_wa*")?;
        for entry in paths {
            match entry {
                Ok(path) => {
                    fs::remove_file(path.to_str().unwrap())?;
                },
                Err(_) => (),
            }
        }
    }

    let mut tle_count: u32 = 0;
    let mut wa_count: u32 = 0;

    for test_number in 1..=test_cases {
        let time_gen: Duration = generator_file_lang.execute(timeout as u32);
        let time_correct: Duration = correct_file_lang.execute(timeout as u32);
        let time_target: Duration = target_file_lang.execute(timeout as u32);

        let mills_target: u128 = time_target.as_millis();

        if time_gen >= Duration::from_millis(timeout as u64) {
            // TLE Generator
            println!(
                "  {} [{}] {} {}ms",
                test_number,
                "TLE".bold().red(),
                "Generator Time Limit Exceeded :".bold().red(),
                timeout
            );

            let error: Result<(), failure::Error> = Err(failure::err_msg("very slow generator"));
            return Ok(error.context("Generator TLE".to_string())?);
        }

        if time_correct >= Duration::from_millis(timeout as u64) {
            // TLE Correct file
            println!(
                "  {} [{}] {} {}ms",
                test_number,
                "TLE".bold().red(),
                "Correct File give Time Limit Exceeded :".bold().red(),
                timeout
            );

            let error: Result<(), failure::Error> = Err(failure::err_msg("Correct file very slow"));
            return Ok(error.context("Correct File TLE".to_string())?);
        }

        if time_target >= Duration::from_millis(timeout as u64) {
            // TLE Target file
            
            tle_count += 1;

            println!(
                "  {} [{}] {} {}ms",
                test_number,
                "TLE".bold().red(),
                "Time Limit Exceeded :".bold().red(),
                timeout
            );
        
            // Verify that the folder test_cases exists, in case it does not exist create it
            if save_cases && !Path::new("test_cases").exists() {
                match fs::create_dir("test_cases") {
                    Err(_) => {
                        let error = Err(failure::err_msg("Could not create folder test_cases"));
                        return Ok(error.context("test_cases folder".to_string())?);
                    }
                    _ => (),
                }
            }

            // Save the input of the test case that gave status tle
            if save_cases {
                let filename: String = format!("test_cases/testcase_tle_{}.txt", tle_count);
                let mut file = fs::File::create(filename)
                    .expect("Error creating file test_cases/testcase(i).txt");
                file.write_all(fs::read_to_string(QTEST_INPUT_FILE).unwrap().as_bytes()).unwrap();
            }
            
            // check if the wa_break flag is high
            if wa_break {
                // remove input, output and error files
                fs::remove_file(&QTEST_INPUT_FILE)?;
                fs::remove_file(&QTEST_OUTPUT_FILE)?;
                fs::remove_file(&QTEST_ERROR_FILE)?;
                fs::remove_file(&QTEST_EXPECTED_FILE)?;

                match file_exists(&TARGET_BINARY_FILE) {
                    Ok(_) => fs::remove_file(&TARGET_BINARY_FILE)?,
                    _ => (),
                }
                match file_exists(&GEN_BINARY_FILE) {
                    Ok(_) => fs::remove_file(&GEN_BINARY_FILE)?,
                    _ => (),
                }
                match file_exists(&CORRECT_BINARY_FILE) {
                    Ok(_) => fs::remove_file(&CORRECT_BINARY_FILE)?,
                    _ => (),
                };
                return Ok(());
            }
        } else {
            // The time is in the allowed range
            let file_out = format!("{}/{}", root, QTEST_OUTPUT_FILE);
            let file_expected = format!("{}/{}", root, QTEST_EXPECTED_FILE);
            
            // Check WA Status
            if compare_file(&file_out, &file_expected, true) {
                // is OK
                println!(
                    "  {} [{}] {} {}ms",
                    test_number.to_string().bold().white(),
                    "OK".bold().green(),
                    "Finished in".bold().green(), mills_target
                );
            } else {
                // WA found
                wa_count += 1;
                println!(
                    "  {} [{}] {} {}ms",
                    test_number.to_string().bold().white(),
                    "WA".bold().red(),
                    "Finished in".bold().red(), mills_target
                );

                // Verify that the folder test_cases exists, in case it does not exist create it
                if save_cases && !Path::new("test_cases").exists() {
                    match fs::create_dir("test_cases") {
                        Err(_) => {
                            let error = Err(failure::err_msg("Could not create folder test_cases"));
                            return Ok(error.context("test_cases folder".to_string())?);
                        }
                        _ => (),
                    }
                }

                // Save the input of the test case that gave status tle
                if save_cases {
                    let filename: String = format!("test_cases/testcase_wa_{}.txt", wa_count);
                    let mut file = fs::File::create(filename)
                        .expect("Error creating file test_cases/testcase(i).txt");
                    file.write_all(fs::read_to_string(QTEST_INPUT_FILE).unwrap().as_bytes()).unwrap();
                }

                if wa_break {
                    // remove input, output and error files
                    fs::remove_file(&QTEST_INPUT_FILE)?;
                    fs::remove_file(&QTEST_OUTPUT_FILE)?;
                    fs::remove_file(&QTEST_ERROR_FILE)?;
                    fs::remove_file(&QTEST_EXPECTED_FILE)?;
                    
                    match file_exists(&TARGET_BINARY_FILE) {
                        Ok(_) => fs::remove_file(&TARGET_BINARY_FILE)?,
                        _ => (),
                    }
                    match file_exists(&GEN_BINARY_FILE) {
                        Ok(_) => fs::remove_file(&GEN_BINARY_FILE)?,
                        _ => (),
                    }
                    match file_exists(&CORRECT_BINARY_FILE) {
                        Ok(_) => fs::remove_file(&CORRECT_BINARY_FILE)?,
                        _ => (),
                    };

                    let error = Err(failure::err_msg(format!("Wrong answer on test {}", test_number)));
                    return Ok(error.context("WA Status".to_string())?);
                }
            }
        }

        // remove input, output and error files
        fs::remove_file(&QTEST_INPUT_FILE)?;
        fs::remove_file(&QTEST_OUTPUT_FILE)?;
        fs::remove_file(&QTEST_ERROR_FILE)?;
        fs::remove_file(&QTEST_EXPECTED_FILE)?;
        
    }

    match file_exists(&TARGET_BINARY_FILE) {
        Ok(_) => fs::remove_file(&TARGET_BINARY_FILE)?,
        _ => (),
    }
    match file_exists(&GEN_BINARY_FILE) {
        Ok(_) => fs::remove_file(&GEN_BINARY_FILE)?,
        _ => (),
    }
    match file_exists(&CORRECT_BINARY_FILE) {
        Ok(_) => fs::remove_file(&CORRECT_BINARY_FILE)?,
        _ => (),
    }

    Ok(())
}

pub fn compare_file(target_file: &String, correct_file: &String, ignore_space: bool) -> bool {
    let mut is_good = true;
    let target_content = match std::fs::read_to_string(target_file) {
        Ok(content) => Some(content),
        Err(_) => {
            is_good = false;
            None
        },
    };

    let correct_content = match std::fs::read_to_string(correct_file) {
        Ok(content) => Some(content),
        Err(_) => {
            is_good = false;
            None
        },
    };

    if !is_good { return false; }

    let mut target_content_vec: VecDeque<char> = VecDeque::new();
    let mut correct_content_vec: VecDeque<char> = VecDeque::new();
    
    is_good = match (target_content, correct_content) {
        (Some(_), None) => false,
        (None, Some(_)) => false,
        (None, None) => false,
        (Some(s1), Some(s2)) => {
            target_content_vec = s1.chars().collect::<VecDeque<char>>();
            correct_content_vec = s2.chars().collect::<VecDeque<char>>();
            true
        },
    };

    if !is_good { return false; }

    if ignore_space {
        // Remove spaces at the beginning and end of the file

        // for target_content_vec
        while !target_content_vec.is_empty()
            && (*target_content_vec.back().unwrap()==' '||*target_content_vec.back().unwrap()=='\n') {
            target_content_vec.pop_back();
        }
        while !target_content_vec.is_empty()
            && (*target_content_vec.front().unwrap()==' '||*target_content_vec.front().unwrap()=='\n') {
            target_content_vec.pop_front();
        }

        // for correct_content_vec
        while !correct_content_vec.is_empty()
            && (*correct_content_vec.back().unwrap()==' '||*correct_content_vec.back().unwrap()=='\n') {
            correct_content_vec.pop_back();
        }
        while !correct_content_vec.is_empty()
            && (*correct_content_vec.front().unwrap()==' '||*correct_content_vec.front().unwrap()=='\n') {
            correct_content_vec.pop_front();
        }

        // replace "  " to " ", " \n" to "\n", "\n " to "\n" and "\n\n" to "\n"
        let mut target_tmp = target_content_vec.clone();
        let mut correct_tmp = correct_content_vec.clone();
        target_content_vec.clear();
        correct_content_vec.clear();

        if !target_tmp.is_empty() {
            target_content_vec.push_back(target_tmp.pop_front().unwrap());
        }
        while !target_tmp.is_empty() {
            match (target_content_vec.back(), target_tmp.pop_front()) {
                (Some(' '), Some('\n')) => {
                    target_content_vec.pop_back();
                    target_content_vec.push_back('\n');
                },
                (Some(' '), Some(' ')) => continue,
                (Some('\n'), Some(' ')) => continue,
                (Some('\n'), Some('\n')) => continue,
                (Some(_), Some(ch)) => target_content_vec.push_back(ch),
                _ => continue,
            }
        }
        if !correct_tmp.is_empty() {
            correct_content_vec.push_back(correct_tmp.pop_front().unwrap());
        }
        while !correct_tmp.is_empty() {
            match (correct_content_vec.back(), correct_tmp.pop_front()) {
                (Some(' '), Some('\n')) => {
                    correct_content_vec.pop_back();
                    correct_content_vec.push_back('\n');
                },
                (Some(' '), Some(' ')) => continue,
                (Some('\n'), Some(' ')) => continue,
                (Some('\n'), Some('\n')) => continue,
                (Some(_), Some(ch)) => correct_content_vec.push_back(ch),
                _ => continue,
            }
        }
    }

    target_content_vec == correct_content_vec
}