How HarfBuzz Works From Unicode to positioned glyphs, and everything in between
HarfBuzz 15.2.0
Contents

Part XI · Using HarfBuzz

47. Testing and debugging fonts with HarfBuzz

A font maker turns to a shaping engine with two kinds of question. The first comes while a font is being made: a rule has been written, and the text doesn’t come out as it should. The second comes once the font works: will it still work after the next change? This chapter answers both with HarfBuzz’s own tools: the first by narrowing a problem down to the step that causes it, the second with tests that every build of the font must pass, run by continuous integration (CI), which builds a project on a server each time a change is pushed.

HarfBuzz is the natural engine for both. Chrome, Firefox, Android, and most other software shape text with it, so for most of a font’s users, what HarfBuzz does with the font is what the font does. hb-shape gives the same answer those programs get for the same text and settings, and it can show each step it took to get there. And HarfBuzz’s own test suite has a format for expected results, and a runner for them, that work as well for a font maker’s tests as for HarfBuzz’s.

The chapter is for font makers and font engineers. Its examples use small test fonts built from feature files with the program in Testing with a font of your own, so their glyphs are boxes. How HarfBuzz tests itself is in Testing HarfBuzz.

This chapter uses hb-shape, hb-info, hb-subset, and the drawing tools without explaining their switches. The command-line tools is the place to get familiar with them: it describes each switch, with recipes for single questions about a font.

When a font doesn’t work

The font in this section has two rules that don’t do what its maker meant. Its feature file:

languagesystem DFLT dflt;
languagesystem latn dflt;

feature liga {
  script DFLT;
  sub f i by f_i;
} liga;

feature dlig {
  sub T h by T_h;
} dlig;

Its maker reports that neither ligature ever forms. The steps below work for any such problem: reproduce it, find the step that goes wrong, decide whose problem it is, cut it down, and keep it as a test.

Reproduce it with hb-shape

Start by getting hb-shape to give the wrong result. Use the text that goes wrong, and give it everything the application gives its shaper: the language (from the document, such as an HTML lang attribute, or from the user’s settings), the script and direction if the application sets them, and the features it turns on or off, such as CSS font-feature-settings (Direction, script, and language, Features). Leave one out and hb-shape may be answering a different question: a locl lookup that runs only for one language, or a feature the application turns off.

FontTextOptionshb-shape output
broken.ttffitU+0066 U+0069 U+0074--language=en[f=0+500|i=1+500|t=2+500]
broken.ttfThU+0054 U+0068--language=en[T=0+500|h=1+500]

Both go wrong here, as reported. If hb-shape gets the right answer, the question moves to the application: what it passes to HarfBuzz, whether it has the build of the font it should (an installed copy, a cached web font), and whether it shapes with HarfBuzz at all.

Find the step

hb-info says what the font offers for the text’s script and language (Which features apply in this language?):

FontOptionshb-info output
broken.ttf--list-scripts
Layout script information:

Table: GSUB
	Script: Zyyy (DFLT)
	Script: Latn (latn)
Table: GPOS
broken.ttf--list-features --script=Latn
Layout features information:

Table: GSUB
	Script: latn
	Language: Default
	Feature: dlig
Table: GPOS

The font has two scripts, DFLT and latn, and under latn it has only dlig. Latin text gets the features of the font’s latn script, and falls back to DFLT only if the font has no latn (Choosing a script shaper), so the liga rule, written under DFLT alone, never runs. A trace shows the same from the other side: GSUB starts, under the script tag latn, and ends without running a lookup:

hb-shape broken.ttf "fit" --language=en --trace
start table GSUB script tag 'latn'[f=0|i=1|t=2]
end table GSUB script tag 'latn'[f=0|i=1|t=2]

Shaped as text whose script DFLT serves, the rule works, so the rule itself is right:

FontTextOptionshb-shape output
broken.ttffitU+0066 U+0069 U+0074--language=en --script=Zyyy[f_i=0+900|t=2+500]

