testing

Assertions for hphp test with readable failure messages.

v1.0.0Tooling & CLIbundledimport "testing";
Overview Installation Documentation Examples

Overview

Small, readable assertions for hphp test. Each check prints one line, a failure shows what was expected and what came back, and done() exits with 1 when anything failed, so the test runner sees it.

bundled — works offline equal, same, contains, near throws / noThrow used by hphp create templates

Quick start

// tests/greeting_test.hphp
import "testing";
import "../src/greeting.hphp";

$t = new Test("greeting");
$t->equal(greeting("Ada"), "Hello, Ada!", "greets by name");
$t->equal(greeting(""), "Hello, world!", "empty means world");
$t->done();
$ hphp test
PASS greeting_test.hphp
1 passed, 0 failed

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install testing

This adds the library to hphp.yaml, installs it into .hphp/packages/testing/ and pins the exact version in hphp.lock:

require:
  testing: "^1.0"

Use it

import "testing";

testing is bundled with the compiler, so import "testing"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install testing          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install testing
Packagetesting
Version1.0.0 (follows the compiler)
Entry filetesting.hphp
Sourcepackages/lib/testing ↗

Documentation

Assertions

Every assertion takes a description as its last argument and returns true when it passed, so you can branch on it.

MethodPasses when
equal($actual, $expected, $what)$actual == $expected (arrays compare their pairs)
same($actual, $expected, $what)$actual === $expected: same type and value
notEqual($actual, $other, $what)$actual != $other
isTrue($cond, $what) / isFalse(...)the condition is true / false
contains($haystack, $needle, $what)the string contains the needle
near($actual, $expected, $epsilon, $what)floats differ by at most $epsilon
count($array, $n, $what)the array has $n items
throws($fn, $what)calling $fn throws
noThrow($fn, $what)calling $fn does not throw
fail($what)never (mark a branch that must not run)

Running

MethodWhat it does
new Test($name)a group of checks; the name prefixes the summary
section($title)prints a heading for the following checks
done()prints “N passed, M failed” and exits with 1 when M > 0
$passed, $failedthe counters, if you want your own summary

A failing check does not stop the test: every check runs, and the output shows all failures at once. hphp test -v prints the output of every test file; hphp test greeting runs only files whose name contains “greeting”.

Failure messages

  FAIL string mismatch
       expected "b", got "a"
  FAIL type mismatch
       expected "1" (string), got 1 (integer)
  FAIL missing needle
       "abc" does not contain "z"

Examples

3 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.

01Your first test file

A test is a normal program: make a Test, check results with equal(), and finish with done(), which exits with 1 when a check failed. In a project this file lives in tests/ and hphp test runs it.

01-first-test.hphp
<?php
import "testing";

// the code under test (normally imported from src/)
function initials(string $name): string {
    $out = "";
    foreach (explode(" ", trim($name)) as $part) {
        if ($part != "") {
            $out = $out . strtoupper(substr($part, 0, 1));
        }
    }
    return $out;
}

$t = new Test("initials");

$t->equal(initials("Ada Lovelace"), "AL", "two names");
$t->equal(initials("grace brewster hopper"), "GBH", "lowercase input");
$t->equal(initials("  Linus   Torvalds "), "LT", "extra spaces");
$t->equal(initials(""), "", "empty name");

$t->done();
Try it
hphp run 01-first-test.hphp

02Testing a class: state, errors and sections

Tests a small bank account. section() groups the checks in the output, throws() checks that invalid operations are rejected, and same() also compares the type.

02-testing-a-class.hphp
<?php
import "testing";

class Account {
    pub int $balance = 0;

    pub function deposit(int $amount): void {
        if ($amount <= 0) {
            throw "deposit must be positive";
        }
        $this->balance = $this->balance + $amount;
    }

    pub function withdraw(int $amount): void {
        if ($amount > $this->balance) {
            throw "insufficient funds";
        }
        $this->balance = $this->balance - $amount;
    }
}

$t = new Test("account");

$t->section("a new account");
$fresh = new Account();
$t->same($fresh->balance, 0, "starts empty");

$t->section("deposits and withdrawals");
$acc = new Account();
$acc->deposit(100);
$acc->withdraw(30);
$t->same($acc->balance, 70, "100 in, 30 out");

$t->section("invalid operations");
$t->throws(function() use ($acc) { $acc->withdraw(1000); }, "cannot overdraw");
$t->throws(function() use ($acc) { $acc->deposit(-5); }, "cannot deposit a negative amount");
$t->same($acc->balance, 70, "a rejected operation changes nothing");

$t->done();
Try it
hphp run 02-testing-a-class.hphp

03Table-driven tests

When many inputs share one rule, list them as rows and loop. Each row is its own check with its own name, so a failure points at the exact case. near() compares floats with a tolerance.

03-table-driven.hphp
<?php
import "testing";

// the code under test
function celsius_to_fahrenheit(float $c): float {
    return $c * 9 / 5 + 32;
}

function is_leap_year(int $year): bool {
    return ($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0;
}

$t = new Test("tables");

$t->section("temperature");
$temperatures = [
    [0.0, 32.0],
    [100.0, 212.0],
    [-40.0, -40.0],
    [36.6, 97.88],
];
foreach ($temperatures as $row) {
    $t->near(celsius_to_fahrenheit($row[0]), $row[1], 0.001, $row[0] . " C");
}

$t->section("leap years");
$years = [[2000, true], [1900, false], [2024, true], [2023, false]];
foreach ($years as $row) {
    $t->equal(is_leap_year($row[0]), $row[1], strval($row[0]));
}

$t->done();
Try it
hphp run 03-table-driven.hphp