eigen_testing_utils/test_data.rs
1use serde::{de::DeserializeOwned, Deserialize};
2use std::fmt::Debug;
3use std::fs::File;
4use std::{env, io::BufReader};
5
6/// Test data for generic loading of JSON data files.
7#[derive(Deserialize, Debug)]
8pub struct TestData<T> {
9 /// Input data read from JSON file.
10 pub input: T,
11 // output: BlsAggregationServiceResponse,
12}
13
14impl<T: DeserializeOwned> TestData<T> {
15 /// Create a new instance of `TestData` with the given input data.
16 /// If the `TEST_DATA_PATH` environment variable is set, it reads the JSON file from the path,
17 /// otherwise (or if it fails) it uses the default input data.
18 ///
19 /// # Arguments
20 ///
21 /// * `default_input` - The default input data to use if the JSON file is not found or fails to read.
22 ///
23 /// # Returns
24 ///
25 /// A new instance of `TestData` with the input data read from the JSON file or the default input data.
26 pub fn new(default_input: T) -> Self {
27 if let Ok(path) = env::var("TEST_DATA_PATH") {
28 let Ok(file) = File::open(path) else {
29 return TestData {
30 input: default_input,
31 };
32 };
33 let reader = BufReader::new(file);
34 let Ok(ret) = serde_json::from_reader(reader) else {
35 return TestData {
36 input: default_input,
37 };
38 };
39 ret
40 } else {
41 // use default values
42 TestData {
43 input: default_input,
44 }
45 }
46 }
47}