Unit Tests and Coverage

cover

Overview

In addition to the existing regression tests in test/, LibTIFF has a unit test suite, written in C++ with GoogleTest, in test/unit/. It contains two kinds of test:

  • black-box tests, which use only the public API declared in tiffio.h and link the regular library, and pin the form and behaviour of the exported interface; and

  • white-box tests, which exercise library internals directly, including functions which are not part of the public API.

The unit tests are intended to complement rather than replace the tool-based regression tests.

The unit tests are optional. They require a system installation of GoogleTest; they are skipped automatically when it is not available.

Enabling and running the tests

CMake

The unit-tests option accepts ON, OFF or AUTO (the default). With AUTO the tests are built if GoogleTest is found by find_package, and silently skipped otherwise. With ON, a missing GoogleTest is an error. The unit tests also require the regression test option tiff-tests to be ON (its default).

cmake -S . -B cmake-build -Dunit-tests=ON
cmake --build cmake-build
ctest --test-dir cmake-build -L unit --output-on-failure

The -L unit label selects only the unit tests; without it, ctest runs the complete suite.

Autotools

Use --enable-unit-tests. In the default (auto) mode the tests are skipped unless their requirements are found, including static libraries. The requirements are:

  • C++ support (--enable-cxx),

  • static libraries enabled (the tests link against the static archive),

  • GoogleTest, located with pkg-config.

./configure --enable-unit-tests
make
make check

To run only the unit tests, run make check in the test/unit directory.

Note

Maintainers: configure.ac uses PKG_PROG_PKG_CONFIG and PKG_CHECK_MODULES, so running autogen.sh requires pkg.m4 (installed with the pkg-config development files) to be present.

Testing strategy

The unit tests are being developed in three phases:

  1. Black-box tests of the public API pin the form of every exported function and the current behaviour of the interface.

  2. With that safety net in place, the library internals can be refactored: any change in the observable behaviour of the public API is caught by the black-box tests.

  3. White-box tests of the refactored internals follow, using the mechanisms described under White-box tests.

The black-box tests of phase 1 are complete, and cover every exported symbol. The white-box mechanisms already exist, and are used by a small number of tests written before the black-box suites.

For new contributions, the default is a black-box test of the public behaviour being added or changed. Use the white-box mechanisms only for internals that cannot reasonably be reached through the public API.

Writing tests

Tests live in test/unit/, in files named test_<name>.cpp, each built into a unit_<name> program. A new test must be added to both test/unit/CMakeLists.txt and test/unit/Makefile.am, as described below. All unit tests are registered under the CTest unit label.

Black-box public API tests

A black-box test exercises the library only through its public interface. It includes tiffio.h (and tiff_test_support.h for the fixtures), and must not include the library-private headers such as tiffiop.h. It is linked against the regular library, so that only exported symbols are available, and a use of an internal function fails to link:

  • in CMake, register it with tiff_public_test(<name>), which links the tiff target;

  • in Automake, add unit_<name> to check_PROGRAMS with unit_<name>_SOURCES and unit_<name>_LDADD (libtiff.la), and without -static in unit_<name>_LDFLAGS.

The existing suites are organised by area of the API (for example test_open.cpp, test_get_set_field.cpp, test_strip_io.cpp, test_directory.cpp and test_rgba.cpp); add tests for a function to the suite which owns it. The suites follow these conventions:

  • They characterise the current behaviour: the tests assert what the library does now, so that a refactoring which changes it is noticed. Where the behaviour is surprising, the test says so in a comment. A suspected bug is reported, and is not silently encoded as expected behaviour.

  • Files are created in memory with MemoryTiff, and diagnostics are captured with ErrorCapture (see Test fixtures). Only the tests of the file-based interfaces, such as TIFFOpen(), use temporary files.

  • Cases which need an optional codec check TIFFIsCODECConfigured() and call GTEST_SKIP() when it is not configured, so that the suite passes in every build configuration.

API signature pins

test/unit/test_api_signatures.cpp binds every symbol exported through the linker version script, libtiff/libtiff.map, to a function pointer of its exact declared type:

