Skip to content

Commit

Permalink
Do not spawn cargo subprocess for testing
Browse files Browse the repository at this point in the history
  • Loading branch information
samueltardieu committed Sep 24, 2023
1 parent 8694191 commit 81ca22f
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 71 deletions.
79 changes: 48 additions & 31 deletions aoc/src/run.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use chrono::{Datelike, Duration};
use clap::Parser;
use itertools::Itertools;
use std::fmt::Write;

#[derive(Parser)]
#[clap(version, author)]
Expand Down Expand Up @@ -46,6 +46,44 @@ fn pretty_duration(duration: Duration) -> String {
}
}

#[allow(clippy::module_name_repetitions)]
pub fn run_tests<F>(
register: F,
single_day: Option<usize>,
main_only: bool,
timings: bool,
) -> eyre::Result<String>
where
F: Fn(),
{
register();
let mut results = String::new();
let mut runners = super::runners::RUNNERS.lock().unwrap();
let keys = runners.keys().copied().collect::<Vec<_>>();
for (day, part) in keys {
if single_day.map_or(true, |d| d == day) {
for (version, runner) in runners.remove(&(day, part)).unwrap() {
if main_only && version.is_some() {
continue;
}
write!(&mut results, "Day {day} - part {part}")?;
if let Some(version) = version {
write!(&mut results, " — {version}")?;
}
let before = chrono::Utc::now();
let result = runner()?;
let after = chrono::Utc::now();
write!(&mut results, ": {result}")?;
if timings {
write!(&mut results, " ({})", pretty_duration(after - before))?;
}
writeln!(&mut results)?;
}
}
}
Ok(results)
}

pub fn run<F>(register: F) -> eyre::Result<()>
where
F: Fn(),
Expand All @@ -62,35 +100,14 @@ where
super::input::OVERRIDE_INPUT = opts.input;
}
let current_day = opts.day.unwrap_or(chrono::Utc::now().day() as usize);
register();
let mut runners = super::runners::RUNNERS.lock().unwrap();
let keys = runners.keys().copied().collect::<Vec<_>>();
for (day, part) in keys {
if day == current_day || opts.all {
for (version, runner) in runners.remove(&(day, part)).unwrap() {
if opts.main_only && version.is_some() {
continue;
}
let before = chrono::Utc::now();
let result = runner();
let after = chrono::Utc::now();
let version = version
.clone()
.map_or_else(String::new, |v| format!(" — {v}"));
let elapsed = if opts.timing {
format!(" ({})", pretty_duration(after - before))
} else {
String::new()
};
let header = format!("Day {day} - part {part}{version}: ");
let sep = format!("\n{}", " ".repeat(header.len()));
let result = match result {
Ok(e) => e.lines().join(&sep),
Err(e) => format!("<error: {e:?}>"),
};
println!("{header}{result}{elapsed}");
}
}
}
println!(
"{}",
run_tests(
register,
(!opts.all).then_some(current_day),
opts.main_only,
opts.timing
)?
);
Ok(())
}
20 changes: 6 additions & 14 deletions aoc/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,6 @@ use std::process::Command;

const ENV_VAR: &str = "RECORD_RESULTS";

fn run_with(args: &[&str]) -> eyre::Result<String> {
let output = Command::new("cargo")
.args(["run", "--release", "--", "-a"])
.args(args)
.output()?;
Ok(String::from_utf8(output.stdout)?)
}

fn equal_content<P: AsRef<Path>>(actual: &str, expected: P, show_diff: bool) -> eyre::Result<bool> {
let expected_content = std::fs::read_to_string(expected.as_ref()).context(format!(
"cannot read {}",
Expand Down Expand Up @@ -41,12 +33,12 @@ fn equal_content<P: AsRef<Path>>(actual: &str, expected: P, show_diff: bool) ->
}
}

pub fn check_results<P: AsRef<Path>>(expected: P, main_only: bool) -> eyre::Result<bool> {
let actual = if main_only {
run_with(&["-m"])?
} else {
run_with(&[])?
};
pub fn check_results<F: Fn(), P: AsRef<Path>>(
register: F,
expected: P,
main_only: bool,
) -> eyre::Result<bool> {
let actual = super::run::run_tests(register, None, false, main_only)?;
let update = std::env::var(ENV_VAR).is_ok();
if update {
if !matches!(equal_content(&actual, &expected, false), Ok(true)) {
Expand Down
18 changes: 0 additions & 18 deletions aoc/tests/dummy-year.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,3 @@ fn all_days_main() {
Day 2 - part 2: 3842356
"###);
}

#[test]
#[serial]
fn check_expected_main() {
let dir = std::env::current_dir().unwrap();
std::env::set_current_dir("../dummy-year").unwrap();
assert!(aoc::test::check_results("expected.txt", true).unwrap());
std::env::set_current_dir(dir).unwrap();
}

#[test]
#[serial]
fn check_expected() {
let dir = std::env::current_dir().unwrap();
std::env::set_current_dir("../dummy-year").unwrap();
assert!(aoc::test::check_results("expected-all.txt", false).unwrap());
std::env::set_current_dir(dir).unwrap();
}
7 changes: 0 additions & 7 deletions dummy-year/expected-all.txt

This file was deleted.

3 changes: 3 additions & 0 deletions dummy-year/expected.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
Day 1 - part 1: 232
Day 1 - part 1 — str_slice: 232
Day 1 - part 2: 1783
Day 1 - part 2 — result: 1783
Day 1 - part 2 — result_string: 1783
Day 2 - part 1: 1606483
Day 2 - part 2: 3842356
2 changes: 1 addition & 1 deletion dummy-year/src/day1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ fn part1(input: &str) -> usize {

#[aoc(day1, part1, str_slice)]
fn part1_string_slice(input: &[&str]) -> usize {
input.iter().cloned().map(part1).sum()
input.iter().copied().map(part1).sum()
}

#[aoc(day1, part2)]
Expand Down
9 changes: 9 additions & 0 deletions dummy-year/tests/check-expected.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#[test]
fn check_expected() {
assert!(aoc::test::check_results(
dummy_year::register::register_runners,
"expected.txt",
false
)
.unwrap());
}

0 comments on commit 81ca22f

Please sign in to comment.