Skip to main content
ThunderLang™Programming Language
← All articles
ai-engineering

Test boolean parsers against exact strings, not truthiness

5 min read · 2026-11-25 · Allen Codewell

Imagine a configuration rewrite that replaces an exact-string parser with Boolean(value): the setting "false" now returns true. If its tests also derive expected values with Boolean(value), they reproduce the mistake and pass.

Python’s bool("false") has the same problem. Both languages treat that nonempty string as truthy.

A boolean return type does not guarantee correct boolean parsing.

Decide whether parsing means exact matching or normalization

Before implementing a parser, decide whether inputs such as "True" and " true " should work. Accepting them requires normalization, which changes the accepted input set.

For this change, choose exact matching and keep the requirement beside the code.

Keep this contract card beside the change

Contract item Checkable decision
Input domain Strings
Accepted inputs Exactly "true" and "false"
Outputs Actual boolean true and false, respectively
Rejection Every other string raises an error; no fallback
Counterexample "false" must return false, despite being nonempty

Rejecting an input and returning false are different behaviors.

For this contract, I would reject unexpected capitalization or whitespace rather than repair it. That exposes a mismatch at the caller. I would choose normalization only if accepting those spellings were an explicit requirement.

This contract concerns strings. It does not define behavior for numbers, null values, or other types. If the application can supply those, add a separate boundary requirement rather than silently deciding their meaning inside this change.

Share cases across languages, not language-specific assumptions

Save the following as boolean-cases.json. Both test runners below consume the same file, preventing their listed expectations from drifting apart. Sharing a fixture does not make it an independent test oracle: its expected outcomes still need review against the written contract, not the implementation.

[
  { "input": "true", "value": true },
  { "input": "false", "value": false },
  { "input": "", "reject": true },
  { "input": "True", "reject": true },
  { "input": "FALSE", "reject": true },
  { "input": " true", "reject": true },
  { "input": "false ", "reject": true },
  { "input": "true\n", "reject": true },
  { "input": "\tfalse", "reject": true },
  { "input": "0", "reject": true },
  { "input": "1", "reject": true },
  { "input": "yes", "reject": true },
  { "input": "unexpected", "reject": true }
]

The valid cases check the mapping. The capitalization and whitespace cases catch unwanted normalization. The remaining cases catch permissive conversions and fallback behavior.

Do not generate expected values by calling another parser. That can copy the same semantic mistake into the test oracle.

For each fixture edit, review whether it changes requirements or merely expands coverage. Adding another rejected string can expand coverage without changing the contract. Accepting "TRUE" changes the contract; updating the expected result to match the implementation can conceal that drift.

Keep expected behavior independent of the implementation being judged.

Check values and errors explicitly

These examples use each language’s standard library. Place all files in the same directory.

Python

Save the parser as boolean_parser.py:

def parse_boolean(value: str) -> bool:
    if value == "true":
        return True
    if value == "false":
        return False
    raise ValueError("Expected 'true' or 'false'")

Save its acceptance tests as test_boolean_parser.py:

import json
from pathlib import Path
import unittest

from boolean_parser import parse_boolean

CASES = json.loads(
    Path(__file__).with_name("boolean-cases.json").read_text(
        encoding="utf-8"
    )
)


class BooleanContractTests(unittest.TestCase):
    def test_contract(self):
        for case in CASES:
            with self.subTest(input=case["input"]):
                if case.get("reject", False):
                    with self.assertRaises(ValueError):
                        parse_boolean(case["input"])
                else:
                    self.assertIs(
                        parse_boolean(case["input"]),
                        case["value"],
                    )

Run it with:

python -m unittest test_boolean_parser

assertIs checks the actual boolean value here. An equality-only assertion would also accept integer 0 as equal to False, weakening the output contract. ValueError is this example’s Python-specific rejection mechanism, enforced by its tests; the shared contract does not prescribe an exception type.

JavaScript

Save the parser as boolean-parser.mjs:

export function parseBoolean(value) {
  if (value === "true") return true;
  if (value === "false") return false;
  throw new Error("Expected 'true' or 'false'");
}

Save its acceptance tests as boolean-parser.test.mjs:

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { parseBoolean } from "./boolean-parser.mjs";

const cases = JSON.parse(
  readFileSync(new URL("./boolean-cases.json", import.meta.url), "utf8")
);

for (const entry of cases) {
  test(`parse ${JSON.stringify(entry.input)}`, () => {
    if (entry.reject) {
      assert.throws(() => parseBoolean(entry.input), Error);
    } else {
      assert.strictEqual(parseBoolean(entry.input), entry.value);
    }
  });
}

Run it in a Node.js environment that supports the built-in test runner:

node --test boolean-parser.test.mjs

The rejection assertion accepts Error or any subclass without checking the message. The fixture shares semantic outcomes, not exception messages or identical exception types. Each implementation signals rejection using its language’s error mechanism.

Passing parser tests does not establish application-wide use

These tests establish agreement on the listed cases, not every possible string. Inspection of the two exact-match branches and the unconditional error path supports the broader rejection requirement.

A correct parser can exist while a configuration entry point still uses generic truthiness. A caller can also catch the parser’s error and silently substitute a default. Keep configuration-entry-point changes separate so they can be reviewed independently.

Before accepting the whole configuration change, use this acceptance checklist:

  • Contract: Accepted inputs and failure behavior remain unchanged.
  • Implementation: Only the two exact strings reach successful return paths.
  • Entry point: The intended configuration path invokes this parser.
  • Error handling: Rejection reaches the required boundary instead of becoming a fallback value.

Configuration-entry-point example

For example, define these outcomes for a setting that enables or disables a feature, then test them through the real configuration entry point:

Configuration input Expected application outcome
"false" The feature is disabled.
"unexpected" Startup fails with a defined configuration error.

This describes an integration test to add, not one included in the parser suites above. Define the required boundary behavior for your application rather than assuming the low-level exception must escape unchanged.

Try breaking the contract before trusting it

For a five-minute check in an isolated working copy, temporarily replace the parser body with return bool(value) in Python or return Boolean(value) in JavaScript. Run the acceptance suite and confirm that "false" and rejection cases fail, then restore the implementation.

This mutation check tests whether the suite detects the specific truthiness mistake, not every possible parsing defect.