Menu
CoddyTech

Testing Public Contracts

Lesson 41 of 48 in Coddy's Rust for C# Developers course.

A test should check behavior that callers rely on, not the implementation's internal representation. The C# program uses a small explicit assertion helper so it needs no test framework package. Rust has built-in assertion macros and a test harness enabled by rustc --test. Ordinary compilation excludes a module marked #[cfg(test)]; merely running main does not execute those tests. The Rust example has both a normal entry point and a separate test module, and both compilation modes are validated for this course. The examples check ASCII text, including the highest ASCII code, the next Unicode scalar, and empty input. Boundaries distinguish plausible wrong implementations from the intended rule. A passing example test is not proof that a different exercise implementation is correct. The course task driver performs its own API checks, while its supplemental unit tests can also be run under the harness. No collection storage implementation appears in this example.

Complete C# program:

using System;
class Program {
    static bool IsAscii(string text) {
        foreach (char unit in text) if (unit > 127) return false;
        return true;
    }
    static void Check(bool condition) { if (!condition) throw new Exception("assertion failed"); }
    static void Main() {
        Check(IsAscii("")); Check(IsAscii("v2"));
        Check(IsAscii("\u007f")); Check(!IsAscii("\u0080"));
        Console.WriteLine("checks passed");
    }
}

Complete Rust program:

fn main() {
    assert!("".is_ascii()); assert!("v2".is_ascii());
    assert!("\u{7f}".is_ascii()); assert!(!"\u{80}".is_ascii());
    println!("checks passed");
}
#[cfg(test)]
mod tests {
    #[test]
    fn ascii_boundary() { assert!("".is_ascii()); assert!("\u{7f}".is_ascii()); }
    #[test]
    fn unicode() { assert!(!"\u{80}".is_ascii()); assert!(!"é".is_ascii()); }
}
challenge icon

Challenge

Easy

Complete store::Store so the supplied unit tests and public API contract hold. Store::new(limit: usize) -> Store starts empty. put(&mut self, key: String, value: i32) -> bool inserts a missing key when below capacity, or replaces an existing value even at capacity. Rejecting a new key at capacity returns false without changing any entry. get(&self, key: &str) -> Option<i32> returns the stored value or None. len(&self) -> usize counts distinct keys. solve reads a capacity between 0 and 100, then commands put key value or get key. Keys are ASCII words, and values fit i32. Output true or false for each insertion, and the value or missing for each lookup, one per line. End with len:n. The #[test] functions are supplemental tests runnable with rustc --test main.rs; the course runner uses the locked entry point and its direct API checks. Both test observable results without depending on the storage representation.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, store.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod store;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let mut s = store::Store::new(2); assert_eq!(s.len(), 0); assert_eq!(s.get("ghost"), None);
assert!(s.put("north".to_string(), 17)); assert!(s.put("south".to_string(), -8));
assert!(s.put("north".to_string(), 23)); assert_eq!(s.len(), 2);
assert!(!s.put("west".to_string(), 90)); assert_eq!(s.get("west"), None);
assert_eq!(s.get("south"), Some(-8)); assert_eq!(s.get("north"), Some(23));
assert!(s.put("south".to_string(), 0)); assert_eq!(s.get("south"), Some(0));
assert_eq!(s.len(), 2);
let mut empty = store::Store::new(0); assert!(!empty.put("x".to_string(), 1));
assert_eq!(empty.len(), 0); assert_eq!(empty.get("x"), None);
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for C# Developers

Practice on your own: Online Rust compiler