Testing Public Contracts
Lesson 41 of 48 in Coddy's Rust for C++ Developers course.
C++ assert checks can disappear when NDEBUG is defined. Rust ordinary assertions remain active; debug_assert! is the separate conditional facility. Rust functions marked #[test] run through the test harness only when compiled with --test. A module gated by #[cfg(test)] is excluded from an ordinary executable build. Therefore a successful run of main alone does not prove those harness tests executed. The example deliberately calls its contract checks from main as well, and the evidence also runs the actual test harness. Tests can assert relationships such as symmetry as well as one expected value. API-level checks should observe public behavior instead of requiring one private data structure. The exercise applies this approach to a capacity-limited key store, not to distances.
Complete standalone C++17 program:
#include <cassert>
#include <iostream>
int distance(int a, int b) { return a > b ? a - b : b - a; }
int main() {
assert(distance(2, 8) == 6);
assert(distance(2, 8) == distance(8, 2));
assert(distance(5, 5) == 0);
std::cout << distance(2, 8) << '\n';
}Complete standalone Rust program:
fn distance(a: i32, b: i32) -> i32 { if a > b { a - b } else { b - a } }
fn check_contract() {
assert_eq!(distance(4, 9), 5);
assert_eq!(distance(9, 4), distance(4, 9));
assert_eq!(distance(7, 7), 0);
}
#[cfg(test)]
mod tests {
#[test]
fn symmetric_and_zero() { super::check_contract(); }
}
fn main() { check_contract(); println!("{}", distance(4, 9)); }Challenge
EasyComplete 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C++ Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate8Traits and Generic Code
Traits and ContractsGenerics and BoundsTrait ObjectsFunction PointersDerived Value SemanticsTesting Public ContractsScoring Contracts Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler