Skip to content

Fuzz Testing ​

Fuzz testing runs your code on many strange inputs to find one that breaks it. You give valid samples, and UniTest edits them at random. New to the idea? Read the introduction in the Quick Start first.

forAll draws fresh, well-formed values from generators. Fuzzing starts from real inputs and edits them byte by byte, so a parser sees input that is almost valid: a truncated string, a length field near Int.MaxValue, a reserved byte. Every UniTest gets fuzz (bytes) and fuzzString (UTF-8 text).

A fuzz target must not fail on any input. It may throw only the exceptions that withExpectedCases accepts as rejections of invalid input; any other exception, or a failed assertion in the body, is a bug.

scala
import wvlet.uni.json.JSON
import wvlet.uni.json.JSONParseException
import wvlet.uni.test.UniTest

class JSONFuzzTest extends UniTest:
  test("JSON parser rejects invalid input cleanly") {
    fuzzString("json-parse")
      .withSeeds("""{"a":[1,true,null]}""", "\"text\"")
      .withDictionary("{", "}", "[", "]", "\"", "\\u", "true", "null")
      .withCorpusDir("src/test/resources/fuzz")
      .withExpectedCases { case _: JSONParseException => } { s =>
        JSON.parseAny(s)
      }
  }

The name identifies the target's corpus and crash directories. Chain any options after it, and end with the code to fuzz. Nothing runs without that code block, so a test that leaves it out fails. (Inside an Rx or Future callback, this is checked only for the target the callback returns.)

A run has two phases:

  1. Replay. Every seed and every file in <corpusDir>/<target>/ runs first, on every test run, so a fixed bug stays fixed.
  2. Mutate. Bit flips, boundary integers (1, 2, 4, or 8 bytes in either byte order), inserts, deletes, duplicated ranges, splices of two inputs, and dictionary tokens, stacked 1 to 4 at a time.

Now and then a mutated input is replaced with fresh random bytes, so a target without seeds still gets varied input.

On a failure, the input is reduced while it still fails with the same exception class (delta debugging, then lowering each byte to the smallest value that still fails), written to target/fuzz/<target>/crash-<hash> with a .report file, and reported with the seed. fuzzString reduces text by whole lines, then by tokens (words, whitespace runs, and single symbols), then by bytes, and never lowers bytes, so a long failing query comes down to the clauses that matter and stays readable:

