use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use arrow_array::{ArrayRef, BooleanArray, Float64Array, Int64Array, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use parquet::arrow::arrow_writer::ArrowWriter;
use parquet::basic::Compression;
use parquet::file::properties::WriterProperties;
use parquet_cli::meta;
use parquet_cli::output::Format;
use parquet_cli::rows;
fn fixture(directory: &Path) -> PathBuf {
let schema = Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("path", DataType::Utf8, false),
Field::new("score", DataType::Float64, true),
Field::new("ok", DataType::Boolean, false),
]);
let ids: ArrayRef = Arc::new(Int64Array::from(vec![1i64, 2, 3]));
let paths: ArrayRef = Arc::new(StringArray::from(vec!["/a", "/b", "/c"]));
let scores: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.5), None, Some(3.5)]));
let flags: ArrayRef = Arc::new(BooleanArray::from(vec![true, false, true]));
let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![ids, paths, scores, flags])
.expect("the batch matches the schema");
let properties = WriterProperties::builder()
.set_compression(Compression::ZSTD(
parquet::basic::ZstdLevel::try_new(1).expect("a level"),
))
.build();
let path = directory.join("events.parquet");
let file = File::create(&path).expect("create the fixture");
let mut writer =
ArrowWriter::try_new(file, Arc::new(schema), Some(properties)).expect("the writer opens");
writer.write(&batch).expect("write the batch");
writer.close().expect("close the file");
path
}
fn temporary_directory(name: &str) -> PathBuf {
let path = std::env::temp_dir().join(format!("parquet-cli-{name}"));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create the temporary directory");
path
}
#[test]
fn facts_count_the_rows_and_the_columns() {
let directory = temporary_directory("facts");
let path = fixture(&directory);
let facts = meta::facts(&path).expect("the facts are readable");
assert_eq!(facts["rows"], 3);
assert_eq!(facts["row_groups"], 1);
assert_eq!(facts["columns"], 4);
assert!(facts["size_bytes"].as_u64().expect("a size") > 0);
assert_eq!(facts["compressions"][0], "ZSTD");
}
#[test]
fn the_schema_names_every_column() {
let directory = temporary_directory("schema");
let path = fixture(&directory);
let schema = meta::schema(&path).expect("the schema is readable");
let fields = schema["fields"].as_array().expect("a list of fields");
assert_eq!(fields.len(), 4);
assert_eq!(fields[0]["name"], "id");
assert_eq!(fields[0]["type"], "int64");
assert_eq!(fields[1]["type"], "utf8");
assert_eq!(fields[3]["nullable"], false);
}
#[test]
fn the_columns_carry_their_statistics() {
let directory = temporary_directory("columns");
let path = fixture(&directory);
let columns = meta::columns(&path, false).expect("the columns are readable");
let columns = columns["columns"].as_array().expect("a list of columns");
assert_eq!(columns.len(), 4);
let id = &columns[0];
assert_eq!(id["name"], "id");
assert_eq!(id["num_values"], 3);
assert_eq!(id["null_count"], 0);
assert_eq!(id["min"], 1);
assert_eq!(id["max"], 3);
let score = &columns[2];
assert_eq!(score["null_count"], 1);
}
#[test]
fn scanning_counts_the_distinct_values() {
let directory = temporary_directory("scan");
let path = fixture(&directory);
let columns = meta::columns(&path, true).expect("the columns are readable");
let columns = columns["columns"].as_array().expect("a list of columns");
assert_eq!(columns[1]["distinct_count"], 3);
}
#[test]
fn the_head_is_the_first_rows() {
let directory = temporary_directory("head");
let path = fixture(&directory);
let table = rows::head(&path, 2).expect("the rows are readable");
assert_eq!(table.rows.len(), 2);
assert_eq!(table.columns, vec!["id", "path", "score", "ok"]);
assert_eq!(table.rows[0][0], serde_json::json!(1));
assert_eq!(table.rows[0][1], serde_json::json!("/a"));
assert_eq!(table.rows[1][2], serde_json::Value::Null);
}
#[test]
fn a_valid_file_passes_every_check() {
let directory = temporary_directory("validate");
let path = fixture(&directory);
let report = parquet_cli::validate::validate(&path).expect("the report is readable");
assert_eq!(report["ok"], true, "the report: {report}");
let checks = report["checks"].as_array().expect("a list of checks");
assert!(checks.len() >= 4);
assert!(checks.iter().all(|check| check["ok"] == true));
}
#[test]
fn the_command_line_answers_in_json() {
let directory = temporary_directory("cli");
let path = fixture(&directory);
let output = std::process::Command::new(env!("CARGO_BIN_EXE_parquet"))
.args(["--json", "info"])
.arg(&path)
.output()
.expect("the command runs");
assert!(output.status.success(), "the command failed");
let text = String::from_utf8(output.stdout).expect("utf8");
let parsed: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
assert_eq!(parsed["rows"], 3);
}
#[test]
fn the_command_line_prints_a_table() {
let directory = temporary_directory("cli-table");
let path = fixture(&directory);
let output = std::process::Command::new(env!("CARGO_BIN_EXE_parquet"))
.args(["columns"])
.arg(&path)
.output()
.expect("the command runs");
assert!(output.status.success(), "the command failed");
let text = String::from_utf8(output.stdout).expect("utf8");
assert!(text.contains("id"), "the table names the column: {text}");
assert!(text.contains("path"), "the table names the column: {text}");
}
#[test]
fn a_file_can_be_converted() {
let directory = temporary_directory("convert");
let path = fixture(&directory);
let out = directory.join("events.csv");
rows::convert(&path, &out, rows::ConvertFormat::Csv).expect("the conversion works");
let text = std::fs::read_to_string(&out).expect("the output is readable");
assert!(text.starts_with("id,path,score,ok"), "the header: {text}");
assert!(text.contains("1,/a,1.5,true"), "the row: {text}");
}
#[test]
fn json_lines_keep_the_types() {
let directory = temporary_directory("jsonl");
let path = fixture(&directory);
let table = rows::head(&path, 3).expect("the rows are readable");
let mut buffer = Vec::new();
parquet_cli::output::write_table(&mut buffer, &table, Format::Jsonl).expect("the output works");
let text = String::from_utf8(buffer).expect("utf8");
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 3);
let first: serde_json::Value = serde_json::from_str(lines[0]).expect("valid JSON");
assert_eq!(first["id"], 1);
assert_eq!(first["score"], 1.5);
}