The fix is in the feature file: write the rule before any script statement, which registers it under every language system, as most feature files do (Reading feature files).

The Th ligature is a different case. dlig is registered under latn, but it is a discretionary feature, off unless asked for. HarfBuzz turns on a fixed set of features by default, and dlig isn’t one of them (Which features are asked for). Asked for, it works:

FontTextOptionshb-shape output
broken.ttfThU+0054 U+0068--language=en --features=dlig[T_h=0+900]

So nothing is broken: the user has to turn the feature on (in CSS, font-variant-ligatures: discretionary-ligatures). If the ligature was meant to form always, it belongs in liga or calt, not dlig.

When the features are all there, the trace shows which lookup did the wrong thing, or which one never ran, and the recipe Why didn’t this ligature form? works through one. Turning features off one at a time, with --features=-calt and so on, finds which feature is responsible when there are many.

Decide whose problem it is

In this font, hb-info and the trace were enough: one rule was registered in the wrong place, and the other is in a feature that is off by default. Most problems are in the font, but not all: when the font’s tables look right and the result is still wrong, try other engines: the same text in another HarfBuzz release, in the platform shapers where HarfBuzz is built with them, and in HarfRust (Other shapers and other versions). If every engine gives the same wrong result, the font is almost certainly the cause, however right the rule looks: read it again beside the trace. If HarfBuzz alone differs, look in this book’s chapter for the script, since many differences are deliberate, and in HarfBuzz’s issues, since many are known. If it is still unexplained, it may be a HarfBuzz bug, worth reporting on HarfBuzz’s issue tracker. The next step makes the small font that such a report needs.

Cut it down

A problem is easiest to understand, and to report, in a small font. hb-subset keeps what a text needs and drops the rest (hb-subset):

$ hb-subset broken.ttf --text="fit" --glyph-names -o fit.ttf

--glyph-names keeps the glyph names, which a subset otherwise drops, so that the results still read f_i, not a glyph number. Check that the subset still goes wrong. Then, if there is a feature file, cut the layout down further: take out features, then lookups, then rules, checking each time, until only what goes wrong is left. If the outlines don’t matter, rebuild what is left with box glyphs. HarfBuzz’s own tests are made the same way, from a font subset to the text of the test (The format of a test), and a bug report with a font of a few glyphs, the hb-shape command, and the output expected is one its developers can turn straight into a test.

Keep the case

Once the problem is fixed, keep the text that went wrong, with its options and the result it should give, as a test. Then the problem can’t come back unnoticed. The rest of the chapter is about such tests.

Keeping a font working

Fonts are revised after they ship, and their layout tables with them. A new alternate is added, a class gains a glyph, a feature file is reordered, a glyph is renamed, a compiler is updated. Each change can alter how some text comes out, and nothing in the font says which. The way to find out is to keep a record of what the font did, and compare every new build with it.

Today that comparison is best made by CI: one more step in the font’s build shapes the test texts with the new build and fails if the output doesn’t match the record. Nobody has to remember to run it, and a mistake is caught in the change that made it. The sections below build that up: recording the font’s output, choosing what to test, running the tests and reading a failure, and then running them in CI.

The examples from here on use two releases of one test font. Release 1 has an fi ligature and kerns T with o:

feature liga {
  sub f i by f_i;
} liga;

feature kern {
  pos T o -80;
} kern;

Release 2 adds a contextual alternate, a different o after T, and nothing else:

feature calt {
  sub T o' by o.alt;
} calt;

It’s a common kind of change, and it has a common kind of mistake in it: the kerning wasn’t updated for the new glyph. Nothing warns about it. The font compiles, and each feature does what its rules say.

Recording what the font does

A test is a text, the options to shape it with, and the result. The result isn’t written by hand: it is what HarfBuzz gives now, recorded once and checked by eye, and from then on it is what every later build must give. Here is what release 1 gives for four texts:

FontTextOptionshb-shape output
release-1.ttfToU+0054 U+006F--language=en[T=0+420|o=1+500]
release-1.ttffitU+0066 U+0069 U+0074--language=en[f_i=0+900|t=2+500]
release-1.ttffiU+0066 U+0069--language=en --features=-liga[f=0+500|i=1+500]
release-1.ttfTo␣fitU+0054 U+006F U+0020 U+0066 U+0069 U+0074--language=en[T=0+420|o=1+500|space=2+500|f_i=3+900|t=5+500]

Each is right: T and o are kerned by −80, and fi is one glyph, except where liga is turned off.

HarfBuzz keeps its own expected results in .tests files, one test to a line: the font, the hb-shape options, the text as code points, and the expected output, separated by semicolons (The format of a test). Nothing in the format is particular to HarfBuzz’s fonts, so a font maker’s tests can use it too, and HarfBuzz’s runner will run them. This program records a .tests file from a list of cases, by running hb-shape on each:

examples/font-tests/record-tests.py
"""Record what HarfBuzz does with a font now, as lines of a .tests file.

usage: python3 record-tests.py HB-SHAPE FONT CASES > FONT.tests

CASES has one case per line: the text, then, after a tab, any hb-shape
options for it (--language=en, --features=-liga ...). Each output line is
one test in the format of HarfBuzz's own test/shape suite: the font, the
options, the text as code points, and the result hb-shape gives today.
Keep the .tests file beside the font: the font is named without a folder.

Needs only Python 3 and hb-shape.
"""
import os
import subprocess
import sys


def main(hb_shape, font, cases):
    env = dict(os.environ, LC_ALL="C")  # as run-tests.py runs it
    with open(cases, encoding="utf-8") as f:
        for line in f:
            line = line.rstrip("\n")
            if not line or line.startswith("#"):
                continue
            text, _, options = line.partition("\t")
            unicodes = ",".join(f"U+{ord(c):04X}" for c in text)
            result = subprocess.run(
                [hb_shape, font, "--unicodes", unicodes, *options.split()],
                capture_output=True, text=True, env=env, check=True,
            ).stdout.strip()
            print(f"{os.path.basename(font)};{options};{unicodes};{result}")


if __name__ == "__main__":
    if len(sys.argv) != 4:
        sys.exit(__doc__)
    main(*sys.argv[1:])

Its cases file has one case to a line, the text and, after a tab, the options:

To	--language=en
fit	--language=en
fi	--language=en --features=-liga
To fit	--language=en

Run on release 1, saved as myfont.ttf, the program writes:

myfont.ttf;--language=en;U+0054,U+006F;[T=0+420|o=1+500]
myfont.ttf;--language=en;U+0066,U+0069,U+0074;[f_i=0+900|t=2+500]
myfont.ttf;--language=en --features=-liga;U+0066,U+0069;[f=0+500|i=1+500]
myfont.ttf;--language=en;U+0054,U+006F,U+0020,U+0066,U+0069,U+0074;[T=0+420|o=1+500|space=2+500|f_i=3+900|t=5+500]

The results are the ones above. The font is named without a folder, because the runner finds it beside the .tests file, so each build of the font is saved under the same name in the same place. Pass --language in every case: hb-shape otherwise takes the language from the locale, and the recording and the rerun could disagree.

Glyph names make the results readable, and a font built without them (a post table of version 3, as many shipping fonts have) is recorded with glyph IDs instead, as gid followed by the number. Either works, but a test with names is easier to check by eye and survives a change in glyph order. Record from a build with names if the build process can make one.

What to test

The tests only see what they shape. Some places to look, in roughly the order they catch problems:

The last needs an example. This font, from Shape plans and their cache, substitutes H for I from weight 600 to 695, and V from 700:

FontTextOptionshb-shape output
shape-plans-and-their-cache/featvar.ttfIU+0049--variations=wght=400 --language=en --ned[I]
shape-plans-and-their-cache/featvar.ttfIU+0049--variations=wght=600 --language=en --ned[H]
shape-plans-and-their-cache/featvar.ttfIU+0049--variations=wght=695 --language=en --ned[H]
shape-plans-and-their-cache/featvar.ttfIU+0049--variations=wght=696 --language=en --ned[I]
shape-plans-and-their-cache/featvar.ttfIU+0049--variations=wght=700 --language=en --ned[V]
shape-plans-and-their-cache/featvar.ttfIU+0049--variations=wght=900 --language=en --ned[V]