text
Fuzz target json-parse failed on input 20 with java.lang.ArrayIndexOutOfBoundsException: ...
  input (1 bytes, reduced from 6): 22
  as text: """
  seed=733437378479625 (replay with UNI_FUZZ_SEED=733437378479625)
  crash_id: java.lang.ArrayIndexOutOfBoundsException@wvlet.uni.json.JSONScanner.scanString:412
  saved to target/fuzz/json-parse/crash-af639f4c860184e5
  keep it as a regression case: mkdir -p src/test/resources/fuzz/json-parse && cp target/fuzz/json-parse/crash-af639f4c860184e5 src/test/resources/fuzz/json-parse/

Run the printed command, fix the bug, and the replay phase checks it from then on. Corpus files are read where a file system is available (JVM, Scala Native, Scala.js on Node); seeds in code run everywhere.

Typed values with fuzzGen ​

fuzzGen fuzzes a target over the values of a generator, the same Gen that forAll uses. It suits writers and round trips, where the input is a value rather than bytes:

scala
import wvlet.uni.test.check.Gen
import wvlet.uni.text.csv.CSV

class CSVFuzzTest extends UniTest:
  test("written records read back the same") {
    val records = Gen.listOf(Gen.nonEmptyListOf(Gen.asciiStr).map(_.toIndexedSeq))
    fuzzGen("csv-write", records) { rs =>
      CSV.parse(CSV.writeRecords(rs)) shouldBe rs
    }
  }

The generator draws its random choices from the input bytes, so the runner still mutates and reduces bytes, and the report shows the generated value (with control and surrogate characters escaped). When the bytes run out, every draw is 0, which generators map to their first or smallest choice, so reducing the bytes shrinks the value: shorter lists, smaller numbers. Inputs for which the generator throws, such as a filter that never matches, are skipped. A saved crash file replays as long as the generator stays the same. For a type with an Arbitrary, pass Arbitrary.arbitrary[A].

Shrinking trees ​

Byte reduction cannot remove the ancestors of a failing subtree: dropping bytes shifts every later draw, so the subtree changes too. Add .withShrink(...) with a Shrink.tree, which tells how to read and replace a node's children, to shrink the reduced value further. For the Expr of Generators:

scala
import wvlet.uni.test.check.Shrink

val shrinkExpr: Shrink[Expr] = Shrink.tree[Expr](
  children = {
    case Expr.Num(_)    => Nil
    case Expr.Neg(e)    => List(e)
    case Expr.Add(args) => args
  },
  withChildren = {
    case (Expr.Neg(_), Seq(e)) => Some(Expr.Neg(e))
    case (Expr.Add(_), args)   => Some(Expr.Add(args.toList))
    case _                     => None // Num has no children; Neg needs exactly one
  },
  local = {
    case Expr.Num(v) => Shrink.shrink(v).map(Expr.Num(_))
    case _           => LazyList.empty
  }
)

def eval(e: Expr): Int =
  e match
    case Expr.Num(v)    => v
    case Expr.Neg(x)    => -eval(x)
    case Expr.Add(args) => args.map(eval).sum

class ExprFuzzTest extends UniTest:
  test("negation flips the sign") {
    fuzzGen("expr-eval", expr).withShrink(shrinkExpr) { e =>
      eval(Expr.Neg(e)) shouldBe -eval(e)
    }
  }

The shrinker tries a child in place of the node first, then the node with fewer children, then the local candidates, then each child shrunk. The report keeps value:, which the saved crash file replays, and adds shrunk value: with the exception it fails with. The crash file stays the reduced bytes, since a generated value has no byte form.

The reducers are public in wvlet.uni.test.fuzz.Reduce for use outside a fuzz target, such as reducing a failing query saved from a bug report: Reduce.text, Reduce.lines, Reduce.tokens, Reduce.bytes, and Reduce.ddmin take a predicate that is true while the input still fails, and Reduce.shrink does the same for a value with a Shrink.

forAll and fuzzGen complement each other: forAll samples a fixed number of values and shrinks with Shrink; fuzzGen keeps going for a time budget (UNI_FUZZ_SECONDS) and keeps failures as corpus files.

Feature guidance ​

Without coverage instrumentation, the runner still learns which inputs are worth mutating further: an input that shows a feature no earlier input showed joins the pool, and half of the mutations build on the latest such finds. Two kinds of features count:

  • Rejections. Each expected exception class and message, with digits removed, is a feature. A parser that fails with expected ':' on one input and unterminated string on another tells the runner the second got further, with no extra code.
  • fuzzFeature(label). A target reports a state it reached, such as a branch of a parser or a header it recognized:
scala
fuzz("archive") { bytes =>
  if bytes.startsWith("PK".getBytes) then
    fuzzFeature("zip")
  Archive.read(bytes)
}

On a keyword that must match byte by byte, guidance finds a 4-byte match within 5,000 to 100,000 inputs, depending on the seed; unguided mutation misses it in 200,000. Failure reports end with explored: N features, M inputs kept. noFeatureGuidance turns it off.

Slow inputs ​

withSlowInputMillis(ms) fails on an input that runs longer than the limit, which catches inputs that make a parser quadratic. A slow input is run again before it counts, so a JIT compilation or GC pause does not fail the test. An input that never finishes still blocks the test.

Longer runs ​

A normal test run mutates 1,000 inputs per target. Environment variables raise the budget without code changes, for a local session or a nightly job:

bash
UNI_FUZZ_SECONDS=300 ./sbt "uniJVM/testOnly *FuzzTest"   # 5 minutes per target
UNI_FUZZ_ITERATIONS=100000 ./sbt "uniJVM/testOnly *FuzzTest"
UNI_FUZZ_SEED=733437378479625 ./sbt "uniJVM/testOnly *FuzzTest"  # replay a failure
KnobMethodDefault
Mutated inputswithIterations(n)1000
Time budgetwithTimeBudgetMillis(ms)none
Input length capwithMaxLength(n)4096
Seed inputswithSeeds(...) / withSeedBytes(...)none
DictionarywithDictionary(...) / withDictionaryBytes(...)none
Corpus directorywithCorpusDir(dir)none
Crash directorywithCrashDir(dir)target/fuzz
Expected rejectionswithExpectedCases { case ... => }none
RNG seedwithSeed(s)System.nanoTime()
Ignore UNI_FUZZ_*noEnvOverridesoverrides on
Generator size (fuzzGen)withGenSize(n)32
Value shrinking (fuzzGen)withShrink(shrink) / noShrinknone
Slow-input limitwithSlowInputMillis(ms) / noSlowInputMillisnone
Feature guidancewithFeatureGuidance / noFeatureGuidanceon

Override fuzzConfig on the test class to share settings across targets. Each target starts from it and adds its own options:

scala
class ParserFuzzTest extends UniTest:
  override protected def fuzzConfig =
    super.fuzzConfig.withIterations(2000).withCorpusDir("src/test/resources/fuzz")

There is no code-coverage feedback; features stand in for it.

In the Uni repository, the Fuzz workflow runs every *FuzzTest suite (parsers, decompressors, and protocol readers) for two minutes each every night, with a fresh seed, and uploads crash files as an artifact.

Released under the Apache 2.0 License.