Skip to main content

arrow/util/
test_util.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Utils to make testing easier
6
7use rand::{RngExt, SeedableRng, rngs::StdRng};
8use std::{env, error::Error, fs, io::Write, path::PathBuf};
9
10/// Returns a vector of size `n`, filled with randomly generated bytes.
11pub fn random_bytes(n: usize) -> Vec<u8> {
12    let mut result = vec![];
13    let mut rng = seedable_rng();
14    for _ in 0..n {
15        result.push(rng.random_range(0..255));
16    }
17    result
18}
19
20/// Returns fixed seedable RNG
21pub fn seedable_rng() -> StdRng {
22    StdRng::seed_from_u64(42)
23}
24
25/// Returns file handle for a temp file in 'target' directory with a provided content
26///
27/// TODO: Originates from `parquet` utils, can be merged in [ARROW-4064]
28pub fn get_temp_file(file_name: &str, content: &[u8]) -> fs::File {
29    // build tmp path to a file in "target/debug/testdata"
30    let dir = env::current_dir().unwrap().join("target/debug/testdata");
31    fs::create_dir_all(&dir).unwrap();
32    let path_buf = dir.join(file_name);
33
34    // write file content
35    let mut tmp_file = fs::File::create(path_buf.as_path()).unwrap();
36    tmp_file.write_all(content).unwrap();
37    tmp_file.sync_all().unwrap();
38
39    // return file handle for both read and write
40    let file = fs::OpenOptions::new()
41        .read(true)
42        .write(true)
43        .open(path_buf.as_path());
44    assert!(file.is_ok());
45    file.unwrap()
46}
47
48/// Returns the arrow test data directory, which is by default stored
49/// in a git submodule rooted at `arrow/testing/data`.
50///
51/// The default can be overridden by the optional environment
52/// variable `ARROW_TEST_DATA`
53///
54/// Example:
55/// ```
56/// let testdata = arrow::util::test_util::arrow_test_data();
57/// let csvdata = format!("{}/csv/aggregate_test_100.csv", testdata);
58/// assert!(std::path::PathBuf::from(csvdata).exists());
59/// ```
60///
61/// # Panics
62///
63/// Panics if the directory can not be found
64pub fn arrow_test_data() -> String {
65    match get_data_dir("ARROW_TEST_DATA", "../testing/data") {
66        Ok(pb) => pb.display().to_string(),
67        Err(err) => panic!("failed to get arrow data dir: {err}"),
68    }
69}
70
71/// Returns the parquest test data directory, which is by default
72/// stored in a git submodule rooted at
73/// `arrow/parquest-testing/data`.
74///
75/// The default can be overridden by the optional environment variable
76/// `PARQUET_TEST_DATA`
77///
78/// Example:
79/// ```
80/// let testdata = arrow::util::test_util::parquet_test_data();
81/// let filename = format!("{}/binary.parquet", testdata);
82/// assert!(std::path::PathBuf::from(filename).exists());
83/// ```
84///
85/// # Panics
86///
87/// Panics if the directory can not be found
88pub fn parquet_test_data() -> String {
89    match get_data_dir("PARQUET_TEST_DATA", "../parquet-testing/data") {
90        Ok(pb) => pb.display().to_string(),
91        Err(err) => panic!("failed to get parquet data dir: {err}"),
92    }
93}
94
95/// Returns a directory path for finding test data.
96///
97/// udf_env: name of an environment variable
98///
99/// submodule_dir: fallback path (relative to CARGO_MANIFEST_DIR)
100///
101///  Returns either:
102/// The path referred to in `udf_env` if that variable is set and refers to a directory
103/// The submodule_data directory relative to CARGO_MANIFEST_PATH
104fn get_data_dir(udf_env: &str, submodule_data: &str) -> Result<PathBuf, Box<dyn Error>> {
105    // Try user defined env.
106    if let Ok(dir) = env::var(udf_env) {
107        let trimmed = dir.trim().to_string();
108        if !trimmed.is_empty() {
109            let pb = PathBuf::from(trimmed);
110            return if pb.is_dir() {
111                Ok(pb)
112            } else {
113                Err(format!(
114                    "the data dir `{}` defined by env {} not found",
115                    pb.display(),
116                    udf_env
117                )
118                .into())
119            };
120        }
121    }
122
123    // The env is undefined or its value is trimmed to empty, let's try default dir.
124
125    // env "CARGO_MANIFEST_DIR" is "the directory containing the manifest of your package",
126    // set by `cargo run` or `cargo test`, see:
127    // https://doc.rust-lang.org/cargo/reference/environment-variables.html
128    let dir = env!("CARGO_MANIFEST_DIR");
129
130    let pb = PathBuf::from(dir).join(submodule_data);
131    if pb.is_dir() {
132        Ok(pb)
133    } else {
134        Err(format!(
135            "env `{}` is undefined or has empty value, and the pre-defined data dir `{}` not found\n\
136             HINT: try running `git submodule update --init`",
137            udf_env,
138            pb.display(),
139        ).into())
140    }
141}
142
143/// An iterator that is untruthful about its actual length
144#[derive(Debug, Clone)]
145pub struct BadIterator<T> {
146    /// where the iterator currently is
147    cur: usize,
148    /// How many items will this iterator *actually* make
149    limit: usize,
150    /// How many items this iterator claims it will make
151    claimed: usize,
152    /// The items to return. If there are fewer items than `limit`
153    /// they will be repeated
154    pub items: Vec<T>,
155}
156
157impl<T> BadIterator<T> {
158    /// Create a new iterator for `<limit>` items, but that reports to
159    /// produce `<claimed>` items. Must provide at least 1 item.
160    ///
161    /// # Panics
162    ///
163    /// Panics if `items` is empty
164    pub fn new(limit: usize, claimed: usize, items: Vec<T>) -> Self {
165        assert!(!items.is_empty());
166        Self {
167            cur: 0,
168            limit,
169            claimed,
170            items,
171        }
172    }
173}
174
175impl<T: Clone> Iterator for BadIterator<T> {
176    type Item = T;
177
178    fn next(&mut self) -> Option<Self::Item> {
179        if self.cur < self.limit {
180            let next_item_idx = self.cur % self.items.len();
181            let next_item = self.items[next_item_idx].clone();
182            self.cur += 1;
183            Some(next_item)
184        } else {
185            None
186        }
187    }
188
189    /// report whatever the iterator says to
190    fn size_hint(&self) -> (usize, Option<usize>) {
191        (0, Some(self.claimed))
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn test_data_dir() {
201        let udf_env = "get_data_dir";
202        let cwd = env::current_dir().unwrap();
203
204        let existing_pb = cwd.join("..");
205        let existing = existing_pb.display().to_string();
206        let existing_str = existing.as_str();
207
208        let non_existing = cwd.join("non-existing-dir").display().to_string();
209        let non_existing_str = non_existing.as_str();
210
211        unsafe { env::set_var(udf_env, non_existing_str) };
212        let res = get_data_dir(udf_env, existing_str);
213        assert!(res.is_err());
214
215        unsafe { env::set_var(udf_env, "") };
216        let res = get_data_dir(udf_env, existing_str);
217        assert!(res.is_ok());
218        assert_eq!(res.unwrap(), existing_pb);
219
220        unsafe { env::set_var(udf_env, " ") };
221        let res = get_data_dir(udf_env, existing_str);
222        assert!(res.is_ok());
223        assert_eq!(res.unwrap(), existing_pb);
224
225        unsafe { env::set_var(udf_env, existing_str) };
226        let res = get_data_dir(udf_env, existing_str);
227        assert!(res.is_ok());
228        assert_eq!(res.unwrap(), existing_pb);
229
230        unsafe { env::remove_var(udf_env) };
231        let res = get_data_dir(udf_env, non_existing_str);
232        assert!(res.is_err());
233
234        let res = get_data_dir(udf_env, existing_str);
235        assert!(res.is_ok());
236        assert_eq!(res.unwrap(), existing_pb);
237    }
238
239    #[test]
240    fn test_happy() {
241        let res = arrow_test_data();
242        assert!(PathBuf::from(res).is_dir());
243
244        let res = parquet_test_data();
245        assert!(PathBuf::from(res).is_dir());
246    }
247}