Wednesday, 22 October 2014

Qt + CMake + code coverage

Yesterday I was working on getting reports on code coverage for Injeqt library. I've found several tutorials on the internet, but every one of them was missing a detail or two.

So here is what I've come with:

1. Update compiler and linker flags in CMakeLists.txt file of your tests:
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -W -g
    -fprofile-arcs -ftest-coverage -O0")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -W  -g
    -fprofile-arcs -ftest-coverage -O0")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}
    -fprofile-arcs -ftest-coverage -O0")
2. Link each test with gcov library:
target_link_libraries (test-target-name gcov)
3. Add new target for extracting coverage data:
add_custom_target (coverage
    COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/coverage.sh
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
4. Insert coverage.sh script into directory of CMakeLists.txt:
#!/bin/bash

lcov --capture --directory . --output-file coverage.info
lcov --directory . --output-file coverage.info \
    --remove coverage.info "/usr/*" "*.moc" "test/*"
genhtml coverage.info
First lcov invocation will capture all data from previously executed tests. Second will remove useless data like coverage of generated moc files or of standard library headers and tests themselves.

5. Run tests and coverage:
make test
make coverage
6. Enjoy nice HTML coverage report.

Injeqt got 90,4% of lines coverage on first try! I hope to make it even better today.

No comments:

Post a Comment