Testing
How mathconv is tested: test cases, the conversion checks, corpus evaluation, fuzzing and the checks of the documentation and bindings.
mathconv is tested in four ways, the first three of which run the same conversion checks:
- test cases: small inputs with the exact output expected for them;
- corpus evaluation: converting a corpus, a large collection of real formulas, and measuring the results;
- fuzzing: generated inputs that search for crashes and failing checks;
- the benchmark: a fixed set of formulas whose conversion speed is measured and guarded, as Benchmarks describes.
Test cases#
A test case is a file holding one input, its expected output and the origin of the input. Every behaviour of mathconv is pinned by at least one test case, so changing a behaviour means changing or adding test cases.
Cases live in tests/cases/, in one directory per area, named after
the area's tag with : written as -. Each case is named after the behaviour it shows, in
lowercase words joined by hyphens:
tests/cases/fraction/zero-line-in-parentheses.toml
tests/cases/output-text/fraction-next-to-identifier.toml
If the name you want is taken, the existing case may already show your behaviour; otherwise choose a more specific name.
The case format#
A case is a TOML file. The shortest case has four fields:
input = '<math><mfrac linethickness="0"><mi>n</mi><mi>k</mi></mfrac></math>'
expected = '\genfrac{}{}{0pt}{}{n}{k}'
tags = ["fraction"]
origin = "hand-written"
Single-quoted TOML strings keep backslashes as they are; triple single
quotes (''') hold input that spans several lines.
| Field | Required | Meaning |
|---|---|---|
input | yes | the input string, exactly as the converter receives it |
expected | yes | the exact expected output |
tags | yes | one or more tags from tests/cases/tags.toml |
origin | yes | the kind of source and its licence |
source | no | the source format; default mathml |
target | no | the target format; default latex |
options | no | options for the conversion, such as { delimiters = "paren" } |
display | no | the expected display flag; default false |
taken_from | no | where the output is expected to come from; default markup |
fallbacks | no | the expected fallback codes in order; default none |
reference | no | a reference TeX the output must match |
The display flag, taken_from and the fallbacks are always checked: a
case that leaves out fallbacks asserts that the conversion makes no
fallback.
Origin names the kind of source and its licence, so that anyone can
check that the case may be published: hand-written, specification example, W3C Document License, journal XML, CC BY 4.0, fuzzing. It never
holds a URL, a host name or a publisher's name.
Minimal. A case holds the smallest input that shows its behaviour. Before adding an input from a corpus or from fuzzing, remove every element, attribute and character the behaviour does not need. A minimal case says exactly what it tests, fails for one reason, and carries no third-party content beyond a few symbols.
Tags group cases across directories. tests/cases/tags.toml lists
the allowed tags and their meanings; a case with an unlisted tag fails.
Tags name constructs (fraction), stages (parse), rewrite rules
(rule:pair-fences), fallback codes (fallback:glyph) and target
formats (output:text).
Running cases#
The case runner is a Rust test that runs each case file as its own test. Standard test filtering selects cases by path:
cargo test --test cases # every case
cargo test --test cases -- fraction/ # the fraction cases
When a deliberate change alters many outputs, regenerate the
expected fields from the current outputs, then review the whole diff
of the case files; every changed line must be intended:
cargo xtask bless tests/cases/fraction/
Conversion checks#
Conversion checks are invariants that hold for every input, so any failure is a bug. In Rust, a panic aborts the current operation on an unrecoverable internal error.
| Check | Holds when | Runs on |
|---|---|---|
| No panic | the conversion returns a result, without panicking or aborting, for example by overflowing the stack | cases, arbitrary input, corpus, fuzzing |
| No raw tags | the output contains no raw tag | cases, arbitrary input, corpus, fuzzing |
| No control characters | the output contains no control character other than tab, line feed and carriage return | arbitrary input, fuzzing |
| No second script | LaTeX output taken from the markup has no second superscript or subscript on one item | cases, arbitrary input, fuzzing |
| Characters accounted for | every token character of the input reaches the output or was removed by a named step | cases, arbitrary input, fuzzing |
| Deterministic | converting the same input again, alone or in a batch, gives the same result | cases, corpus, arbitrary input, fuzzing |
| Bounded time | a conversion takes at most a fixed time plus a time in proportion to the length of the input | arbitrary input, fuzzing |
| Renderers accept | KaTeX and MathJax both accept the converted LaTeX, as described below | cases, combining marks, corpus |
| Reference match | the output looks like the reference TeX | cases with reference; corpus formulas with a tex field |
No second script. A scan of the LaTeX output follows its braces and
control sequences, takes an item to be a character, a control sequence
or a braced group, and fails when an item gets a second ^, a second
_, or a ^ or an apostrophe after a superscript. An apostrophe is a
superscript, so s^2' fails and s^2{}' passes. Text commands such as
\text are skipped and carried TeX is not checked. The scan needs no
renderer, so it covers the arbitrary input and the fuzz targets, which
the render check does not reach.
Characters accounted for. Built with its ledger feature, as the
case runner and the arbitrary input test build it, the engine keeps a
ledger: lowering enters each character of each token and text node
it creates, and records the characters a lowering step leaves out, such
as control characters, with the step's name; the rewrite walker marks
the characters of every node a rule drops with the rule's name; and the
writer marks each character it writes, directly or through a command. A
character entered and left unmarked fails the check, which catches
content that disappears silently. Without the feature the ledger does
nothing.
Renderers accept. The render check runs the LaTeX output through
KaTeX and MathJax in Node.js, in batches, so that tens of thousands of
formulas take seconds in one process. KaTeX runs with throwOnError
set and strict mode error, which also rejects input that LaTeX itself
only tolerates, such as a text accent in math mode. One kind of
strictness is not applied: an unknown Unicode character inside \text,
which the engine writes with the fallback unmapped-character. KaTeX's
default settings accept it, and the check ignores the strict categories
KaTeX raises for it, unknownSymbol and, in text mode,
symbolNotInFont. Every other strict category stays an error, including
unicodeTextInMathMode, which KaTeX raises for characters in math mode
and never inside \text. MathJax runs its TeX
input with its default packages plus textmacros, without noundefined
(which would show an undefined control sequence as red text instead of
failing), and any parse error fails the check. The renderer versions are
pinned in tools/render-check/package.json and its lock file, and the
settings live in tools/render-check/render-check.mjs. Carried TeX is
returned as its author wrote it and is not checked.
Isolation. The answer to a string depends on that string alone, not
on the strings the same process handled before it. A reference TeX can
define macros, environments and delimiters (\newcommand, \def,
\let, \DeclareMathOperator), load extensions with \require, set
labels and tags, or fail to parse, and MathJax keeps all of that in its
TeX input jax. The render check therefore creates a new jax, with the
configured options, for every string it draws or converts, so a
definition lives only as long as its own request. KaTeX reads a fresh
macro table for each call. The check of cargo xtask render, which
cargo xtask check runs, begins with strings that leave state behind (a
redefined \|, a global macro, a label, a tag, an extension, a parse
error) and strings that depend on it, and sends them in reversed order,
in batches of uneven size and to two processes at once. It fails
unless every answer is the same everywhere and a string that nothing
defines is rejected.
cargo xtask render runs the check on the LaTeX output of every test
case that has a LaTeX target, with the delimiters left off and in the
display mode of its result, on every output shown in the examples of
LaTeX output style, in display mode where the
example's input is a display math element and inline otherwise, and
on generated formulas that place every code point of the combining
mark blocks alone and after a letter, a space, an escaped character and
a character with no command, in text and in tokens, because whether
KaTeX reads a combining mark depends on the mark and on what comes
before it. It prints each rejection with the input, the output and the
renderer's message. The same check runs in cargo xtask check, which fails with
installation instructions when Node.js or the packages are missing.
Reference match. A reference TeX is LaTeX known to show the same
formula: the reference field of a case, or the tex field of a
corpus row. The output matches it when it looks like it: MathJax draws
both with the same glyphs and rules, none of them displaced by more than
the tolerance of the visual comparison, so x^2
matches x^{2} and \le matches \leq. A mismatch fails a case; in a
corpus, the match rate is a measurement, because reference TeX is often
written differently from the markup beside it, and a corpus reference
first passes through the
reference rules.
Corpus evaluation describes the measurement.
Corpus evaluation#
The public corpus lives in the Hugging Face dataset mathconv-corpus, not in the repository. Each row holds one MathML formula from an openly licensed document, with its source, producer and licence, and, for part of the rows, reference TeX. Only formulas whose source licence permits redistribution are published. To request the removal of a formula, open an issue with the removal-request form, or write to legal@mathconv.dev if you do not use GitHub or prefer not to make the request in public; the rows are removed in the next revision of the dataset and are excluded from tests.
The corpus has two splits, assigned by document so that no document
contributes to both. dev is for developing the converter: read it and
study it. test is for reporting: use it to measure, not to tune
the converter. The evaluation sample is a fixed draw from test,
stratified by source and producer, small enough to evaluate on every
check; the README table measures it. The repository pins the dataset
revision and the checksum of each file it downloads, so every
evaluation reads the same formulas.
Other corpora are large and often under licences that forbid redistribution, so they stay outside the repository too.
cargo xtask eval # the pinned evaluation sample; rewrites the README table
cargo xtask eval --check # fails if the README table is out of date
cargo xtask eval --split dev # the whole development split; prints the scorecard only
cargo xtask eval --corpus <path> # a local corpus; prints the scorecard only
cargo xtask eval --corpus <path> --report # also writes target/eval/report.html
--split dev and --split test download the compressed split file
once into target/xtask/ and evaluate all of its formulas, which takes
several minutes; the render check answers are cached in target/eval/
for the next run. Use it to find where the converter fails, then read
the scorecard's failure lists. --split and --corpus never touch the
README.
A corpus is a JSON Lines file, a gzip-compressed one (.jsonl.gz), or a
directory whose .jsonl and .jsonl.gz row files are read in name
order; files ending in .documents.jsonl and hidden files are skipped.
Each line is an object with at least the fields id, mathml and
source, as in the public corpus. Three optional fields add
measurements:
| Field | Holds |
|---|---|
producer | the tool or publisher that wrote the MathML; the scorecard groups by it as well as by source |
tex | reference TeX for the formula, or null |
tex_kind | author for TeX written by a person, normalised for TeX produced by a tool that rewrites it |
The command streams the files, skips a pair of source and id that
repeats within a file, and converts each remaining formula for every
pair of a source format and a target format that the engine supports,
with default options. For the LaTeX target it also sends every output
to the render check. It prints a scorecard and writes it to
target/eval/scorecard.txt.
Measures#
For each pair, for the whole corpus, for each source value and for
each producer value, the scorecard gives:
-
the number of formulas evaluated and the share converted without fallback, that is, with no fallback code recorded, so that every element, entity and character was converted;
-
the throughput in formulas per second on one core, measured on a release build with one reused workspace;
-
for the LaTeX target, the share of outputs accepted by KaTeX and by MathJax, with the settings of the render check;
-
for formulas with a
texfield, separately for eachtex_kind, the agreement with the reference at two levels, which the visual comparison and the reference rules define:- looks like the reference: MathJax draws the output and the reference, after the reference rules for drawings, with the same glyphs and rules, and no one is displaced by more than the tolerance; the scorecard also gives the share drawn identically;
- identical after normalisation: the output and the reference, after the reference rules and the normalisation, are the same string.
Both comparisons leave the labels of lines out: the output compared is the conversion with
drop_labels, and a reference rule removes\tag. Reference TeX carries the number of an equation in some documents and not in others, and MathJax draws a tag at the right edge of the page, where it depends on the width of the page and not on the string alone.A reference that MathJax rejects, such as one that uses macros defined elsewhere in its document, cannot be compared. It is counted separately, by reason, and left out of both denominators, as is an output that MathJax rejects.
Beside the measures, the scorecard lists what to fix first. For the whole corpus it lists the 20 most frequent entries of each kind, and for each group the 5 most frequent, each with its number of formulas and up to three example ids:
- fallback signatures: a fallback code with its detail, usually an element name or a character;
- renderer rejections: the renderer and its error message, with the position and the quoted input removed so that equal errors group;
- first differences: for outputs that disagree with their
reference, the output's token and the reference's token at the first
place the two normalised strings differ, for example output
\limitsvs reference_. One list holds outputs that look different and one holds outputs that look alike but are spelled differently. Each entry of the first list also gives the typical size of the visual difference: the median displacement of its formulas in em and the median number of unpaired primitives, which the next section defines.
For each kind of reference the scorecard also counts how many references each reference rule changed and how many were excluded, by reason.
Visual comparison#
Two strings look alike when what MathJax draws for them is the same.
MathJax renders TeX to SVG entirely in Node.js, with each glyph as an
inline path from its own font data, so the drawing is a function of the
string, the display mode and the MathJax version: no browser, no
platform font and no rasteriser takes part. The render check's look
request draws both strings in the display mode of the output, inline or
display, and reduces each SVG to its primitives: the glyphs and the
rules (fraction bars, radical bars, lines over and under) with the box
that their ink occupies, measured in em from the baseline and the left
edge of the formula. It pairs the primitives of the two drawings and
reports two numbers:
- unpaired: how many primitives find no partner;
- shift: the largest distance, in em, between corresponding edges of the boxes of a pair, or of the frames of the two drawings. The frame includes the space that a formula leaves at its ends, so a missing trailing space counts.
A glyph is identified by its character when it is a symbol, and by its
outline when it is a letter or a digit. A delimiter or an operator comes
in several sizes with different outlines, which MathJax picks by the
height of the content, so \left( and ( around a short fraction pair;
an italic letter, an upright letter and a script capital are three
glyphs for one character, so they do not. Primitives of one identity are
paired in order of position.
A drawing is identical to another when nothing is unpaired and the
shift is zero, and it looks alike when nothing is unpaired and the
shift is at most TOLERANCE in xtask/src/render.rs, 0.1 em; otherwise it is
different. The measure "looks like the reference" counts identical
and alike drawings. The measures of each pair are cached, so changing the
tolerance needs no new rendering.
The tolerance separates spacings that no reader tells apart from spacings that someone asked for. Measured on pairs:
| Pair | Unpaired | Shift (em) | Verdict |
|---|---|---|---|
(x) and \left(x\right), \le and \leq, \to and \rightarrow, \mathrm{ab} and \mathrm{a}\mathrm{b} | 0 | 0 | identical |
a\;b and a\ b | 0 | 0.054 | alike |
\left(\frac ab\right) and (\frac ab) | 0 | 0.066 | alike |
A\ B and A\:B | 0 | 0.110 | different |
a\,b and ab (a missing thin space) | 0 | 0.167 | different |
f(x) and f\left(x\right) | 0 | 0.167 | different |
\frac{a}{b} and \frac{b}{a} | 0 | 0.739 | different |
x_a and x^a | 0 | 0.513 | different |
\sum_a^b and \sum\limits_a^b, inline | 0 | 0.748 | different |
a+b and a-b, \mathrm{U} and \mathcal{U}, ab and a | 1 to 2 | different |
The two kinds of space \; and \ differ by 0.054 em, less than a
pixel at the size of running text, so they count as alike; a thin space
moves everything after it by a sixth of an em, which is a deliberate
space and a visible one, so its absence counts as a difference. On the
8,590 pairs of the evaluation sample that MathJax renders, 5,573 are
identical and the shifts of the others fall as follows, which shows that
the tolerance sits in a sparse part of the distribution, below the peak
at one sixth of an em that thin spaces make:
| Largest shift (em) | Pairs with every primitive paired |
|---|---|
| 0 | 5,573 |
| up to 0.05 | 64 |
| 0.05 to 0.1 | 44 |
| 0.1 to 0.16 | 49 |
| 0.16 to 0.18 | 166 |
| 0.18 to 0.3 | 337 |
| 0.3 to 1 | 304 |
| over 1 | 318 |
991 further pairs have unpaired primitives.
The comparison pairs primitives and does not rasterise the drawings.
Comparing bitmaps after a blur that absorbs sub-pixel shifts also
absorbs small changes: a \frac{a}{b} against \frac{b}{a}, and an
upright against an italic c, differ in too few pixels of a
formula to stand out, and it costs more than drawing the formulas.
The primitives name what differs and by how much, which the scorecard
and the report use.
One render check compares about 750 pairs a second on a laptop, and the cache keeps the answers. Drawing the two strings is almost all of it; pairing the primitives takes under 2% of the time.
The HTML report#
--report writes target/eval/report.html, for judging clusters of
visual disagreement in seconds. For each kind of reference it lists the
15 most frequent clusters of the whole corpus, each with its size and six
of its formulas: the output and the reference as TeX, the reference after
the rules, MathJax's drawing of each, and the two drawings laid over one
another, the output in red and the reference in blue, with what they share
dark. The report holds formulas of whatever corpus was evaluated, so it
stays under target/ and is never committed.
Reference rules, normalisation and clusters#
A reference is what an author typed, and an author's TeX often asks for
something that the canonical output never writes: an old font switch, a
forced size, a spacing command that no MathML records. The comparison
should measure the engine against what the author meant, so the
reference rules rewrite such a choice into the spelling that the
style rules write, or remove it where the engine
writes nothing for it. They apply to the reference before it is
rendered or compared, never to the output, and each follows from a
style rule. Every rule applies to the spelling comparison. The comparison of
drawings applies every rule except the font switches, because MathJax
draws {\rm x} as it draws \mathrm{x}: that rule changes no verdict
there. The other rules rewrite choices that change the drawing, such as
the size of a fraction or of a fence, the placement of limits, the style
of a formula and the layout of a table, and they stay.
| Rule | Rewrites in the reference | Because |
|---|---|---|
| old font switches | {\rm x} to \mathrm{x}, likewise \bf, \it, \cal, \sf and \tt; a switch reaches to the end of its group or table cell | L1 maps variants to the \math… commands |
| infix fractions | {a \over b} to \frac{a}{b}, \choose to \binom, \atop to \genfrac | F1 and F2 write \frac, \binom and \genfrac |
| fraction styles | \dfrac and \tfrac to \frac, \dbinom and \tbinom to \binom | the markup records no request for a style, and F1 writes \frac |
| style switches | \displaystyle, \textstyle, \scriptstyle and \scriptscriptstyle removed | no rule writes a style switch |
| limits placement | \nolimits removed, and \limits removed unless an integral precedes it | U1 writes \limits only for the items of an integral |
| left and right | \left and \right removed around content without a fraction, root, table, under or over construct, large operator or function name that takes limits; a dot delimiter is dropped | B1 and B2 |
| manual sizes | \big, \Big, \bigg, \Bigg and their l, r and m forms removed, the delimiter kept | B1 writes no manual size |
| tags | \tag and \tag* removed with their argument | the comparison leaves the labels of lines out, as below |
| display environments | align, flalign, gather, multline and alignat, starred or not, to aligned, gathered or alignedat; equation to its content | M1 writes the inner environments for lines without labels, which is what the comparison compares |
A fence whose content may be tall stays as the author wrote it when the TeX alone cannot tell, as for a function name that takes limits: whether it is set below depends on the display mode, which is the engine's decision. The scorecard counts, for each kind of reference, the references that each rule changed, so that the size of each effect is visible, and the references that MathJax rejects after the rules, by reason: an undefined control sequence, such as a macro of the author's document, a private-use character, or another error. These stay a reason to exclude a reference and are never rewritten.
The two measures claim different things:
- Looks like the reference says that the output shows the formula
as the reference, once the rules have removed the reference's choices
that the engine never writes. It ignores the spelling:
\rightarrowand\to,\leand\leq,\left(x\right)and(x)look alike. It compares what is drawn, so an upright letter against an italic one, a\boldsymbolagainst a\mathbfGreek letter and a missing thin space differ, which a comparison of MathML elements does not see. - Identical after normalisation says that the output is spelled as
the reference, after the rules, white space and script braces below.
It is stricter: strings that are identical after normalisation draw
alike, and
\rightarrowagainst\tois a difference.
The normalisation changes the spelling of a TeX string and nothing that affects how it renders. It applies to the output as well as the reference, so a difference in white space or in the braces below never counts against the output:
- white space is removed, except one space after a control word that
a letter follows (
\alpha x) and inside the argument of a text command (\text,\textrm,\mboxand similar), where a run of white space becomes one space; - the braces around a script that is a single character, control word
or control symbol, or one font or accent command with its argument
(
\text,\mathrm,\mathbf,\hatand similar), are removed, sox^{2}becomesx^2andx_{\text{a}}becomesx_\text{a}.
Braces around other command arguments (\frac{a}{b}), around longer
scripts and around a base are kept, as are all commands that the rules
do not rewrite. A reference that spells a thing another way, such as
\to for \rightarrow, therefore differs, and the first-difference
lists show it.
Both measures cluster their disagreements by the first difference, which
is found on the normalised strings split into
tokens: a control word or control symbol, the whole argument of a text
command (shown as {text}, so two {text} tokens mean the text
differs), or any other single character. The clusters are the pairs of
the output's and the reference's first differing token, with (end) for
a string that ends first. The pair depends only on the two strings, so
runs agree, and ordering by count then by pair makes the lists
deterministic. The method is deliberately plain: it names the first
point of disagreement, which is usually the style choice, and a pair
that appears in many unrelated formulas is a systematic difference.
The render cache#
Rendering is the slowest part of the evaluation. Answers are kept in
target/eval/render-cache-<digest>.jsonl, keyed by the digest of the
request, which holds the output, the reference and the display flag; each
entry also keeps the request itself. The digest in the file name covers the KaTeX and MathJax versions and
the .mjs files of the render check, so a new renderer or new settings
start a new cache and delete the old one. A request that is not cached
goes to the render check; a large batch is shared among up to four
render checks that run side by side, and a small one starts a single
process. With a warm cache the evaluation does not start Node.js.
Node.js and the packages of the render check must still be installed,
and their absence is an error with installation instructions, as for
cargo xtask render.
Because the render check answers each request in isolation, a cached
answer equals a fresh one. cargo xtask eval --verify-cache renders a
random sample of 1,000 cached requests again in a new render check and
fails, listing each request with both answers, on any difference. To
clear the cache, delete target/eval/, which also holds the kept table;
the next evaluation renders everything again. The workflow of the
continuous integration deletes target/eval/ before cargo xtask check,
so that the coverage check there renders every output and reads no
earlier answer.
The table of the pinned evaluation sample is kept too, in
target/eval/table-<digest>.md. Its digest covers every input of the
evaluation: the files of crates/ and xtask/, the lock files, the
render check and its versions, and the corpus revision. When none of
them has changed since the table was computed, cargo xtask eval --check compares the kept table with the README and evaluates nothing,
which takes about a second. After any change to the engine it
converts the sample again and sends only the outputs that changed to
the renderers.
The coverage table#
The README holds a table with one row per supported pair: the formulas
of the evaluation sample, the share converted without fallback, the
share accepted by KaTeX and by MathJax with the settings of the
render check (a dash for a target that is not
LaTeX), and the share that looks like the reference, within the
tolerance of the visual comparison, for each
reference kind (a dash when the corpus has no reference of that kind).
These are the measures of the scorecard, described in
Measures; the lines under the table name the sample and
summarise each column. The table sits between the marker comments
<!-- coverage:start --> and <!-- coverage:end --> and is never
edited by hand. cargo xtask eval rewrites it, and cargo xtask check
fails when it differs from a fresh evaluation, so a change that alters
coverage includes the new table. Each column is one entry in the
COLUMNS list of xtask/src/eval/report.rs, so adding a measurement
means adding an entry.
The corpus is pinned in xtask/src/eval.rs by the commit of the
dataset and the SHA-256 checksum of data/formulas.jsonl at that
commit. The file is downloaded into target/xtask/ and verified. To
move to a newer corpus, set both constants to the new commit and the
checksum of its file, run cargo xtask eval, and commit the new table
with the new constants.
Arbitrary input#
crates/mathconv-cases/tests/arbitrary_input.rs runs the conversion
checks that need no renderer on every cargo test: random bytes,
random markup built from fragments of every element, each test case
input cut at twelve points, and long inputs such as deep nesting closed
by unmatched tags. The checks live in crates/mathconv-cases/src/checks.rs,
which the fuzz targets use as well. They run every converter, that is,
every source format with and without carried TeX and every target
format with each delimiters option, and require each conversion to
finish within two seconds, which catches superlinear behaviour.
Documentation examples#
tests/python/test_documents.py runs the Python examples of the README
and of every page of the user guide
against the installed package. Each example block runs on its own,
with mathconv imported. An example
is a statement followed by its value in a comment, as in
# 'x^2', either on the same line or on the next, and the value may be
followed by : and an explanation. The test fails when a statement
gives another value, so the documents cannot drift from the engine.
The npm package#
The tests in crates/mathconv-wasm/tests run against the packed
tarball, installed as users install it, with Node.js's built-in test
runner. They cover the API as an ES module and through require:
single and batch conversion, the options, the fields of a result, large
batches and inputs outside ASCII, and the errors of wrong options and
inputs. The entry for browsers and bundlers is loaded by its path to
check that converting before init fails and that init loads the
module once. Further tests check that the package holds only its
intended files and that its manifest names the types and the licence,
and tsc checks the TypeScript declarations against an example that
uses every part of the API. The JavaScript examples of the package's
README and of the JavaScript API reference
run against the package as the Python examples do, with the value in a
// comment, or the error class and message for a statement that
throws. cargo xtask npm runs them, and so does cargo xtask check.
Fuzzing#
Fuzzing runs the conversion checks that need no renderer on large
numbers of generated inputs. It uses
cargo-fuzz, which
drives libFuzzer: a coverage-guided fuzzer that keeps every input that
reaches new code and mutates the kept inputs to find more. The two
targets in fuzz/ run the checks of the arbitrary input test on every
converter, as listed in the conversion checks,
and compare each result with the results of converting the input again
in the same workspace and in a fresh one. The time limit of one
conversion is 100 ms plus 5 µs for each byte of input, so that an input
whose conversion time grows faster than its length is reported, while a
busy machine, which runs the instrumented build several times slower
than a release build, does not cause false alarms.
parse_and_converttakes arbitrary bytes, read as lossy UTF-8, and finds crashes and failed checks on broken markup. Its seed corpus holds the inputs of the test cases and the benchmark formulas, andfuzz/mathml.dictlists element, attribute and entity names, markup syntax and the characters that the converter treats specially, such as invisible operators, combining marks and control characters.structuredbuilds MathML from a grammar of every element the reader knows, content markup included with its operators, qualifiers, constructors, numbers with separators, long products and applications nested past the depth limit, with attributes of plausible and implausible values, entity references, namespace prefixes, comments and other markup, annotations of many encodings, tables of up to 150 rows and columns, rows of thousands of items, nesting up to and past the depth limit, and long runs of one character and of combining marks. It breaks some of the markup on purpose, with a missing or wrong closing tag, an unquoted attribute or a cut-short entity. The grammar reads the lengths of runs and rows from the input as numbers, so inputs of a few bytes describe formulas of hundreds of kilobytes, and it reaches the lowering, rewrite and writer code that random bytes rarely get to.
cargo xtask fuzz # each target for 60 seconds
cargo xtask fuzz --seconds 300 structured
The command writes the seeds to fuzz/corpus/, runs each target for the
given time and fails on a finding. It prints the path of the
reproducer in fuzz/artifacts/<target>/, a command that replays it, and
a command that minimises it with cargo fuzz tmin. The directories
fuzz/corpus/ and fuzz/artifacts/ are not tracked by Git; the seeds
are written from the test cases and the benchmark formulas on each run.
Running the targets needs a nightly Rust toolchain and cargo-fuzz, as
described in Contributing.
cargo xtask check does not run the fuzz targets, which need a nightly
toolchain and minutes of run time, so that the check stays fast. The
fuzz workflow of continuous integration runs each target for two
minutes on every pull request and every push to dev, and the
fuzz-daily workflow runs each for an hour on dev every day. The
daily run restores the corpus of the previous one from a cache, minimises
the corpus it grew with cargo fuzz cmin and saves it; the short runs
restore that corpus and do not save it, because a run replays the whole
corpus before it mutates anything, and a corpus that every change grew
would soon take all of the two minutes to replay. A finding fails the
job and uploads the reproducer as an artifact.
An input that fails a check is minimised and then becomes a regression
test. A small input whose output is stable becomes a test case, tagged
by the construct it concerns and with the origin fuzzing; an input
that is long, such as a run of tens of thousands of characters, becomes
a test in the arbitrary input test. The fix goes with it.