Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

c++ - How to get coverage for tests with CMake and Catch2

I'm trying to print coverage with lcov on a C++ project that is using Catch2 for tests. I'm able to run my tests and get results. However, I'm unable to get any coverage. This is the error that is shown.

Capturing coverage data from .
Found gcov version: 9.3.0
Using intermediate gcov format
Scanning . for .gcda files ...
geninfo: WARNING: no .gcda files found in . - skipping!
Finished .info-file creation
Combining tracefiles.
Reading tracefile coverage.base
lcov: ERROR: no valid records found in tracefile coverage.base

My current toolchain is WSL. I'm using Conan for dependency management. The solution has the following structure:

my project/
├─ build/
│  ├─ build files
├─ core/
│  ├─ library files
├─ main/
│  ├─ main runtime
├─ tests/
│  ├─ test runtime/
├─ CMakeLists.txt

Each folder has it's CMakeLists.txt file and is identified as a target. I'm also using this CMake Module to register a target for coverage.

My root CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.16)
project(my-project)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "-O0")

include(build/conanbuildinfo.cmake)
conan_basic_setup()

add_subdirectory(core)

option(BUILD_TESTING "Builds only the test executable." OFF)
option(CODE_COVERAGE "Collect coverage from test library" OFF)

if(BUILD_TESTING)
    enable_testing()
    add_subdirectory(tests)
    add_test(NAME project-tests COMMAND ./bin/tests)

    if(CODE_COVERAGE)
        include(CodeCoverage.cmake)
        append_coverage_compiler_flags()
        setup_target_for_coverage_lcov(NAME coverage EXECUTABLE ./bin/tests BASE_DIRECTORY ../coverage)
    endif()
else()
    add_subdirectory(main)
endif()

To get my coverage, I'm using the following commands (on build/).

cmake .. -DCODE_COVERAGE=ON -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug
make
make coverage

From what I understand, it seems to be missing some files necessary for coverage information, but I don't know how to make them. From what I've looked online, I have all the necessary compiler flags. I can't see what is wrong/missing in here.

question from:https://stackoverflow.com/questions/65603144/how-to-get-coverage-for-tests-with-cmake-and-catch2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe you forgot to add appropriate flags

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage")
set(CMAKE_CXX_FLAGS " ${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...