Skip to main content

ef_tests/
suite.rs

1//! Abstractions for groups of tests.
2
3use crate::{
4    case::{Case, Cases},
5    result::{assert_tests_pass, Error},
6};
7use std::{
8    fs::File,
9    path::{Path, PathBuf},
10};
11use walkdir::WalkDir;
12
13/// A collection of tests.
14pub trait Suite {
15    /// The type of test cases in this suite.
16    type Case: Case;
17
18    /// The path to the test suite directory.
19    fn suite_path(&self) -> &Path;
20
21    /// Run all test cases in the suite.
22    fn run(&self) {
23        let suite_path = self.suite_path();
24        for entry in WalkDir::new(suite_path).min_depth(1).max_depth(1) {
25            let entry = entry.expect("Failed to read directory");
26            if entry.file_type().is_dir() {
27                self.run_only(entry.file_name().to_string_lossy().as_ref());
28            }
29        }
30    }
31
32    /// Load and run each contained test case for the provided sub-folder.
33    ///
34    /// # Note
35    ///
36    /// This recursively finds every test description in the resulting path.
37    fn run_only(&self, name: &str) {
38        // Build the path to the test suite directory
39        let suite_path = self.suite_path().join(name);
40
41        // Verify that the path exists
42        assert!(suite_path.exists(), "Test suite path does not exist: {suite_path:?}");
43
44        // Find all files with the ".json" extension in the test suite directory
45        let test_cases = find_all_files_with_extension(&suite_path, ".json")
46            .expect("fixture paths should be readable")
47            .into_iter()
48            .map(|test_case_path| {
49                let case = Self::Case::load(&test_case_path).expect("test case should load");
50                (test_case_path, case)
51            })
52            .collect();
53
54        // Run the test cases and collect the results
55        let results = Cases { test_cases }.run();
56
57        // Assert that all tests in the suite pass
58        assert_tests_pass(name, &suite_path, &results);
59    }
60}
61
62/// Recursively find all files with a given extension.
63pub fn find_all_files_with_extension(path: &Path, extension: &str) -> Result<Vec<PathBuf>, Error> {
64    let mut files = Vec::new();
65    for entry in WalkDir::new(path) {
66        let entry = entry?;
67        if !entry.file_type().is_dir() && entry.file_name().to_string_lossy().ends_with(extension) {
68            File::open(entry.path())
69                .map_err(|error| Error::Io { path: entry.path().into(), error })?;
70            files.push(entry.into_path());
71        }
72    }
73    Ok(files)
74}