Mini Project 2: Presets & Tests
Part 2 makes TextStats pleasant to work on and safe to change: presets so every developer, IDE and CI job configures it the same way, and tests, unit tests of the library plus command-line tests of wcstats, registered with CTest. It builds on Part 1.
What's new
textstats/
├── CMakePresets.json dev + release presets, build/test presets, a workflow
├── CMakeLists.txt + option TEXTSTATS_BUILD_TESTS, enable_testing(), add_subdirectory(tests)
└── tests/
├── CMakeLists.txt unit.* and cli.* tests, labels, a fixture
├── test_textstats.cpp unit tests (no framework: exit code 0 = pass)
└── sample.txt input for the CLI testsThe tests are added only when TEXTSTATS_BUILD_TESTS is on, which defaults to PROJECT_IS_TOP_LEVEL: a project that embeds TextStats doesn't build them (Structuring Real Projects).
The test suite:
| Test | Label | Checks |
|---|---|---|
unit.count, unit.empty, unit.version |
unit |
the library API, through one test program run with three arguments |
cli.setup / cli.cleanup |
cli |
fixture sample: copy sample.txt into the test directory, remove it afterwards |
cli.counts |
cli |
requires the fixture; passes only if the output matches lines=3 words=9 chars=44 |
cli.missing |
cli |
WILL_FAIL: wcstats must fail on a missing file |
Develop with the dev preset
# ---- create the project (Mini Project part 2) ----
mkdir -p textstats/include/textstats textstats/src textstats/apps textstats/cmake textstats/tests && cd textstats
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25...4.4)
project(TextStats VERSION 1.2.0
DESCRIPTION "Line, word and character statistics"
LANGUAGES CXX)
include(GNUInstallDirs)
include(GenerateExportHeader)
include(CMakePackageConfigHelpers)
if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
endif()
option(TEXTSTATS_BUILD_APP "Build the wcstats program" ON)
option(TEXTSTATS_BUILD_TESTS "Build the TextStats tests" ${PROJECT_IS_TOP_LEVEL})
# ---- the library ------------------------------------------------------------
add_library(textstats src/textstats.cpp)
add_library(TextStats::textstats ALIAS textstats)
set_target_properties(textstats PROPERTIES
VERSION ${PROJECT_VERSION}
SOVERSION ${PROJECT_VERSION_MAJOR}
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON)
target_compile_features(textstats PUBLIC cxx_std_17)
set(gen ${CMAKE_CURRENT_BINARY_DIR}/generated)
generate_export_header(textstats EXPORT_FILE_NAME ${gen}/textstats/export.hpp)
configure_file(cmake/version.hpp.in ${gen}/textstats/version.hpp @ONLY)
target_sources(textstats PUBLIC
FILE_SET HEADERS
BASE_DIRS include ${gen}
FILES include/textstats/textstats.hpp
${gen}/textstats/export.hpp
${gen}/textstats/version.hpp)
# ---- the program -------------------------------------------------------------
if(TEXTSTATS_BUILD_APP)
add_executable(wcstats apps/wcstats.cpp)
target_link_libraries(wcstats PRIVATE TextStats::textstats)
file(RELATIVE_PATH bin_to_lib ${CMAKE_INSTALL_FULL_BINDIR} ${CMAKE_INSTALL_FULL_LIBDIR})
set_target_properties(wcstats PROPERTIES INSTALL_RPATH "$ORIGIN/${bin_to_lib}")
endif()
# ---- tests ---------------------------------------------------------------------
if(TEXTSTATS_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
# ---- install + export ----------------------------------------------------------
set(cmake_dir ${CMAKE_INSTALL_LIBDIR}/cmake/TextStats)
install(TARGETS textstats EXPORT TextStatsTargets
LIBRARY COMPONENT runtime NAMELINK_COMPONENT dev
ARCHIVE COMPONENT dev
RUNTIME COMPONENT runtime
FILE_SET HEADERS COMPONENT dev)
if(TEXTSTATS_BUILD_APP)
install(TARGETS wcstats RUNTIME COMPONENT runtime)
endif()
install(EXPORT TextStatsTargets NAMESPACE TextStats::
DESTINATION ${cmake_dir} COMPONENT dev)
configure_package_config_file(cmake/TextStatsConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
INSTALL_DESTINATION ${cmake_dir})
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
COMPATIBILITY SameMajorVersion)
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
DESTINATION ${cmake_dir} COMPONENT dev)
export(EXPORT TextStatsTargets NAMESPACE TextStats::
FILE ${CMAKE_CURRENT_BINARY_DIR}/TextStatsTargets.cmake)
CM
cat > cmake/TextStatsConfig.cmake.in <<'CM'
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/TextStatsTargets.cmake")
check_required_components(TextStats)
CM
cat > cmake/version.hpp.in <<'SRC'
#pragma once
#define TEXTSTATS_VERSION "@PROJECT_VERSION@"
#define TEXTSTATS_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
SRC
cat > include/textstats/textstats.hpp <<'SRC'
#pragma once
#include <cstddef>
#include <string>
#include <string_view>
#include <textstats/export.hpp>
namespace textstats {
struct Stats { std::size_t lines = 0, words = 0, chars = 0; };
TEXTSTATS_EXPORT Stats count(std::string_view text);
TEXTSTATS_EXPORT std::string version();
} // namespace textstats
SRC
cat > src/textstats.cpp <<'SRC'
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#include <cctype>
namespace textstats {
namespace {
bool is_space(char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; }
}
Stats count(std::string_view text) {
Stats s;
bool in_word = false;
for (char c : text) {
++s.chars;
if (c == '\n') ++s.lines;
if (is_space(c)) in_word = false;
else if (!in_word) { in_word = true; ++s.words; }
}
if (!text.empty() && text.back() != '\n') ++s.lines;
return s;
}
std::string version() { return TEXTSTATS_VERSION; }
} // namespace textstats
SRC
cat > apps/wcstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstream>
#include <textstats/textstats.hpp>
int main(int argc, char** argv) {
if (argc < 2) { std::puts("usage: wcstats FILE... | --version"); return 2; }
if (std::strcmp(argv[1], "--version") == 0) {
std::printf("wcstats (TextStats %s)\n", textstats::version().c_str());
return 0;
}
int status = 0;
for (int i = 1; i < argc; ++i) {
std::ifstream in(argv[i]);
if (!in) { std::printf("%s: cannot open\n", argv[i]); status = 1; continue; }
std::stringstream buf;
buf << in.rdbuf();
textstats::Stats s = textstats::count(buf.str());
std::printf("%s: lines=%zu words=%zu chars=%zu\n", argv[i], s.lines, s.words, s.chars);
}
return status;
}
SRC
cat > tests/CMakeLists.txt <<'CM'
add_executable(textstats_tests test_textstats.cpp)
target_link_libraries(textstats_tests PRIVATE TextStats::textstats)
foreach(t count empty version)
add_test(NAME unit.${t} COMMAND textstats_tests ${t})
endforeach()
set_tests_properties(unit.count unit.empty unit.version PROPERTIES LABELS unit)
if(TARGET wcstats)
# A fixture copies the sample file into the test directory and removes it afterwards.
add_test(NAME cli.setup COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/sample.txt sample.txt)
add_test(NAME cli.cleanup COMMAND ${CMAKE_COMMAND} -E rm -f sample.txt)
add_test(NAME cli.counts COMMAND wcstats sample.txt)
add_test(NAME cli.missing COMMAND wcstats no-such-file.txt)
set_tests_properties(cli.setup PROPERTIES FIXTURES_SETUP sample)
set_tests_properties(cli.cleanup PROPERTIES FIXTURES_CLEANUP sample)
set_tests_properties(cli.counts PROPERTIES FIXTURES_REQUIRED sample
PASS_REGULAR_EXPRESSION "lines=3 words=9 chars=44")
set_tests_properties(cli.missing PROPERTIES WILL_FAIL TRUE)
set_tests_properties(cli.setup cli.cleanup cli.counts cli.missing PROPERTIES LABELS cli)
endif()
CM
cat > tests/test_textstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#define CHECK(e) do { if (!(e)) { std::printf("FAILED: %s (line %d)\n", #e, __LINE__); return 1; } } while (0)
int main(int argc, char** argv) {
const char* t = argc > 1 ? argv[1] : "";
if (!std::strcmp(t, "count")) {
textstats::Stats s = textstats::count("one two\nthree\n");
CHECK(s.lines == 2); CHECK(s.words == 3); CHECK(s.chars == 14);
} else if (!std::strcmp(t, "empty")) {
textstats::Stats s = textstats::count("");
CHECK(s.lines == 0 && s.words == 0 && s.chars == 0);
} else if (!std::strcmp(t, "version")) {
CHECK(textstats::version() == TEXTSTATS_VERSION);
} else {
std::printf("unknown test '%s'\n", t);
return 2;
}
std::printf("%s: ok\n", t);
return 0;
}
SRC
printf 'the quick brown fox\njumps over\nthe lazy dog\n' > tests/sample.txt
cat > CMakePresets.json <<'JSON'
{
"version": 6,
"cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
"configurePresets": [
{
"name": "base",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}",
"cacheVariables": { "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" }
},
{ "name": "dev", "displayName": "Development (Debug)", "inherits": "base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } },
{ "name": "release", "displayName": "Release", "inherits": "base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }
],
"buildPresets": [
{ "name": "dev", "configurePreset": "dev" },
{ "name": "release", "configurePreset": "release" }
],
"testPresets": [
{ "name": "dev", "configurePreset": "dev",
"output": { "outputOnFailure": true },
"execution": { "noTestsAction": "error" } },
{ "name": "release", "inherits": "dev", "configurePreset": "release" }
],
"workflowPresets": [
{
"name": "release",
"steps": [
{ "type": "configure", "name": "release" },
{ "type": "build", "name": "release" },
{ "type": "test", "name": "release" }
]
}
]
}
JSON
cmake --list-presets=all
echo "=== configure, build, test with the dev preset"
cmake --preset dev --log-level=NOTICE
cmake --build --preset dev
ctest --preset devAvailable configure presets:
"dev" - Development (Debug)
"release" - Release
Available build presets:
"dev"
"release"
Available test presets:
"dev"
"release"
Available workflow presets:
"release"
=== configure, build, test with the dev preset
-- Configuring done (0.5s)
-- Generating done (0.0s)
-- Build files have been written to: /home/learner/textstats/build/dev
[1/7] Building CXX object CMakeFiles/textstats.dir/src/textstats.cpp.o
[2/7] Linking CXX shared library libtextstats.so.1.2.0
[3/7] Creating library symlink libtextstats.so.1 libtextstats.so
[4/7] Building CXX object CMakeFiles/wcstats.dir/apps/wcstats.cpp.o
[5/7] Building CXX object tests/CMakeFiles/textstats_tests.dir/test_textstats.cpp.o
[6/7] Linking CXX executable wcstats
[7/7] Linking CXX executable tests/textstats_tests
Test project /home/learner/textstats/build/dev
Start 1: unit.count
1/7 Test #1: unit.count ....................... Passed 0.00 sec
Start 2: unit.empty
2/7 Test #2: unit.empty ....................... Passed 0.00 sec
Start 3: unit.version
3/7 Test #3: unit.version ..................... Passed 0.00 sec
Start 4: cli.setup
4/7 Test #4: cli.setup ........................ Passed 0.00 sec
Start 6: cli.counts
5/7 Test #6: cli.counts ....................... Passed 0.00 sec
Start 5: cli.cleanup
6/7 Test #5: cli.cleanup ...................... Passed 0.00 sec
Start 7: cli.missing
7/7 Test #7: cli.missing ...................... Passed 0.00 sec
100% tests passed out of 7
Label Time Summary:
cli = 0.01 sec*proc (4 tests)
unit = 0.01 sec*proc (3 tests)
Total Test time (real) = 0.02 sec
Note the order CTest chose: cli.setup ran before cli.counts and cli.cleanup right after it, although the cleanup test was registered first. That's the fixture at work (Test Fixtures). The Label Time Summary appears because the tests have labels.
Running subsets
# ---- create the project (Mini Project part 2) ----
mkdir -p textstats/include/textstats textstats/src textstats/apps textstats/cmake textstats/tests && cd textstats
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25...4.4)
project(TextStats VERSION 1.2.0
DESCRIPTION "Line, word and character statistics"
LANGUAGES CXX)
include(GNUInstallDirs)
include(GenerateExportHeader)
include(CMakePackageConfigHelpers)
if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
endif()
option(TEXTSTATS_BUILD_APP "Build the wcstats program" ON)
option(TEXTSTATS_BUILD_TESTS "Build the TextStats tests" ${PROJECT_IS_TOP_LEVEL})
# ---- the library ------------------------------------------------------------
add_library(textstats src/textstats.cpp)
add_library(TextStats::textstats ALIAS textstats)
set_target_properties(textstats PROPERTIES
VERSION ${PROJECT_VERSION}
SOVERSION ${PROJECT_VERSION_MAJOR}
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON)
target_compile_features(textstats PUBLIC cxx_std_17)
set(gen ${CMAKE_CURRENT_BINARY_DIR}/generated)
generate_export_header(textstats EXPORT_FILE_NAME ${gen}/textstats/export.hpp)
configure_file(cmake/version.hpp.in ${gen}/textstats/version.hpp @ONLY)
target_sources(textstats PUBLIC
FILE_SET HEADERS
BASE_DIRS include ${gen}
FILES include/textstats/textstats.hpp
${gen}/textstats/export.hpp
${gen}/textstats/version.hpp)
# ---- the program -------------------------------------------------------------
if(TEXTSTATS_BUILD_APP)
add_executable(wcstats apps/wcstats.cpp)
target_link_libraries(wcstats PRIVATE TextStats::textstats)
file(RELATIVE_PATH bin_to_lib ${CMAKE_INSTALL_FULL_BINDIR} ${CMAKE_INSTALL_FULL_LIBDIR})
set_target_properties(wcstats PROPERTIES INSTALL_RPATH "$ORIGIN/${bin_to_lib}")
endif()
# ---- tests ---------------------------------------------------------------------
if(TEXTSTATS_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
# ---- install + export ----------------------------------------------------------
set(cmake_dir ${CMAKE_INSTALL_LIBDIR}/cmake/TextStats)
install(TARGETS textstats EXPORT TextStatsTargets
LIBRARY COMPONENT runtime NAMELINK_COMPONENT dev
ARCHIVE COMPONENT dev
RUNTIME COMPONENT runtime
FILE_SET HEADERS COMPONENT dev)
if(TEXTSTATS_BUILD_APP)
install(TARGETS wcstats RUNTIME COMPONENT runtime)
endif()
install(EXPORT TextStatsTargets NAMESPACE TextStats::
DESTINATION ${cmake_dir} COMPONENT dev)
configure_package_config_file(cmake/TextStatsConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
INSTALL_DESTINATION ${cmake_dir})
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
COMPATIBILITY SameMajorVersion)
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
DESTINATION ${cmake_dir} COMPONENT dev)
export(EXPORT TextStatsTargets NAMESPACE TextStats::
FILE ${CMAKE_CURRENT_BINARY_DIR}/TextStatsTargets.cmake)
CM
cat > cmake/TextStatsConfig.cmake.in <<'CM'
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/TextStatsTargets.cmake")
check_required_components(TextStats)
CM
cat > cmake/version.hpp.in <<'SRC'
#pragma once
#define TEXTSTATS_VERSION "@PROJECT_VERSION@"
#define TEXTSTATS_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
SRC
cat > include/textstats/textstats.hpp <<'SRC'
#pragma once
#include <cstddef>
#include <string>
#include <string_view>
#include <textstats/export.hpp>
namespace textstats {
struct Stats { std::size_t lines = 0, words = 0, chars = 0; };
TEXTSTATS_EXPORT Stats count(std::string_view text);
TEXTSTATS_EXPORT std::string version();
} // namespace textstats
SRC
cat > src/textstats.cpp <<'SRC'
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#include <cctype>
namespace textstats {
namespace {
bool is_space(char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; }
}
Stats count(std::string_view text) {
Stats s;
bool in_word = false;
for (char c : text) {
++s.chars;
if (c == '\n') ++s.lines;
if (is_space(c)) in_word = false;
else if (!in_word) { in_word = true; ++s.words; }
}
if (!text.empty() && text.back() != '\n') ++s.lines;
return s;
}
std::string version() { return TEXTSTATS_VERSION; }
} // namespace textstats
SRC
cat > apps/wcstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstream>
#include <textstats/textstats.hpp>
int main(int argc, char** argv) {
if (argc < 2) { std::puts("usage: wcstats FILE... | --version"); return 2; }
if (std::strcmp(argv[1], "--version") == 0) {
std::printf("wcstats (TextStats %s)\n", textstats::version().c_str());
return 0;
}
int status = 0;
for (int i = 1; i < argc; ++i) {
std::ifstream in(argv[i]);
if (!in) { std::printf("%s: cannot open\n", argv[i]); status = 1; continue; }
std::stringstream buf;
buf << in.rdbuf();
textstats::Stats s = textstats::count(buf.str());
std::printf("%s: lines=%zu words=%zu chars=%zu\n", argv[i], s.lines, s.words, s.chars);
}
return status;
}
SRC
cat > tests/CMakeLists.txt <<'CM'
add_executable(textstats_tests test_textstats.cpp)
target_link_libraries(textstats_tests PRIVATE TextStats::textstats)
foreach(t count empty version)
add_test(NAME unit.${t} COMMAND textstats_tests ${t})
endforeach()
set_tests_properties(unit.count unit.empty unit.version PROPERTIES LABELS unit)
if(TARGET wcstats)
# A fixture copies the sample file into the test directory and removes it afterwards.
add_test(NAME cli.setup COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/sample.txt sample.txt)
add_test(NAME cli.cleanup COMMAND ${CMAKE_COMMAND} -E rm -f sample.txt)
add_test(NAME cli.counts COMMAND wcstats sample.txt)
add_test(NAME cli.missing COMMAND wcstats no-such-file.txt)
set_tests_properties(cli.setup PROPERTIES FIXTURES_SETUP sample)
set_tests_properties(cli.cleanup PROPERTIES FIXTURES_CLEANUP sample)
set_tests_properties(cli.counts PROPERTIES FIXTURES_REQUIRED sample
PASS_REGULAR_EXPRESSION "lines=3 words=9 chars=44")
set_tests_properties(cli.missing PROPERTIES WILL_FAIL TRUE)
set_tests_properties(cli.setup cli.cleanup cli.counts cli.missing PROPERTIES LABELS cli)
endif()
CM
cat > tests/test_textstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#define CHECK(e) do { if (!(e)) { std::printf("FAILED: %s (line %d)\n", #e, __LINE__); return 1; } } while (0)
int main(int argc, char** argv) {
const char* t = argc > 1 ? argv[1] : "";
if (!std::strcmp(t, "count")) {
textstats::Stats s = textstats::count("one two\nthree\n");
CHECK(s.lines == 2); CHECK(s.words == 3); CHECK(s.chars == 14);
} else if (!std::strcmp(t, "empty")) {
textstats::Stats s = textstats::count("");
CHECK(s.lines == 0 && s.words == 0 && s.chars == 0);
} else if (!std::strcmp(t, "version")) {
CHECK(textstats::version() == TEXTSTATS_VERSION);
} else {
std::printf("unknown test '%s'\n", t);
return 2;
}
std::printf("%s: ok\n", t);
return 0;
}
SRC
printf 'the quick brown fox\njumps over\nthe lazy dog\n' > tests/sample.txt
cat > CMakePresets.json <<'JSON'
{
"version": 6,
"cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
"configurePresets": [
{
"name": "base",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}",
"cacheVariables": { "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" }
},
{ "name": "dev", "displayName": "Development (Debug)", "inherits": "base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } },
{ "name": "release", "displayName": "Release", "inherits": "base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }
],
"buildPresets": [
{ "name": "dev", "configurePreset": "dev" },
{ "name": "release", "configurePreset": "release" }
],
"testPresets": [
{ "name": "dev", "configurePreset": "dev",
"output": { "outputOnFailure": true },
"execution": { "noTestsAction": "error" } },
{ "name": "release", "inherits": "dev", "configurePreset": "release" }
],
"workflowPresets": [
{
"name": "release",
"steps": [
{ "type": "configure", "name": "release" },
{ "type": "build", "name": "release" },
{ "type": "test", "name": "release" }
]
}
]
}
JSON
cmake --preset dev --log-level=NOTICE > /dev/null
cmake --build --preset dev > /dev/null
echo "=== only the unit tests"
ctest --preset dev -L unit 2>&1 | grep -E 'Test +#|tests passed'
echo "=== one CLI test: its fixture comes along"
ctest --preset dev -R cli.counts 2>&1 | grep -E 'Test +#|tests passed'
echo "=== break the library and watch the tests catch it"
sed -i 's/++s.words; }/++s.words; ++s.words; }/' src/textstats.cpp
cmake --build --preset dev > /dev/null
ctest --preset dev 2>&1 | grep -E 'Test +#|^FAILED:|tests passed|lines='=== only the unit tests
1/3 Test #1: unit.count ....................... Passed 0.00 sec
2/3 Test #2: unit.empty ....................... Passed 0.00 sec
3/3 Test #3: unit.version ..................... Passed 0.00 sec
100% tests passed out of 3
=== one CLI test: its fixture comes along
1/3 Test #4: cli.setup ........................ Passed 0.00 sec
2/3 Test #6: cli.counts ....................... Passed 0.00 sec
3/3 Test #5: cli.cleanup ...................... Passed 0.00 sec
100% tests passed out of 3
=== break the library and watch the tests catch it
1/7 Test #1: unit.count .......................***Failed 0.00 sec
FAILED: s.words == 3 (line 12)
2/7 Test #2: unit.empty ....................... Passed 0.00 sec
3/7 Test #3: unit.version ..................... Passed 0.00 sec
4/7 Test #4: cli.setup ........................ Passed 0.00 sec
5/7 Test #6: cli.counts .......................***Failed Required regular expression not found. Regex=[lines=3 words=9 chars=44
sample.txt: lines=3 words=18 chars=44
6/7 Test #5: cli.cleanup ...................... Passed 0.00 sec
7/7 Test #7: cli.missing ...................... Passed 0.00 sec
71% tests passed, 2 tests failed out of 7
The deliberate bug (counting every word twice) was caught twice: by the unit test (FAILED: s.words == 3, printed thanks to the preset's outputOnFailure) and by the CLI test, whose output no longer matched the required regular expression.
The release workflow
The release workflow preset chains configure, build and test: one command for CI.
# ---- create the project (Mini Project part 2) ----
mkdir -p textstats/include/textstats textstats/src textstats/apps textstats/cmake textstats/tests && cd textstats
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25...4.4)
project(TextStats VERSION 1.2.0
DESCRIPTION "Line, word and character statistics"
LANGUAGES CXX)
include(GNUInstallDirs)
include(GenerateExportHeader)
include(CMakePackageConfigHelpers)
if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
endif()
option(TEXTSTATS_BUILD_APP "Build the wcstats program" ON)
option(TEXTSTATS_BUILD_TESTS "Build the TextStats tests" ${PROJECT_IS_TOP_LEVEL})
# ---- the library ------------------------------------------------------------
add_library(textstats src/textstats.cpp)
add_library(TextStats::textstats ALIAS textstats)
set_target_properties(textstats PROPERTIES
VERSION ${PROJECT_VERSION}
SOVERSION ${PROJECT_VERSION_MAJOR}
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON)
target_compile_features(textstats PUBLIC cxx_std_17)
set(gen ${CMAKE_CURRENT_BINARY_DIR}/generated)
generate_export_header(textstats EXPORT_FILE_NAME ${gen}/textstats/export.hpp)
configure_file(cmake/version.hpp.in ${gen}/textstats/version.hpp @ONLY)
target_sources(textstats PUBLIC
FILE_SET HEADERS
BASE_DIRS include ${gen}
FILES include/textstats/textstats.hpp
${gen}/textstats/export.hpp
${gen}/textstats/version.hpp)
# ---- the program -------------------------------------------------------------
if(TEXTSTATS_BUILD_APP)
add_executable(wcstats apps/wcstats.cpp)
target_link_libraries(wcstats PRIVATE TextStats::textstats)
file(RELATIVE_PATH bin_to_lib ${CMAKE_INSTALL_FULL_BINDIR} ${CMAKE_INSTALL_FULL_LIBDIR})
set_target_properties(wcstats PROPERTIES INSTALL_RPATH "$ORIGIN/${bin_to_lib}")
endif()
# ---- tests ---------------------------------------------------------------------
if(TEXTSTATS_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()
# ---- install + export ----------------------------------------------------------
set(cmake_dir ${CMAKE_INSTALL_LIBDIR}/cmake/TextStats)
install(TARGETS textstats EXPORT TextStatsTargets
LIBRARY COMPONENT runtime NAMELINK_COMPONENT dev
ARCHIVE COMPONENT dev
RUNTIME COMPONENT runtime
FILE_SET HEADERS COMPONENT dev)
if(TEXTSTATS_BUILD_APP)
install(TARGETS wcstats RUNTIME COMPONENT runtime)
endif()
install(EXPORT TextStatsTargets NAMESPACE TextStats::
DESTINATION ${cmake_dir} COMPONENT dev)
configure_package_config_file(cmake/TextStatsConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
INSTALL_DESTINATION ${cmake_dir})
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
COMPATIBILITY SameMajorVersion)
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
DESTINATION ${cmake_dir} COMPONENT dev)
export(EXPORT TextStatsTargets NAMESPACE TextStats::
FILE ${CMAKE_CURRENT_BINARY_DIR}/TextStatsTargets.cmake)
CM
cat > cmake/TextStatsConfig.cmake.in <<'CM'
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/TextStatsTargets.cmake")
check_required_components(TextStats)
CM
cat > cmake/version.hpp.in <<'SRC'
#pragma once
#define TEXTSTATS_VERSION "@PROJECT_VERSION@"
#define TEXTSTATS_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
SRC
cat > include/textstats/textstats.hpp <<'SRC'
#pragma once
#include <cstddef>
#include <string>
#include <string_view>
#include <textstats/export.hpp>
namespace textstats {
struct Stats { std::size_t lines = 0, words = 0, chars = 0; };
TEXTSTATS_EXPORT Stats count(std::string_view text);
TEXTSTATS_EXPORT std::string version();
} // namespace textstats
SRC
cat > src/textstats.cpp <<'SRC'
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#include <cctype>
namespace textstats {
namespace {
bool is_space(char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; }
}
Stats count(std::string_view text) {
Stats s;
bool in_word = false;
for (char c : text) {
++s.chars;
if (c == '\n') ++s.lines;
if (is_space(c)) in_word = false;
else if (!in_word) { in_word = true; ++s.words; }
}
if (!text.empty() && text.back() != '\n') ++s.lines;
return s;
}
std::string version() { return TEXTSTATS_VERSION; }
} // namespace textstats
SRC
cat > apps/wcstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstream>
#include <textstats/textstats.hpp>
int main(int argc, char** argv) {
if (argc < 2) { std::puts("usage: wcstats FILE... | --version"); return 2; }
if (std::strcmp(argv[1], "--version") == 0) {
std::printf("wcstats (TextStats %s)\n", textstats::version().c_str());
return 0;
}
int status = 0;
for (int i = 1; i < argc; ++i) {
std::ifstream in(argv[i]);
if (!in) { std::printf("%s: cannot open\n", argv[i]); status = 1; continue; }
std::stringstream buf;
buf << in.rdbuf();
textstats::Stats s = textstats::count(buf.str());
std::printf("%s: lines=%zu words=%zu chars=%zu\n", argv[i], s.lines, s.words, s.chars);
}
return status;
}
SRC
cat > tests/CMakeLists.txt <<'CM'
add_executable(textstats_tests test_textstats.cpp)
target_link_libraries(textstats_tests PRIVATE TextStats::textstats)
foreach(t count empty version)
add_test(NAME unit.${t} COMMAND textstats_tests ${t})
endforeach()
set_tests_properties(unit.count unit.empty unit.version PROPERTIES LABELS unit)
if(TARGET wcstats)
# A fixture copies the sample file into the test directory and removes it afterwards.
add_test(NAME cli.setup COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/sample.txt sample.txt)
add_test(NAME cli.cleanup COMMAND ${CMAKE_COMMAND} -E rm -f sample.txt)
add_test(NAME cli.counts COMMAND wcstats sample.txt)
add_test(NAME cli.missing COMMAND wcstats no-such-file.txt)
set_tests_properties(cli.setup PROPERTIES FIXTURES_SETUP sample)
set_tests_properties(cli.cleanup PROPERTIES FIXTURES_CLEANUP sample)
set_tests_properties(cli.counts PROPERTIES FIXTURES_REQUIRED sample
PASS_REGULAR_EXPRESSION "lines=3 words=9 chars=44")
set_tests_properties(cli.missing PROPERTIES WILL_FAIL TRUE)
set_tests_properties(cli.setup cli.cleanup cli.counts cli.missing PROPERTIES LABELS cli)
endif()
CM
cat > tests/test_textstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#define CHECK(e) do { if (!(e)) { std::printf("FAILED: %s (line %d)\n", #e, __LINE__); return 1; } } while (0)
int main(int argc, char** argv) {
const char* t = argc > 1 ? argv[1] : "";
if (!std::strcmp(t, "count")) {
textstats::Stats s = textstats::count("one two\nthree\n");
CHECK(s.lines == 2); CHECK(s.words == 3); CHECK(s.chars == 14);
} else if (!std::strcmp(t, "empty")) {
textstats::Stats s = textstats::count("");
CHECK(s.lines == 0 && s.words == 0 && s.chars == 0);
} else if (!std::strcmp(t, "version")) {
CHECK(textstats::version() == TEXTSTATS_VERSION);
} else {
std::printf("unknown test '%s'\n", t);
return 2;
}
std::printf("%s: ok\n", t);
return 0;
}
SRC
printf 'the quick brown fox\njumps over\nthe lazy dog\n' > tests/sample.txt
cat > CMakePresets.json <<'JSON'
{
"version": 6,
"cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
"configurePresets": [
{
"name": "base",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}",
"cacheVariables": { "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" }
},
{ "name": "dev", "displayName": "Development (Debug)", "inherits": "base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } },
{ "name": "release", "displayName": "Release", "inherits": "base",
"cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }
],
"buildPresets": [
{ "name": "dev", "configurePreset": "dev" },
{ "name": "release", "configurePreset": "release" }
],
"testPresets": [
{ "name": "dev", "configurePreset": "dev",
"output": { "outputOnFailure": true },
"execution": { "noTestsAction": "error" } },
{ "name": "release", "inherits": "dev", "configurePreset": "release" }
],
"workflowPresets": [
{
"name": "release",
"steps": [
{ "type": "configure", "name": "release" },
{ "type": "build", "name": "release" },
{ "type": "test", "name": "release" }
]
}
]
}
JSON
cmake --workflow --preset release 2>&1 | grep -E '^Executing|tests passed|Linking'
ls build
test -f build/release/compile_commands.json && echo "compile_commands.json is there for clangd"Executing workflow step 1 of 3: configure preset "release"
Executing workflow step 2 of 3: build preset "release"
[2/7] Linking CXX shared library libtextstats.so.1.2.0
[6/7] Linking CXX executable wcstats
[7/7] Linking CXX executable tests/textstats_tests
Executing workflow step 3 of 3: test preset "release"
100% tests passed out of 7
release
compile_commands.json is there for clangd
Both presets inherit CMAKE_EXPORT_COMPILE_COMMANDS from the hidden base preset, so editors get compile_commands.json in either build directory (Toolkit: VS Code, CLion & compile_commands.json).
A GitHub Actions job is now three lines of real work:
- uses: actions/checkout@v4
- name: Build and test
run: cmake --workflow --preset releaseChecklist for Part 2
-
CMakePresets.jsoncommitted; personal tweaks go in an untrackedCMakeUserPresets.json. - Tests are optional, on by default only at the top level.
- Unit tests and CLI tests are labelled and can run separately.
- The CLI tests use a fixture instead of relying on files left lying around.
- One workflow command builds and tests a release, exactly as CI does.
Next: Part 3: Package & Consume.
Test yourself
Why did ctest -R cli.counts also run cli.setup and cli.cleanup?
- -R matches all cli tests
- cli.counts requires the fixture
sample, which pulls in its setup and cleanup tests - Tests always run in pairs
- Because of the release preset
What does noTestsAction: error in the test preset protect against?
- Slow tests
- A misconfigured build where no tests were registered silently 'passing' in CI
- Flaky tests
- Missing labels