static constexpr TIFF *(*p_TIFFOpen)(const char *, const char *) = &TIFFOpen;

C++ does not convert implicitly between function pointer types, so any change to the return or parameter types of an exported function breaks the build of this test. Such a change alters the ABI and must be deliberate; when it is, update the pin alongside it. Because the test links the regular library, it also checks that every pinned symbol is exported. The public API is pinned with tiffio.h alone; the exported internal symbols used by the tools (for example _TIFFMultiply32) are pinned in a separate, marked section, which is the only place in the black-box tests where tiffiop.h is included.

The unit_api_pin_completeness test checks that every symbol in libtiff.map has a pin. It is registered in both build systems, each using the tools it can rely on: CTest runs test/unit/check_api_pins.cmake with cmake -P (no shell needed), and the Autotools harness runs the equivalent test/unit/check_api_pins.sh. A merge request which exports a new symbol must therefore:

  • add a pin for it to test_api_signatures.cpp, following the existing entries: the pointer itself, its entry in the kPins table which is checked at run time, and the expected count kExpectedPins (which is platform-conditional: TIFFOpenW and TIFFOpenWExt are declared and exported only on Windows, so the count there is two higher); and

  • add behavioural tests for it to the suite which owns its area of the API.

White-box tests

White-box tests reach the library internals. They are registered with tiff_unit_test(<name>) in CMake, and in Automake with unit_<name>_LDADD and unit_<name>_LDFLAGS = -static. There are two patterns, named after the module under test (tif_dirread.c in the examples below).

Tests of internal interfaces

test_<module>.cpp, for example test_dirread.cpp, includes the internal headers (tiffiop.h and friends) and calls internal (non-static, _TIFF-prefixed or otherwise unexported) functions. It is linked against the static library archive: the tiff_unit target in CMake, and libtiff.la -static in Automake. Use this pattern for an internal function which is reachable through a header but not through the public API.

Tests of static functions