Tests at 400 and 900 never see the H, nor the gap at 696, where the I comes back: the conditions say 0.59, and a user value of 696 normalizes to just above it. A feature file says where the switches are; the cases should sit on each side of each of them (Design space explains the normalization).

Running the tests

HarfBuzz’s runner is test/shape/run-tests.py, in its source tree. It is one Python file with no dependencies beyond Python itself, so it can be copied out and used with any hb-shape (Building HarfBuzz shows how to get one). It takes the path of hb-shape, then one or more .tests files:

$ python3 run-tests.py /path/to/hb-shape myfont.tests

Two things it does are worth having in a font’s tests. It runs every test with --verify --unsafe-to-concat --safe-to-insert-tatweel (run-tests.py:284), so a test also checks that the font gives the same result when the text is cut where a line could break; more on that below. And it runs every test once for each kind of font functions the hb-shape was built with (:143–:150), so that a build with FreeType checks HarfBuzz’s metrics against FreeType’s too. An @shapers= or @font-funcs= line in the file narrows that (How a test is run).

Run on release 1, every test passes. Here is what it printed for release 2, saved as myfont.ttf in its place, run by hand with the book’s hb-shape (its path shortened to hb-shape, the first three lines left out, and the options the runner adds shown as …):

# Supported font-funcs: ['ot']
# Running tests in myfont.tests
not ok 1 - hb-shape myfont.ttf --unicodes U+0054,U+006F --language=en …
ok 2 - hb-shape myfont.ttf --unicodes U+0066,U+0069,U+0074 --language=en …
ok 3 - hb-shape myfont.ttf --unicodes U+0066,U+0069 --language=en --features=-liga …
not ok 4 - hb-shape myfont.ttf --unicodes U+0054,U+006F,U+0020,U+0066,U+0069,U+0074 --language=en …
# 2 tests passed; 2 failed; 0 skipped.
1..4

and, on standard error, for each failure:

   ---
   test_file: "myfont.tests"
   cmd: "hb-shape myfont.ttf --unicodes U+0054,U+006F --language=en …"
   actual:   "[T=0+500|o.alt=1+500]"
   expected: "[T=0+420|o=1+500]"
   ...

The output is TAP, the format Meson’s test runner reads. One thing to know before calling it from a build script: it exits with 0 whether or not tests fail. Nothing after the count is checked (run-tests.py:357, the last line), because Meson reads the ok and not ok lines itself. A script should look for not ok, or for the summary line, rather than the exit status.

Reading a failure

The runner says what changed. Shaped by both releases, the text that failed shows it plainly:

FontTextOptionshb-shape output
release-1.ttfToU+0054 U+006F--language=en[T=0+420|o=1+500]
release-2.ttfToU+0054 U+006F--language=en[T=0+500|o.alt=1+500]

In release 2 the o is o.alt, as intended, and the T has lost its kerning: its advance is 500, not 420. Drawn, with every glyph a box, the two releases look like this:

To␣fit, rendered by hb-raster
hb-raster release-1.ttf To␣fit --font-size=48 (140 × 53 pixels, shown 2 times larger)
To␣fit, rendered by hb-raster
hb-raster release-2.ttf To␣fit --font-size=48 (144 × 53 pixels, shown 2 times larger)

A trace finds the cause. It needs an hb-shape built with detailed messages (Building HarfBuzz), and Traces explains what it prints. For release 2:

hb-shape release-2.ttf "To" --language=en --trace
start lookup 1 feature 'calt'[T=0|o=1]
start recursing to lookup 2 at 1[T=0|o=1]
replacing glyph at 1 (single substitution)[T=0|o=1]
replaced glyph at 1 (single substitution)[T=0|o.alt=1]
end recursing to lookup 2[T=0|o.alt=1]
end lookup 1 feature 'calt'[T=0|o.alt=1]
end table GSUB script tag 'latn'[T=0|o.alt=1]
start table GPOS script tag 'latn'[T=0+500|o.alt=1+500]
start lookup 0 feature 'kern'[T=0+500|o.alt=1+500]
end lookup 0 feature 'kern'[T=0+500|o.alt=1+500]

calt replaces the o with o.alt, and then kern runs and changes nothing, because its pair is T o, and there is no longer an o. Substitution always comes before positioning, so GPOS only ever sees what GSUB has left. The recipe Why didn’t this ligature form? works through the same reading for a substitution.

Then comes the decision only the font maker can make: is the change a mistake, or the new intended behavior? Here it is a mistake, and the fix is in the font, pos T [o o.alt] -80;. Had the change been intended, the tests would be recorded again instead, as Running the tests in CI shows.

Results that change at a line break

Line breaking means shaping a text in pieces. An application shapes a paragraph once, picks the breaks, and reuses the glyphs on each side when the glyph flags say it can (For applications). If a font’s result for a piece differs from the same glyphs in the whole, a line ends or begins with the wrong glyphs, and only where it happens to break.

--verify checks that, for one text at a time: it shapes the pieces between every break the flags allow, and compares them with the whole (Verifying). The runner turns it on for every test, so a font’s tests check it for free. When verification fails, hb-shape prints the reason on standard error, and error: Shaping failed. in place of the result, so the test fails with that as its actual output. For applications shows texts that fail.

A failure there isn’t always the font’s fault. The flags are set by HarfBuzz, from what the lookups did, and some of the failures in that chapter are HarfBuzz setting them wrongly. But it is always a break where the font’s text comes out differently in an application, so it is worth knowing about, and worth reporting to HarfBuzz if the font is doing nothing unusual. To test a text that should only be checked whole, record it with * as its expected result: the runner then counts it as passed without comparing anything, and runs it without --verify (run-tests.py:298).

Running the tests in CI

The .tests file is kept in the repository with the font’s sources, so CI can check every change against it before the font is released.

The usual way to run shaping tests in CI is fontspector, the successor to fontbakery, with tests in a JSON format of their own (Font QA tools). Large projects work this way. Each of the Noto fonts’ repositories has a GitHub Actions workflow that, for every branch, builds the font, runs the QA checks, including any shaping tests in its qa/shaping_tests folder, and compares the build with the font’s previous release using gftools.diffenator, which renders test strings from both and shows the differences (notofonts.github.io, its README). Fontspector shapes with HarfRust, not HarfBuzz. To test against HarfBuzz itself, run the same kind of tests with hb-shape and HarfBuzz’s own runner, as the rest of this section does. A font can use both.

The step is the same as on a desktop: build the font, then run the tests and fail if any test failed:

$ python3 run-tests.py "$(command -v hb-shape)" myfont.tests > results.tap
$ ! grep -q '^not ok' results.tap

The second command fails when the file has a not ok line, and so fails the build. On GitHub Actions, for example, a workflow could do it like this. It is an example, hand-written and not run by this book, and it assumes the font is built by a build.sh and its tests are in tests/:

name: Shaping tests
on: [push, pull_request]
jobs:
  shaping:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install meson ninja fonttools==4.38.0
      - name: Build HarfBuzz 15.2.0
        run: |
          git clone --depth 1 --branch 15.2.0 https://github.com/harfbuzz/harfbuzz.git hb
          meson setup hb/build hb -Dtests=disabled -Ddocs=disabled
          ninja -C hb/build util/hb-shape
      - run: sh build.sh
      - name: Run the tests
        run: |
          python3 hb/test/shape/run-tests.py "$PWD/hb/build/util/hb-shape" tests/myfont.tests > results.tap
          cat results.tap
          ! grep -q '^not ok' results.tap

The runner’s source comes with the HarfBuzz it builds, so the two always match. The failures’ details, the actual and expected results, go to standard error, which the CI log shows.

Not every failure is a mistake. When a change is meant to alter the output, the tests are recorded again in the same change, and the difference in the .tests file says exactly what the change did. Had release 2’s alternate been intended, recording again would have given:

-myfont.ttf;--language=en;U+0054,U+006F;[T=0+420|o=1+500]
+myfont.ttf;--language=en;U+0054,U+006F;[T=0+500|o.alt=1+500]
 myfont.ttf;--language=en;U+0066,U+0069,U+0074;[f_i=0+900|t=2+500]
 myfont.ttf;--language=en --features=-liga;U+0066,U+0069;[f=0+500|i=1+500]
-myfont.ttf;--language=en;U+0054,U+006F,U+0020,U+0066,U+0069,U+0074;[T=0+420|o=1+500|space=2+500|f_i=3+900|t=5+500]
+myfont.ttf;--language=en;U+0054,U+006F,U+0020,U+0066,U+0069,U+0074;[T=0+500|o.alt=1+500|space=2+500|f_i=3+900|t=5+500]

That is what a reviewer reads in the pull request: each changed result beside the old one. Here it shows the alternate, and also that T lost its kerning, which nobody intended. A change that alters results without changing the .tests file fails; one that changes the file has said, in its diff, what it changed. So the new results are read before they are committed: a suite whose expected results are regenerated without being read checks nothing.

Three things keep the comparison honest:

Other shapers and other versions

A font’s users don’t all have the same HarfBuzz, and some don’t have HarfBuzz at all. The same tests can be run more widely.

The book’s build has only the ot and fallback shapers, so none of these runs here.

Proofs

A test says which glyphs come out and where. It doesn’t say whether they look right: a wrong but consistent result passes forever once it is recorded. So the first recording of a case is checked by eye, and a proof is the easiest way to do that. hb-view, hb-raster, and hb-vector draw text as HarfBuzz shapes it, with the same options as hb-shape (Drawing), so a proof of the cases file shows exactly what the tests recorded. Release 2’s To above is easy to miss in a list of numbers and hard to miss in a picture.

Font QA tools

Fontspector, the Rust successor to fontbakery, runs a font maker’s shaping tests as checks in its Google Fonts profile: shaping/regression compares the results with expected ones, and shaping/forbidden fails if a forbidden glyph, such as .notdef or a visible virama, appears (profile-googlefonts/src/checks/shaping/ in fontspector). Fontbakery has checks of the same names. The tests are JSON files, in the format Simon Cozens describes in Better Fonts Through Test-Driven Development. Here is one of Noto Looped Thai’s (qa/shaping_tests/looped.json in notofonts/thai), trimmed:

{
  "expectation": "uni0E23=0+510|uni0E37=0@-625,0+0|uni0E48.small=0@-215,-1+0|uni0E2D=3+584|…",
  "input": "รื่องนั้",
  "note": "Issue #21",
  "only": "NotoLoopedThai-Regular.ttf"
}

The expectation is HarfBuzz’s output format, as hb-shape prints it, without the brackets: so a .tests line and a JSON test record the same thing, and either can be made from the other. The note ties the test to the issue it came from, which is Keep the case in practice.

Fontspector shapes with HarfRust (its Cargo.toml), and fontbakery with uharfbuzz, HarfBuzz’s Python binding, by way of vharfbuzz. HarfRust follows HarfBuzz closely, but not exactly (HarfRust), so a result that matters is worth checking with HarfBuzz too.

Their other checks are outside this book: outlines, metadata, spacing, naming, and the rest of what makes a font fit to ship.

Where to read the source

File What’s there
test/shape/run-tests.py the runner: the backends it tries, the options it adds, its TAP output
test/shape/README.md, test/shape/record-test.sh how HarfBuzz records its own tests, with a subset of the font
util/batch.hh --batch, which the runner drives
src/hb-buffer-verify.cc what --verify checks, and the messages it prints
examples/font-tests/record-tests.py (this book) recording a .tests file from a list of cases

In short