812 lines
27 KiB
Rust
812 lines
27 KiB
Rust
//! End-to-end tests for the file-mode `curate-fundamentals` CLI.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::fs::{self, File};
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
use bson::raw::{cstr, RawDocumentBuf};
|
|
use curate_etl::fundamentals::FundamentalsFields;
|
|
use curate_etl::run_curate_fundamentals::{
|
|
format_curate_fundamentals_report, run_curate_fundamentals, CurateFundamentalsArgs,
|
|
CurateFundamentalsFiscalPeriod,
|
|
};
|
|
use curate_etl::shorts::et_to_utc_micros;
|
|
use curate_etl::split::ymd_to_epoch_days;
|
|
use parquet::file::reader::{FileReader, SerializedFileReader};
|
|
use parquet::record::{Field, Row};
|
|
|
|
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
|
|
|
struct TempDir(PathBuf);
|
|
|
|
impl TempDir {
|
|
fn new(label: &str) -> Self {
|
|
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
|
|
let path = std::env::temp_dir().join(format!(
|
|
"curate-fundamentals-cli-{label}-{}-{seq}",
|
|
std::process::id()
|
|
));
|
|
let _ = fs::remove_dir_all(&path);
|
|
fs::create_dir_all(&path).expect("create isolated test directory");
|
|
Self(path)
|
|
}
|
|
}
|
|
|
|
impl Drop for TempDir {
|
|
fn drop(&mut self) {
|
|
let _ = fs::remove_dir_all(&self.0);
|
|
}
|
|
}
|
|
|
|
fn cli() -> Command {
|
|
let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl"));
|
|
command.arg("curate-fundamentals");
|
|
command
|
|
}
|
|
|
|
fn make_financials_doc(
|
|
key: &str,
|
|
period_end: &str,
|
|
report_date: &str,
|
|
report_period: &str,
|
|
currency: &str,
|
|
fields: FundamentalsFields,
|
|
) -> Vec<u8> {
|
|
let mut doc = RawDocumentBuf::new();
|
|
doc.append(cstr!("qmSearchCode"), key);
|
|
doc.append(cstr!("periodEndDate"), period_end);
|
|
doc.append(cstr!("reportDate"), report_date);
|
|
doc.append(cstr!("reportPeriod"), report_period);
|
|
doc.append(cstr!("currency"), currency);
|
|
|
|
let mut income = RawDocumentBuf::new();
|
|
if let Some(v) = fields.revenue {
|
|
income.append(cstr!("revenue"), v);
|
|
}
|
|
if let Some(v) = fields.net_income {
|
|
income.append(cstr!("netIncome"), v);
|
|
}
|
|
doc.append(cstr!("IncomeStatement"), income);
|
|
|
|
let mut cashflow = RawDocumentBuf::new();
|
|
if let Some(v) = fields.operating_cash_flow {
|
|
cashflow.append(cstr!("operatingCashFlow"), v);
|
|
}
|
|
doc.append(cstr!("CashFlow"), cashflow);
|
|
|
|
let mut balance = RawDocumentBuf::new();
|
|
if let Some(v) = fields.total_assets {
|
|
balance.append(cstr!("totalAssets"), v);
|
|
}
|
|
if let Some(v) = fields.total_equity {
|
|
balance.append(cstr!("totalEquity"), v);
|
|
}
|
|
if let Some(v) = fields.shares_outstanding {
|
|
balance.append(cstr!("sharesOutstanding"), v);
|
|
}
|
|
doc.append(cstr!("BalanceSheet"), balance);
|
|
|
|
doc.into_bytes()
|
|
}
|
|
|
|
fn make_filing_doc(key: &str, timefiled: &str, form_type: &str, filing_id: &str) -> Vec<u8> {
|
|
let mut doc = RawDocumentBuf::new();
|
|
doc.append(cstr!("symbol"), key);
|
|
doc.append(cstr!("timefiled"), timefiled);
|
|
doc.append(cstr!("formType"), form_type);
|
|
doc.append(cstr!("filingId"), filing_id);
|
|
doc.into_bytes()
|
|
}
|
|
|
|
fn read_parquet_partitions(out_dir: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
|
|
let dataset_root = out_dir.join("fundamentals_pit");
|
|
let mut files = BTreeMap::new();
|
|
for entry in fs::read_dir(&dataset_root).expect("read fundamentals_pit dir") {
|
|
let entry = entry.expect("dir entry");
|
|
let name = entry.file_name();
|
|
let part_path = entry.path().join("part.parquet");
|
|
assert!(
|
|
part_path.is_file(),
|
|
"expected part.parquet in {}",
|
|
entry.path().display()
|
|
);
|
|
let rel = PathBuf::from(&name).join("part.parquet");
|
|
files.insert(rel, fs::read(&part_path).expect("read parquet bytes"));
|
|
}
|
|
files
|
|
}
|
|
|
|
fn write_restatement_fixture(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
|
|
let fin_path = dir.join("qmFinancials.bson");
|
|
let fil_path = dir.join("qmFilings.bson");
|
|
let map_path = dir.join("provider_mapping.tsv");
|
|
let venues_path = dir.join("listing_venues.tsv");
|
|
|
|
fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap();
|
|
fs::write(&venues_path, "301\tus_tsx\n").unwrap();
|
|
|
|
// Specimen dates and field shapes from `run_curate_fundamentals_tests`:
|
|
// four contiguous quarters (Q3 2023 .. Q2 2024) plus a late Q1 2024 restatement (10-Q/A on
|
|
// 2024-09-15) and an unmapped observation.
|
|
let mut fin_bytes = Vec::new();
|
|
for (key, pe, rd, rp, rev, ni, ocf, ta, te, sh) in [
|
|
(
|
|
"ACME",
|
|
"2023-09-30",
|
|
"2023-11-05",
|
|
"Q3",
|
|
90.0,
|
|
8.0,
|
|
10.0,
|
|
460.0,
|
|
275.0,
|
|
20.0,
|
|
),
|
|
(
|
|
"ACME",
|
|
"2023-12-31",
|
|
"2024-02-20",
|
|
"Q4",
|
|
110.0,
|
|
11.0,
|
|
14.0,
|
|
480.0,
|
|
288.0,
|
|
20.0,
|
|
),
|
|
(
|
|
"ACME",
|
|
"2024-03-31",
|
|
"2024-05-05",
|
|
"Q1",
|
|
100.0,
|
|
10.0,
|
|
12.0,
|
|
500.0,
|
|
300.0,
|
|
20.0,
|
|
),
|
|
(
|
|
"ACME",
|
|
"2024-06-30",
|
|
"2024-08-05",
|
|
"Q2",
|
|
250.0,
|
|
30.0,
|
|
35.0,
|
|
550.0,
|
|
330.0,
|
|
20.0,
|
|
),
|
|
(
|
|
"ACME",
|
|
"2024-03-31",
|
|
"2024-09-15",
|
|
"Q1",
|
|
88.0,
|
|
4.0,
|
|
9.0,
|
|
490.0,
|
|
294.0,
|
|
20.0,
|
|
),
|
|
(
|
|
"UNMAPPED",
|
|
"2024-06-30",
|
|
"2024-08-05",
|
|
"Q2",
|
|
50.0,
|
|
5.0,
|
|
6.0,
|
|
100.0,
|
|
60.0,
|
|
10.0,
|
|
),
|
|
] {
|
|
fin_bytes.extend_from_slice(&make_financials_doc(
|
|
key,
|
|
pe,
|
|
rd,
|
|
rp,
|
|
"USD",
|
|
FundamentalsFields {
|
|
revenue: Some(rev),
|
|
net_income: Some(ni),
|
|
operating_cash_flow: Some(ocf),
|
|
total_assets: Some(ta),
|
|
total_equity: Some(te),
|
|
shares_outstanding: Some(sh),
|
|
},
|
|
));
|
|
}
|
|
fs::write(&fin_path, fin_bytes).unwrap();
|
|
|
|
let mut fil_bytes = Vec::new();
|
|
for (key, ts, form, id) in [
|
|
("ACME", "2023-11-05T16:10:00 EST", "10-Q", "q3-2023-1"),
|
|
("ACME", "2024-02-20T16:10:00 EST", "10-Q", "q4-2023-1"),
|
|
("ACME", "2024-05-05T16:10:00 EDT", "10-Q", "q1-2024-1"),
|
|
("ACME", "2024-08-05T16:15:00 EDT", "10-Q", "q2-2024-1"),
|
|
("ACME", "2024-09-15T16:20:00 EDT", "10-Q/A", "q1-2024-a"),
|
|
] {
|
|
fil_bytes.extend_from_slice(&make_filing_doc(key, ts, form, id));
|
|
}
|
|
fs::write(&fil_path, fil_bytes).unwrap();
|
|
|
|
(fin_path, fil_path, map_path, venues_path)
|
|
}
|
|
|
|
#[test]
|
|
fn cli_publishes_runner_equivalent_fundamentals_and_preserves_pit_restatement() {
|
|
let dir = TempDir::new("e2e");
|
|
let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0);
|
|
|
|
let baseline_dir = dir.0.join("baseline");
|
|
let mut baseline_args = CurateFundamentalsArgs::with_verified_defaults(
|
|
fin_path.clone(),
|
|
fil_path.clone(),
|
|
map_path.clone(),
|
|
venues_path.clone(),
|
|
baseline_dir.clone(),
|
|
"currency",
|
|
Some("IncomeStatement.revenue".to_string()),
|
|
Some("IncomeStatement.netIncome".to_string()),
|
|
Some("CashFlow.operatingCashFlow".to_string()),
|
|
Some("BalanceSheet.totalAssets".to_string()),
|
|
Some("BalanceSheet.totalEquity".to_string()),
|
|
Some("BalanceSheet.sharesOutstanding".to_string()),
|
|
CurateFundamentalsFiscalPeriod::ByTokens {
|
|
quarterly: vec![
|
|
"Q1".to_string(),
|
|
"Q2".to_string(),
|
|
"Q3".to_string(),
|
|
"Q4".to_string(),
|
|
],
|
|
annual: vec!["FY".to_string()],
|
|
},
|
|
"formType",
|
|
4,
|
|
);
|
|
baseline_args.filings_filing_id_field = Some("filingId".to_string());
|
|
|
|
let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline");
|
|
let expected_report = format_curate_fundamentals_report(&baseline_report);
|
|
let baseline_partitions = read_parquet_partitions(&baseline_dir);
|
|
assert!(
|
|
baseline_partitions.contains_key(Path::new("year=2024/part.parquet")),
|
|
"expected nonempty 2024 partition"
|
|
);
|
|
|
|
let cli_out = dir.0.join("cli_out");
|
|
let result = cli()
|
|
.current_dir(&dir.0)
|
|
.args([
|
|
"--qm-financials",
|
|
"qmFinancials.bson",
|
|
"--qm-filings=qmFilings.bson",
|
|
"--provider-mapping",
|
|
"provider_mapping.tsv",
|
|
"--listing-venues=listing_venues.tsv",
|
|
"--out",
|
|
"cli_out",
|
|
"--currency-field=currency",
|
|
"--filings-form-type-field",
|
|
"formType",
|
|
"--filings-filing-id-field=filingId",
|
|
"--k",
|
|
"4",
|
|
"--quarterly-tokens=Q1,Q2,Q3,Q4",
|
|
"--annual-tokens",
|
|
"FY",
|
|
"--revenue-field",
|
|
"IncomeStatement.revenue",
|
|
"--net-income-field=IncomeStatement.netIncome",
|
|
"--operating-cash-flow-field",
|
|
"CashFlow.operatingCashFlow",
|
|
"--total-assets-field=BalanceSheet.totalAssets",
|
|
"--total-equity-field",
|
|
"BalanceSheet.totalEquity",
|
|
"--shares-outstanding-field=BalanceSheet.sharesOutstanding",
|
|
])
|
|
.output()
|
|
.expect("run curate-fundamentals");
|
|
|
|
assert!(result.status.success(), "{result:?}");
|
|
assert!(
|
|
result.stderr.is_empty(),
|
|
"unexpected stderr: {}",
|
|
String::from_utf8_lossy(&result.stderr)
|
|
);
|
|
|
|
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
|
|
let actual_lines: Vec<&str> = stdout.lines().collect();
|
|
let expected_lines: Vec<&str> = expected_report.lines().collect();
|
|
assert_eq!(actual_lines.len(), expected_lines.len(), "{stdout}");
|
|
assert_eq!(
|
|
&actual_lines[..actual_lines.len() - 1],
|
|
&expected_lines[..expected_lines.len() - 1],
|
|
"deterministic report lines must match library baseline"
|
|
);
|
|
let timing_line = *actual_lines.last().unwrap();
|
|
let elapsed_str = timing_line
|
|
.strip_prefix(" timing: elapsed_secs=")
|
|
.unwrap_or_else(|| panic!("unexpected timing line: {timing_line:?}"));
|
|
let elapsed: f64 = elapsed_str.parse().expect("valid elapsed_secs float");
|
|
assert!(elapsed.is_finite() && elapsed >= 0.0, "{timing_line}");
|
|
|
|
let cli_partitions = read_parquet_partitions(&cli_out);
|
|
assert_eq!(
|
|
cli_partitions.keys().collect::<Vec<_>>(),
|
|
baseline_partitions.keys().collect::<Vec<_>>(),
|
|
"partition paths must match baseline"
|
|
);
|
|
for (rel, expected_bytes) in &baseline_partitions {
|
|
assert_eq!(
|
|
cli_partitions.get(rel).unwrap(),
|
|
expected_bytes,
|
|
"Parquet bytes differ for {}",
|
|
rel.display()
|
|
);
|
|
}
|
|
|
|
// Read the 2024 partition and verify listing, currency, metric value, filing-derived known_at,
|
|
// and PIT restatement isolation (Q1 restatement only visible at 2024-09-15).
|
|
let part_2024 = cli_out.join("fundamentals_pit/year=2024/part.parquet");
|
|
let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap();
|
|
let rows: Vec<_> = reader
|
|
.get_row_iter(None)
|
|
.unwrap()
|
|
.map(Result::unwrap)
|
|
.collect();
|
|
assert_eq!(
|
|
rows.len(),
|
|
4,
|
|
"expected Q4-23, Q1-24, Q2-24, and Q1-24/A snapshots in 2024"
|
|
);
|
|
|
|
let q2_filed_micros =
|
|
et_to_utc_micros(ymd_to_epoch_days(2024, 8, 5).unwrap(), 16, 15, 0).unwrap();
|
|
let restate_filed_micros =
|
|
et_to_utc_micros(ymd_to_epoch_days(2024, 9, 15).unwrap(), 16, 20, 0).unwrap();
|
|
|
|
fn col<'a>(row: &'a Row, name: &str) -> &'a Field {
|
|
row.get_column_iter()
|
|
.find(|(col_name, _)| col_name.as_str() == name)
|
|
.unwrap_or_else(|| panic!("missing Parquet column '{name}'"))
|
|
.1
|
|
}
|
|
|
|
let q2_row = &rows[2];
|
|
assert_eq!(col(q2_row, "listing_id"), &Field::Int(301));
|
|
assert_eq!(
|
|
col(q2_row, "effective_known_at"),
|
|
&Field::TimestampMicros(q2_filed_micros)
|
|
);
|
|
assert_eq!(
|
|
col(q2_row, "known_at_source"),
|
|
&Field::Str("filing_timestamp".to_string())
|
|
);
|
|
assert_eq!(
|
|
col(q2_row, "period_end"),
|
|
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
|
|
);
|
|
assert_eq!(col(q2_row, "currency"), &Field::Str("USD".to_string()));
|
|
assert_eq!(col(q2_row, "revenue"), &Field::Double(250.0));
|
|
assert_eq!(col(q2_row, "ttm_revenue"), &Field::Double(550.0));
|
|
|
|
let restated_row = &rows[3];
|
|
assert_eq!(col(restated_row, "listing_id"), &Field::Int(301));
|
|
assert_eq!(
|
|
col(restated_row, "effective_known_at"),
|
|
&Field::TimestampMicros(restate_filed_micros)
|
|
);
|
|
assert_eq!(
|
|
col(restated_row, "known_at_source"),
|
|
&Field::Str("filing_timestamp".to_string())
|
|
);
|
|
// Latest period remains Q2 2024 (250.0 revenue) while TTM revenue reflects the -12.0 Q1 restatement.
|
|
assert_eq!(
|
|
col(restated_row, "period_end"),
|
|
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
|
|
);
|
|
assert_eq!(
|
|
col(restated_row, "currency"),
|
|
&Field::Str("USD".to_string())
|
|
);
|
|
assert_eq!(col(restated_row, "revenue"), &Field::Double(250.0));
|
|
assert_eq!(col(restated_row, "ttm_revenue"), &Field::Double(538.0));
|
|
}
|
|
|
|
#[test]
|
|
fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() {
|
|
let dir = TempDir::new("fail-closed");
|
|
let (_fin_path, _fil_path, _map_path, _venues_path) = write_restatement_fixture(&dir.0);
|
|
|
|
let out_missing_k = dir.0.join("out_missing_k");
|
|
let res_missing_k = cli()
|
|
.current_dir(&dir.0)
|
|
.args([
|
|
"--qm-financials",
|
|
"qmFinancials.bson",
|
|
"--qm-filings",
|
|
"qmFilings.bson",
|
|
"--provider-mapping",
|
|
"provider_mapping.tsv",
|
|
"--listing-venues",
|
|
"listing_venues.tsv",
|
|
"--out",
|
|
"out_missing_k",
|
|
"--currency-field",
|
|
"currency",
|
|
"--filings-form-type-field",
|
|
"formType",
|
|
"--fiscal-period",
|
|
"quarterly",
|
|
])
|
|
.output()
|
|
.expect("run curate-fundamentals missing --k");
|
|
|
|
assert_eq!(res_missing_k.status.code(), Some(1));
|
|
assert!(res_missing_k.stdout.is_empty());
|
|
let stderr_k = String::from_utf8(res_missing_k.stderr).unwrap();
|
|
let mut lines_k = stderr_k.lines();
|
|
assert_eq!(lines_k.next(), Some("error: missing required flag '--k'"));
|
|
assert_eq!(lines_k.next(), Some("Usage:"));
|
|
assert!(
|
|
stderr_k.contains("curate-fundamentals --qm-financials"),
|
|
"{stderr_k}"
|
|
);
|
|
assert!(!out_missing_k.exists(), "out_missing_k must not be created");
|
|
|
|
let out_from_mongo = dir.0.join("out_from_mongo");
|
|
let res_mongo = cli()
|
|
.current_dir(&dir.0)
|
|
.args([
|
|
"--from-mongo",
|
|
"--qm-financials",
|
|
"qmFinancials.bson",
|
|
"--qm-filings",
|
|
"qmFilings.bson",
|
|
"--provider-mapping",
|
|
"provider_mapping.tsv",
|
|
"--listing-venues",
|
|
"listing_venues.tsv",
|
|
"--out",
|
|
"out_from_mongo",
|
|
"--currency-field",
|
|
"currency",
|
|
"--filings-form-type-field",
|
|
"formType",
|
|
"--k",
|
|
"4",
|
|
"--fiscal-period",
|
|
"quarterly",
|
|
])
|
|
.output()
|
|
.expect("run curate-fundamentals with --from-mongo");
|
|
|
|
assert_eq!(res_mongo.status.code(), Some(1));
|
|
assert!(res_mongo.stdout.is_empty());
|
|
let stderr_mongo = String::from_utf8(res_mongo.stderr).unwrap();
|
|
let mut lines_mongo = stderr_mongo.lines();
|
|
assert_eq!(
|
|
lines_mongo.next(),
|
|
Some("error: cannot combine '--from-mongo' with '--qm-financials', '--qm-financials-old', or '--qm-filings'")
|
|
);
|
|
assert_eq!(lines_mongo.next(), Some("Usage:"));
|
|
assert!(
|
|
stderr_mongo.contains("curate-fundamentals --qm-financials"),
|
|
"{stderr_mongo}"
|
|
);
|
|
assert!(
|
|
!out_from_mongo.exists(),
|
|
"out_from_mongo must not be created"
|
|
);
|
|
}
|
|
|
|
const FIXTURE_REQUIRED_ARGS: [&str; 14] = [
|
|
"--qm-financials",
|
|
"qmFinancials.bson",
|
|
"--qm-filings",
|
|
"qmFilings.bson",
|
|
"--provider-mapping",
|
|
"provider_mapping.tsv",
|
|
"--listing-venues",
|
|
"listing_venues.tsv",
|
|
"--currency-field",
|
|
"currency",
|
|
"--filings-form-type-field",
|
|
"formType",
|
|
"--k",
|
|
"4",
|
|
];
|
|
|
|
fn assert_single_line_error_then_usage(stderr: &[u8], expected_error: &str) {
|
|
let text = String::from_utf8(stderr.to_vec()).expect("utf-8 stderr");
|
|
let mut lines = text.lines();
|
|
assert_eq!(lines.next(), Some(expected_error), "{text}");
|
|
assert_eq!(lines.next(), Some("Usage:"), "{text}");
|
|
assert!(
|
|
text.contains("curate-fundamentals --qm-financials"),
|
|
"{text}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn cli_fixed_fiscal_period_without_metric_fields_matches_runner_and_writes_null_metrics() {
|
|
let dir = TempDir::new("fixed-null-metrics");
|
|
let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0);
|
|
|
|
let baseline_dir = dir.0.join("baseline");
|
|
let baseline_args = CurateFundamentalsArgs::with_verified_defaults(
|
|
fin_path,
|
|
fil_path,
|
|
map_path,
|
|
venues_path,
|
|
baseline_dir.clone(),
|
|
"currency",
|
|
None,
|
|
None,
|
|
None,
|
|
None,
|
|
None,
|
|
None,
|
|
CurateFundamentalsFiscalPeriod::Fixed(curate_etl::fundamentals::FiscalPeriod::Quarterly),
|
|
"formType",
|
|
4,
|
|
);
|
|
let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline");
|
|
let expected_report = format_curate_fundamentals_report(&baseline_report);
|
|
let baseline_partitions = read_parquet_partitions(&baseline_dir);
|
|
|
|
let result = cli()
|
|
.current_dir(&dir.0)
|
|
.args(FIXTURE_REQUIRED_ARGS)
|
|
.args(["--out=cli_out", "--fiscal-period=quarterly"])
|
|
.output()
|
|
.expect("run curate-fundamentals");
|
|
assert!(result.status.success(), "{result:?}");
|
|
assert!(result.stderr.is_empty(), "{result:?}");
|
|
|
|
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
|
|
let actual: Vec<&str> = stdout.lines().collect();
|
|
let expected: Vec<&str> = expected_report.lines().collect();
|
|
assert_eq!(actual.len(), expected.len(), "{stdout}");
|
|
assert_eq!(actual[..actual.len() - 1], expected[..expected.len() - 1]);
|
|
|
|
let cli_partitions = read_parquet_partitions(&dir.0.join("cli_out"));
|
|
assert_eq!(cli_partitions, baseline_partitions);
|
|
|
|
let part_2024 = dir
|
|
.0
|
|
.join("cli_out/fundamentals_pit/year=2024/part.parquet");
|
|
let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap();
|
|
let rows: Vec<Row> = reader
|
|
.get_row_iter(None)
|
|
.unwrap()
|
|
.map(Result::unwrap)
|
|
.collect();
|
|
assert!(!rows.is_empty(), "expected nonempty 2024 partition");
|
|
for row in &rows {
|
|
let revenue = row
|
|
.get_column_iter()
|
|
.find(|(name, _)| name.as_str() == "revenue")
|
|
.expect("revenue column")
|
|
.1;
|
|
assert_eq!(revenue, &Field::Null, "unconfigured metric must be NULL");
|
|
let currency = row
|
|
.get_column_iter()
|
|
.find(|(name, _)| name.as_str() == "currency")
|
|
.expect("currency column")
|
|
.1;
|
|
assert_eq!(currency, &Field::Str("USD".to_string()));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn cli_rerun_into_fresh_out_dir_is_byte_deterministic() {
|
|
let dir = TempDir::new("rerun");
|
|
write_restatement_fixture(&dir.0);
|
|
|
|
for out in ["run_a", "run_b"] {
|
|
let result = cli()
|
|
.current_dir(&dir.0)
|
|
.args(FIXTURE_REQUIRED_ARGS)
|
|
.args(["--out", out, "--quarterly-tokens", "Q1,Q2,Q3,Q4"])
|
|
.args(["--revenue-field", "IncomeStatement.revenue"])
|
|
.output()
|
|
.expect("run curate-fundamentals");
|
|
assert!(result.status.success(), "{result:?}");
|
|
}
|
|
|
|
let a = read_parquet_partitions(&dir.0.join("run_a"));
|
|
let b = read_parquet_partitions(&dir.0.join("run_b"));
|
|
assert!(!a.is_empty());
|
|
assert_eq!(
|
|
a, b,
|
|
"identical inputs must publish identical Parquet bytes"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn cli_runner_failure_on_missing_input_exits_nonzero_single_line_without_usage_or_output() {
|
|
let dir = TempDir::new("missing-input");
|
|
write_restatement_fixture(&dir.0);
|
|
fs::remove_file(dir.0.join("qmFilings.bson")).unwrap();
|
|
|
|
let result = cli()
|
|
.current_dir(&dir.0)
|
|
.args(FIXTURE_REQUIRED_ARGS)
|
|
.args(["--out", "out", "--fiscal-period", "quarterly"])
|
|
.output()
|
|
.expect("run curate-fundamentals");
|
|
|
|
assert_eq!(result.status.code(), Some(1));
|
|
assert!(result.stdout.is_empty());
|
|
let stderr = String::from_utf8(result.stderr).unwrap();
|
|
assert_eq!(stderr.lines().count(), 1, "{stderr}");
|
|
assert!(stderr.starts_with("error: "), "{stderr}");
|
|
assert!(stderr.contains("qmFilings.bson"), "{stderr}");
|
|
assert!(!stderr.contains("Usage:"), "{stderr}");
|
|
assert!(!dir.0.join("out").exists(), "out must not be created");
|
|
}
|
|
|
|
#[test]
|
|
fn cli_truncated_financials_dump_fails_closed_without_publishing() {
|
|
let dir = TempDir::new("truncated");
|
|
write_restatement_fixture(&dir.0);
|
|
fs::write(dir.0.join("qmFinancials.bson"), [0x10u8, 0x00, 0x00]).unwrap();
|
|
|
|
let result = cli()
|
|
.current_dir(&dir.0)
|
|
.args(FIXTURE_REQUIRED_ARGS)
|
|
.args(["--out", "out", "--fiscal-period", "quarterly"])
|
|
.output()
|
|
.expect("run curate-fundamentals");
|
|
|
|
assert_eq!(result.status.code(), Some(1));
|
|
assert!(result.stdout.is_empty());
|
|
let stderr = String::from_utf8(result.stderr).unwrap();
|
|
assert_eq!(stderr.lines().count(), 1, "{stderr}");
|
|
assert!(stderr.starts_with("error: "), "{stderr}");
|
|
assert!(!dir.0.join("out/fundamentals_pit").exists());
|
|
}
|
|
|
|
#[test]
|
|
fn cli_parse_time_config_errors_fail_closed_before_touching_out() {
|
|
let dir = TempDir::new("config-errors");
|
|
write_restatement_fixture(&dir.0);
|
|
|
|
let cases: [(&[&str], &str); 4] = [
|
|
(
|
|
&["--quarterly-tokens", "Q1,FY", "--annual-tokens", "FY"],
|
|
"error: invalid qmFinancials fiscal period configuration: report_period token 'FY' cannot appear in both quarterly and annual lists",
|
|
),
|
|
(
|
|
&["--fiscal-period", "quarterly", "--quarterly-tokens", "Q1"],
|
|
"error: cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'",
|
|
),
|
|
(
|
|
&["--fiscal-period", "quarterly", "--mongo-uri", "mongodb://localhost:27017/stock"],
|
|
"error: MongoDB streaming flags require '--from-mongo'",
|
|
),
|
|
(
|
|
&["--fiscal-period", "quarterly", "--k", "0"],
|
|
"error: duplicate flag '--k'",
|
|
),
|
|
];
|
|
|
|
for (idx, (extra, expected_error)) in cases.iter().enumerate() {
|
|
let out = format!("out_{idx}");
|
|
let result = cli()
|
|
.current_dir(&dir.0)
|
|
.args(FIXTURE_REQUIRED_ARGS)
|
|
.args(["--out", out.as_str()])
|
|
.args(*extra)
|
|
.output()
|
|
.expect("run curate-fundamentals");
|
|
assert_eq!(result.status.code(), Some(1), "case {idx}");
|
|
assert!(result.stdout.is_empty(), "case {idx}");
|
|
assert_single_line_error_then_usage(&result.stderr, expected_error);
|
|
assert!(
|
|
!dir.0.join(&out).exists(),
|
|
"case {idx}: out must not be created"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn cli_supports_qm_financials_old_curate_inputs_and_blocks_unsafe_mongo_uri() {
|
|
let dir = TempDir::new("old-and-curate-inputs");
|
|
write_restatement_fixture(&dir.0);
|
|
|
|
// Create a committed curate-inputs/<gen> + current symlink layout.
|
|
let inputs_root = dir.0.join("curate_inputs");
|
|
let gen_dir = inputs_root.join("gen-1");
|
|
std::fs::create_dir_all(&gen_dir).unwrap();
|
|
std::fs::copy(
|
|
dir.0.join("provider_mapping.tsv"),
|
|
gen_dir.join("provider_mapping.tsv"),
|
|
)
|
|
.unwrap();
|
|
std::fs::copy(
|
|
dir.0.join("listing_venues.tsv"),
|
|
gen_dir.join("listing_venues.tsv"),
|
|
)
|
|
.unwrap();
|
|
#[cfg(unix)]
|
|
std::os::unix::fs::symlink(&gen_dir, inputs_root.join("current")).unwrap();
|
|
|
|
// Run with --qm-financials-old (empty BSON) + --curate-inputs.
|
|
let old_bson = dir.0.join("qmFinancials-old.bson");
|
|
std::fs::write(&old_bson, b"").unwrap();
|
|
let out_dir = dir.0.join("out_curate_inputs");
|
|
let res = cli()
|
|
.current_dir(&dir.0)
|
|
.args([
|
|
"--qm-financials",
|
|
"qmFinancials.bson",
|
|
"--qm-financials-old",
|
|
"qmFinancials-old.bson",
|
|
"--qm-filings",
|
|
"qmFilings.bson",
|
|
"--curate-inputs",
|
|
"curate_inputs",
|
|
"--out",
|
|
"out_curate_inputs",
|
|
"--currency-field",
|
|
"currency",
|
|
"--filings-form-type-field",
|
|
"formType",
|
|
"--k",
|
|
"4",
|
|
"--quarterly-tokens",
|
|
"Q1,Q2,Q3,Q4",
|
|
])
|
|
.output()
|
|
.expect("run curate-fundamentals with --qm-financials-old and --curate-inputs");
|
|
assert!(
|
|
res.status.success(),
|
|
"stderr: {}",
|
|
String::from_utf8_lossy(&res.stderr)
|
|
);
|
|
assert!(out_dir.join("fundamentals_pit").is_dir());
|
|
|
|
// Fail-closed mongo_safety check on trading_admin URI: redacts password and creates no --out.
|
|
let out_unsafe = dir.0.join("out_unsafe_mongo");
|
|
let secret = "T212_ADMIN_SECRET_PW";
|
|
let unsafe_uri =
|
|
format!("mongodb://trading_admin:{secret}@localhost:27017/stock?authSource=admin");
|
|
let res_unsafe = cli()
|
|
.current_dir(&dir.0)
|
|
.args([
|
|
"--from-mongo",
|
|
"--mongo-uri",
|
|
&unsafe_uri,
|
|
"--with-qm-financials-old",
|
|
"--curate-inputs",
|
|
"curate_inputs",
|
|
"--out",
|
|
"out_unsafe_mongo",
|
|
"--currency-field",
|
|
"currency",
|
|
"--filings-form-type-field",
|
|
"formType",
|
|
"--k",
|
|
"4",
|
|
"--fiscal-period",
|
|
"quarterly",
|
|
])
|
|
.output()
|
|
.expect("run curate-fundamentals --from-mongo with trading_admin");
|
|
assert_eq!(res_unsafe.status.code(), Some(1));
|
|
assert!(res_unsafe.stdout.is_empty());
|
|
let stderr = String::from_utf8_lossy(&res_unsafe.stderr);
|
|
assert!(
|
|
!stderr.contains(secret),
|
|
"secret leaked in stderr: {stderr}"
|
|
);
|
|
assert!(!out_unsafe.exists(), "unsafe URI must not create --out");
|
|
}
|