test_<module>_internals.cpp, for example test_dirread_internals.cpp, directly includes the library source file (#include "tif_dirread.c") so that the test can call static functions and see file-local types. Use this pattern for narrowly scoped helpers, such as range checks, which are not worth exposing. It has several caveats:

  • The test translation unit contains its own copy of the module. It must precede the library archive on the link line so that its copies of the symbols are used and the archive member is not pulled in as well (which would give duplicate symbols). The build files already do this; follow the existing entries when adding a test.

  • Unity builds must be disabled for the test targets (CMake UNITY_BUILD OFF, which tiff_unit_test() sets), since combining them with other sources would merge the module into unrelated translation units.

  • Because the included module is compiled as part of the test, the library's own coverage of that module comes from the test's copy.

Promoting static functions

A function tested via direct inclusion may later be promoted to an internal (non-public) interface so that the ordinary test pattern can be used. Promote a static function when:

  • it has meaningful logic of its own;

  • it is a shared seam, that is, used or useful to other modules; or

  • its direct-include test is becoming unwieldy.

To promote a function:

  • rename it with a _TIFF prefix;

  • declare it in tiffiop.h (or in a per-module internal header) with complete Doxygen markup;

  • do not add it to the version script or the Windows .def files, since it is not part of the library's exported interface.

_TIFFReadDirEntryCheckedRational in tif_dirread.c is an example.

Test fixtures

test/unit/tiff_test_support.h provides the shared fixtures, in the tifftest namespace. They use only the public API, and so are available to both black-box and white-box tests:

MemoryTiff

Creates and opens a TIFF file held entirely in memory, so that tests need no files on disk and can construct malformed files easily. Deterministic I/O fault injection (failReadsAfter(), failWritesAfter(), failSeeksAfter(), cleared with resetFaults()) lets the next n calls of a client procedure succeed and fails every later one, so a test can fail a specific internal read, write or seek; readCalls(), writeCalls() and seekCalls() observe the traffic. enableMap(true) provides a working memory-map procedure so that "rM" opens exercise the memory-mapped read paths, observed with mapCalls() and unmapCalls().

RawTiff (raw_tiff.h)

Hand-assembles a TIFF file byte by byte — header, data blocks and IFDs, in either byte order, ClassicTIFF or BigTIFF — for reader tests whose input the library's writer would refuse to produce: unusual-but-valid layouts, unsorted or unlinked IFDs, directory loops (setNextIfd(), setFirstIfd()) and arbitrarily inconsistent entries (entryRaw()). Assign bytes() to MemoryTiff::data() and open through the public API.

ErrorCapture

Provides open options (options()) which install error and warning handlers on the handle being opened, and records the messages, so that tests can assert on diagnostics without printing them.

GlobalDiagnostics

Records the messages sent to the global error and warning handlers, for calls that have no TIFF handle (such as the codec registry functions) or whose handle carries no per-handle handlers, and restores the previous handlers on destruction.

isDiag()

Checks that a recorded message was reported by the given module and contains each of the given phrases. Assert diagnostics with discriminating phrases, not full-message equality: the full wording of a diagnostic is not part of the API.

Coverage analysis

Code coverage is measured with gcov instrumentation and reported with gcovr, which must be installed. Coverage is most meaningful with a Debug build.

CMake

cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Debug \
    -Dunit-tests=ON -Dcoverage=ON
cmake --build cmake-build
ctest --test-dir cmake-build -L unit
cmake --build cmake-build --target coverage

-Dcoverage=ON adds the --coverage compiler and linker flags, and provides a coverage target which runs gcovr. The HTML report (index.html), a Cobertura XML report (cobertura.xml) and a text summary are written to the coverage/ directory in the build directory.

Autotools

Configure with --enable-coverage, which adds the instrumentation flags, then build and run the tests:

./configure --enable-unit-tests --enable-coverage
make
make check

gcovr is then run manually from the build directory. The following is the canonical invocation, where /path/to/source is the absolute path of the source tree:

gcovr --root /path/to/source \
    --filter '/path/to/source/libtiff/' \
    --merge-mode-functions merge-use-line-min \
    . \
    --html-details coverage/index.html \
    --cobertura coverage/cobertura.xml \
    --txt

The --filter argument must be an absolute path. The . is the directory searched for coverage data; it must precede --txt, which would otherwise take it as its output file. Create the coverage directory first. With Apple Clang, also pass --gcov-executable "xcrun llvm-cov gcov"; with other Clang builds, pass --gcov-executable "llvm-cov gcov".

Continuous integration

The coverage job in the GitLab CI pipeline (which runs only in the main repository) builds with coverage enabled, runs the unit tests, and publishes the Cobertura report. GitLab uses this to annotate the lines of merge request diffs as covered or uncovered, so a merge request's new code can be checked for test coverage directly in the diff view.

Testing policy for contributions

Unit tests are part of how changes to the library are reviewed, and the following is expected of merge requests, from human and AI-assisted contributors alike. It applies to the code a merge request adds or changes, and does not require existing, untouched code to be retrofitted with tests.

  • A merge request which adds or changes library functions must, where practical, create or update unit tests covering those functions.

  • The tests should exercise both the core functionality and the edge cases of each function: boundary values, error paths and the diagnostics they report (using ErrorCapture), overflow conditions, and both byte orders where byte order is relevant.

  • Test public behaviour with black-box tests (see Black-box public API tests), in the suite which owns the area of the API. Use the white-box mechanisms only for internals which cannot be reached through the public API: test through the internal headers where the function is reachable that way, use direct inclusion for narrowly scoped static helpers, and promote a static function when it meets the criteria under Promoting static functions.

  • A merge request which exports a new symbol must add a signature pin for it (see API signature pins) as well as behavioural tests. A change to the signature of an exported function must update its pin, and is an ABI change.

  • Add new tests to both the CMake and Autotools builds.

  • Reviewers should check the merge request's coverage report (see Continuous integration) for the changed lines, and ask for further tests where those lines are not covered.

Where a function cannot reasonably be tested, for example because it needs a resource unavailable to the test environment, say so in the merge request description.