stock-bot/tools/curate-etl/tests/curate_posts.rs

250 lines
8.8 KiB
Rust

//! End-to-end tests for the file-mode curate-posts CLI.
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use bson::{doc, Document};
use curate_etl::bson_ceo_posts::CeoPostsTimestampUnit;
use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts, CuratePostsArgs};
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::RowAccessor;
const POSTED: i64 = 1_718_460_000;
const EDITED: i64 = POSTED + 3_600;
const PARTITION: &str = "events/year=2024/part-posts.parquet";
const EVENTS_PARTITION: &str = "events/year=2024/part.parquet";
const MAPPING: &str = "ceo_alt\tCH_1\t2020-01-01\t\t555\nceo_alt\tCH_2\t2020-01-01\t\t556\nqm\tSYM_1\t2020-01-01\t\t555\n";
const CUSTOM_FLAGS: &[&str] = &[
"--key-field=channel",
"--spiel-id-field=id",
"--timestamp-field=ts",
"--edited-field=ed",
"--bot-field=isBot",
"--user-id-field=author",
"--text-field=body",
"--mapping-source=ceo_alt",
];
struct TempDir(PathBuf);
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-posts");
command
}
fn curate(dir: &Path, out: &str, unit: &str) -> Output {
cli()
.current_dir(dir)
.args([
"--ceo-posts",
"posts.bson",
"--provider-mapping=mapping.tsv",
])
.args(["--out", out, "--timestamp-unit", unit])
.args(CUSTOM_FLAGS)
.output()
.expect("run curate-posts")
}
fn write_posts(path: &Path, scale: i64, edited_text: &str) {
let posts: [Document; 3] = [
doc! {
"channel": "CH_1", "id": "p-1", "ts": POSTED * scale,
"ed": EDITED * scale, "author": "u1", "body": edited_text,
},
doc! {
"channel": "CH_2", "id": "wire-1", "ts": POSTED * scale,
"isBot": "1", "body": "wire release",
},
doc! {
"channel": "unmapped", "id": "p-2", "ts": POSTED * scale,
"body": "unmapped post",
},
];
let bytes: Vec<u8> = posts
.iter()
.flat_map(|post| post.to_vec().unwrap())
.collect();
fs::write(path, bytes).expect("write concatenated BSON");
}
fn curate_events(dir: &Path, out: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
.arg("curate-events")
.current_dir(dir)
.args([
"--qm-filings",
"filings.bson",
"--qm-earnings",
"earnings.bson",
"--provider-mapping=mapping.tsv",
"--out",
out,
"--filings-form-type-field",
"formType",
])
.output()
.expect("run curate-events")
}
fn write_events_fixtures(dir: &Path) {
let filing = doc! {
"symbol": "SYM_1",
"timefiled": "2024-06-10T16:15:00 EDT",
"formType": "8-K",
};
let earning = doc! {
"qmSearchCode": "SYM_1",
"reportDate": "2024-06-12",
"announceTime": "AMC",
};
fs::write(dir.join("filings.bson"), filing.to_vec().unwrap()).expect("write filings.bson");
fs::write(dir.join("earnings.bson"), earning.to_vec().unwrap()).expect("write earnings.bson");
}
#[test]
fn cli_publishes_runner_equivalent_posts_and_copublishes_with_curate_events() {
// Use the runner's fixed custom-field and edited-post fixture, plus a wire and an unmapped row.
let path = std::env::temp_dir().join(format!("curate-posts-cli-{}", std::process::id()));
fs::create_dir(&path).expect("create isolated test directory");
let dir = TempDir(path);
let bson = dir.0.join("posts.bson");
let mapping = dir.0.join("mapping.tsv");
write_posts(&bson, 1, "hello");
fs::write(&mapping, MAPPING).unwrap();
let baseline_dir = dir.0.join("baseline");
let baseline_report = run_curate_posts(&CuratePostsArgs {
ceo_posts: bson.clone(),
provider_mapping: mapping,
out_dir: baseline_dir.clone(),
timestamp_unit: CeoPostsTimestampUnit::Seconds,
key_field: "channel".into(),
spiel_id_field: "id".into(),
timestamp_field: "ts".into(),
edited_field: "ed".into(),
bot_field: "isBot".into(),
user_id_field: "author".into(),
text_field: "body".into(),
mapping_source: "ceo_alt".into(),
})
.expect("run library baseline");
let baseline = fs::read(baseline_dir.join(PARTITION)).unwrap();
let expected_report = format_curate_posts_report(&baseline_report);
for (unit, scale) in [("seconds", 1), ("millis", 1_000)] {
write_posts(&bson, scale, "hello");
let result = curate(&dir.0, unit, unit);
assert!(result.status.success(), "{unit}: {:?}", result);
assert!(result.stderr.is_empty());
let stdout = String::from_utf8(result.stdout).unwrap();
assert_eq!(
stdout.lines().take(5).collect::<Vec<_>>(),
expected_report.lines().take(5).collect::<Vec<_>>()
);
assert!(stdout.contains("docs_framed=3"));
assert!(stdout.contains("dropped_unmapped=1"));
assert!(stdout.contains("rows_written=2"));
assert!(stdout.lines().last().unwrap().contains("timing:"));
assert_eq!(
fs::read(dir.0.join(unit).join(PARTITION)).unwrap(),
baseline
);
}
let partition = dir.0.join("millis").join(PARTITION);
let reader = SerializedFileReader::new(File::open(&partition).unwrap()).unwrap();
let rows: Vec<_> = reader
.get_row_iter(None)
.unwrap()
.map(Result::unwrap)
.collect();
assert_eq!(rows.len(), 2);
for (row, listing, subtype, known_at) in [
(&rows[0], 555, "retail", EDITED),
(&rows[1], 556, "newswire", POSTED),
] {
assert_eq!(row.get_int(0).unwrap(), listing);
assert_eq!(row.get_timestamp_micros(1).unwrap(), POSTED * 1_000_000);
assert_eq!(row.get_timestamp_micros(2).unwrap(), known_at * 1_000_000);
assert_eq!(row.get_string(4).unwrap(), "ceo_post");
assert_eq!(row.get_string(5).unwrap(), subtype);
}
let edited_text_visible = |cutoff| {
rows.iter().any(|row| {
row.get_timestamp_micros(2).unwrap() <= cutoff
&& row.get_string(6).unwrap().contains(r#""text":"hello""#)
})
};
assert!(!edited_text_visible(EDITED * 1_000_000 - 1));
assert!(edited_text_visible(EDITED * 1_000_000));
// Co-publish curate-events into the same --out and verify part-posts.parquet stays intact.
write_events_fixtures(&dir.0);
let ev_res = curate_events(&dir.0, "millis");
assert!(ev_res.status.success(), "curate-events: {:?}", ev_res);
assert!(ev_res.stderr.is_empty());
let events_part = dir.0.join("millis").join(EVENTS_PARTITION);
let events_bytes = fs::read(&events_part).unwrap();
assert_eq!(fs::read(&partition).unwrap(), baseline);
// Re-running curate-posts updates part-posts.parquet with exit code 0 while preserving part.parquet.
write_posts(&bson, 1_000, "replacement");
let retry = curate(&dir.0, "millis", "millis");
assert!(retry.status.success(), "curate-posts rerun: {:?}", retry);
assert!(retry.stderr.is_empty());
assert_eq!(fs::read(&events_part).unwrap(), events_bytes);
let rerun_reader = SerializedFileReader::new(File::open(&partition).unwrap()).unwrap();
let rerun_rows: Vec<_> = rerun_reader
.get_row_iter(None)
.unwrap()
.map(Result::unwrap)
.collect();
assert_eq!(rerun_rows.len(), 2);
assert_eq!(rerun_rows[0].get_string(4).unwrap(), "ceo_post");
assert!(rerun_rows[0]
.get_string(6)
.unwrap()
.contains(r#""text":"replacement""#));
}
#[test]
fn cli_reports_usage_for_invalid_posts_flags() {
for (args, error) in [
(
&["--from-mongo", "--ceo-posts", "p.bson"][..],
"cannot combine '--from-mongo' with '--ceo-posts'",
),
(
&["--mongo-uri", "mongodb://u:s3cr3t@localhost:27017/stock"][..],
"MongoDB streaming flags require '--from-mongo'",
),
(
&["--timestamp-unit", "--out=x"][..],
"missing value for flag '--timestamp-unit'",
),
(
&["--text-field=first", "--text-field", "second"][..],
"duplicate flag '--text-field'",
),
] {
let result = cli().args(args).output().expect("run curate-posts");
assert_eq!(result.status.code(), Some(1), "{args:?}");
assert!(result.stdout.is_empty(), "{args:?}");
let stderr = String::from_utf8(result.stderr).unwrap();
assert_eq!(
stderr.lines().next(),
Some(format!("error: {error}").as_str())
);
assert!(stderr.contains("curate-posts --ceo-posts"), "{stderr}");
}
}