FAQ - Help and questions

How do I write golden-file tests before porting a function to Rust?

#porting#testing#pythonpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Run the old function over a list of inputs, including awkward ones, and save each input with its output in a plain text file. Then write the Rust version and a test that reads the file and compares. Differences point to behaviour you must either copy or deliberately change.

Checked with rustc 1.93.0, Python 3.13.7, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A golden file records what the old program does, as data, before anyone changes it. It is a characterization test: it does not say the old behaviour is right, only what it is. The port is then measured against it.

The example ports a Python function that turns a title into a URL slug. First, a script runs the Python function over twelve inputs and writes input<TAB>output lines.

golden_gen.pypython
import sys

def slug(title):
    out, prev_dash = [], True
    for ch in title.lower():
        if ch.isalnum():
            out.append(ch)
            prev_dash = False
        elif not prev_dash:
            out.append("-")
            prev_dash = True
    return "".join(out).rstrip("-")

cases = ["Hello, World!", "  spaced   out  ", "a--b", "", "Rust 1.93 released", "Straße nach Köln",
         "İstanbul", "x² + y²", "日本語 text", "ΑΣ", "café — menu", "100%"]
with open(sys.argv[1], "w", encoding="utf-8", newline="\n") as f:
    for c in cases:
        f.write(f"{c}\t{slug(c)}\n")

The list includes the cases a quick test would skip: empty text, repeated separators, accented letters, non-Latin scripts and a superscript digit. A first Rust port, written the way the English examples suggest, only keeps ASCII letters and digits. A second port keeps every character that Rust's char::is_alphanumeric accepts. A small program runs both against the file:

src/main.rsrust
use std::fs;

// A first, ASCII-only port: looks right for English titles.
pub fn slug_naive(title: &str) -> String {
    let mut out = String::new();
    let mut prev_dash = true;
    for ch in title.to_lowercase().chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch);
            prev_dash = false;
        } else if !prev_dash {
            out.push('-');
            prev_dash = true;
        }
    }
    out.trim_end_matches('-').to_string()
}

// The port that matches what the Python function does for any letter or digit.
pub fn slug(title: &str) -> String {
    let mut out = String::new();
    let mut prev_dash = true;
    for ch in title.to_lowercase().chars() {
        if ch.is_alphanumeric() {
            out.push(ch);
            prev_dash = false;
        } else if !prev_dash {
            out.push('-');
            prev_dash = true;
        }
    }
    out.trim_end_matches('-').to_string()
}

fn load(path: &str) -> Vec<(String, String)> {
    let text = fs::read_to_string(path).expect("golden file");
    text.lines().map(|l| {
        let (a, b) = l.split_once('\t').unwrap_or((l, ""));
        (a.to_string(), b.to_string())
    }).collect()
}

fn main() {
    let path = std::env::args().nth(1).expect("path to the golden file");
    let cases = load(&path);
    for (name, f) in [("slug_naive", slug_naive as fn(&str) -> String), ("slug", slug)] {
        let bad: Vec<_> = cases.iter().filter(|(i, o)| f(i) != *o).collect();
        println!("{name}: {} of {} cases differ from the Python output", bad.len(), cases.len());
        for (i, o) in bad {
            println!("  input {i:?}: python {o:?}, rust {:?}", f(i));
        }
    }
}
text
slug_naive: 5 of 12 cases differ from the Python output
  input "Straße nach Köln": python "straße-nach-köln", rust "stra-e-nach-k-ln"
  input "x² + y²": python "x²-y²", rust "x-y"
  input "日本語 text": python "日本語-text", rust "text"
  input "ΑΣ": python "ας", rust ""
  input "café — menu": python "café-menu", rust "caf-menu"
slug: 0 of 12 cases differ from the Python output

The naive port passes the English-looking cases and fails five others. The second port matches all twelve. Two cases deserve a remark: "İstanbul" gives i-stanbul in both languages, because lower-casing the Turkish capital dotted I produces an i followed by a combining dot that is not a letter, and "ΑΣ" gives a final-form sigma ς in both.

The same comparison as a real test, so that it runs with cargo test and fails the build on a difference (the path of the golden file is passed in an environment variable):

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

    #[test]
    fn matches_the_python_golden_file() {
        let path = std::env::var("GOLDEN").expect("set GOLDEN to the golden file");
        for (input, expected) in load(&path) {
            assert_eq!(slug(&input), expected, "input {input:?}");
        }
    }
}
text
running 1 test
test tests::matches_the_python_golden_file ... ok

How to do it#

  1. Write the list of inputs from three sources: the cases the function's callers really send, the boundaries (empty, one item, maximum size), and the strange cases of the data type (non-ASCII text, negative numbers, very large numbers, NaN).
  2. Generate the outputs with the old code, once, and commit the file. A tab- or line-separated text file is easy to read in any language; JSON lines work when values contain tabs or newlines.
  3. Write the Rust port and the test that reads the file.
  4. For each difference decide: is it a mistake in the port, or a bug in the old code you want to leave behind? In the second case, change the golden file on purpose and say why in the commit.

Common mistakes#

  • Making the golden file with the new code. It then proves nothing.
  • Leaving out the unusual inputs because "nobody sends those". Ported code diverges exactly there.
  • Comparing text that contains time stamps, random identifiers or map ordering. Remove or fix what changes between runs, or the test is flaky.

Does this work when the old code is not a pure function?#

Record its inputs and outputs at the boundary (arguments and return values, or request and response). A function that reads a database needs the database state fixed for the recording.

What about performance?#

A golden file checks behaviour only. See the thread with a measured example for timing.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet