Skip to main content

The PreTeXt Guide

Section 4.38 Testing Sage Examples

This section gives the practical details behind Section 5.13, building on the <sage> element introduced in Section 3.17. When an example pairs an <input> with the <output> that Sage actually produced, that pair can be extracted into a file in the format of Sage’s own doctest framework, and Sage will re-run every input and compare its result against the recorded output. Over the life of a book this is the surest way to learn, early, that an upgrade to Sage has changed what one of your examples produces.

Subsection 4.38.1 One Result per Cell

For the comparison to work, author each <sage> cell so that its <input> has at most one top-level statement that produces output. Sage’s doctester attaches the expected <output> to the last statement of the cell, so a cell whose input prints twice can never be matched against two separate results. The remedy is simply to split such a cell into several, one result each.
<sage>
    <input>
    A = matrix(2, 2, [1, 2, 3, 4])
    A.determinant()
    </input>
    <output>
    -2
    </output>
</sage>
Here the assignment to A produces nothing and the determinant is the single result, so the cell tests cleanly. A multi-line construction is no obstacle: a for loop, or any statement continued across several lines, is one top-level statement, and its continuation lines keep it together as a single block. Only a second top-level statement that also prints needs a cell of its own.

Subsection 4.38.2 Generating and Running the Tests

The conversion is the pretext/xsl/pretext-sage-doctest.xsl stylesheet, applied to your source with xsltproc (see Section 46.11). It writes one or more files of Python, holding only the Sage input and expected output with your prose discarded. Chunking controls how many files are produced (Subsection 44.1.1), which is convenient for testing one chapter at a time.
Hand the resulting file to Sage’s testing facility, invoked with the -t option, as in sage -t chapter.py. Sage reports any example whose result no longer matches the recorded <output>. Such a report is your cue either to update the expected output, when the new result is correct, or to revisit the surrounding exposition when Sage’s behavior has genuinely shifted.
You have attempted of activities on this page.