feat(list): add generic list implementation
All checks were successful
continuous-integration/drone/push Build is passing

This pull request adds a list implementation that can be used
in a generic way and adds everything that might be needed in
later implementation of other data structurs.

Reviewed-on: #1
PR #1
This commit is contained in:
Rick Barenthin 2022-07-26 22:45:21 +02:00
parent 16825ad6a5
commit 9e4c9eb0ea
16 changed files with 2396 additions and 7 deletions

View File

@ -38,7 +38,7 @@ name: tag
steps: steps:
- name: Build release - name: Build release
image: registry.riba-interactive.de/alpine-build:1 image: registry.riba-interactive.de/alpine-build:3
commands: commands:
- cmake -S. -Bcmake-build-ci -DCMAKE_BUILD_TYPE=Release - cmake -S. -Bcmake-build-ci -DCMAKE_BUILD_TYPE=Release
- cd cmake-build-ci - cd cmake-build-ci
@ -58,12 +58,12 @@ name: Build and Test
steps: steps:
- name: Build and run tests - name: Build and run tests
image: registry.riba-interactive.de/alpine-build:1 image: registry.riba-interactive.de/alpine-build:3
commands: commands:
- cmake -S. -Bcmake-build-ci -DCMAKE_BUILD_TYPE=Debug -DENABLE_TEST_COVERAGE=on - cmake -S. -Bcmake-build-ci -DCMAKE_BUILD_TYPE=Debug -DENABLE_TEST_COVERAGE=on
- cd cmake-build-ci - cd cmake-build-ci
- cmake --build . - cmake --build .
- ctest -T Test -T Coverage - make coverage
- name: Report test and coverage - name: Report test and coverage
image: alpine image: alpine

View File

@ -13,15 +13,30 @@ set(CMAKE_C_STANDARD 17)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
option(ENABLE_TEST_COVERAGE "Enable test coverage" OFF)
if (CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) if (CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME)
set_property(GLOBAL PROPERTY USE_FOLDERS ON) set_property(GLOBAL PROPERTY USE_FOLDERS ON)
include(CTest) include(CTest)
endif () endif ()
add_subdirectory(app) add_subdirectory(app)
add_subdirectory(library/list)
add_subdirectory(library/log) add_subdirectory(library/log)
if ((CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME OR MODERN_CMAKE_BUILD_TESTING) if ((CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME OR MODERN_CMAKE_BUILD_TESTING)
AND BUILD_TESTING) AND BUILD_TESTING)
add_subdirectory(tests) add_subdirectory(tests)
if (ENABLE_TEST_COVERAGE)
include(CodeCoverage)
setup_target_for_coverage_lcov(
NAME coverage
EXECUTABLE ${CMAKE_CTEST_COMMAND}
EXCLUDE "tests/*"
LCOV_ARGS --rc lcov_branch_coverage=1
GENHTML_ARGS --rc genhtml_branch_coverage=1
)
endif ()
endif () endif ()

View File

@ -1,7 +1,11 @@
FROM alpine:3.16.0 FROM alpine:3.16.0
RUN apk --no-cache add \ RUN echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories; \
apk --no-cache add \
bison \ bison \
build-base \ build-base \
cmake \ cmake \
flex flex \
git \
ncurses-dev\
lcov@testing

721
cmake/CodeCoverage.cmake Normal file
View File

@ -0,0 +1,721 @@
# Copyright (c) 2012 - 2017, Lars Bilke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# CHANGES:
#
# 2012-01-31, Lars Bilke
# - Enable Code Coverage
#
# 2013-09-17, Joakim Söderberg
# - Added support for Clang.
# - Some additional usage instructions.
#
# 2016-02-03, Lars Bilke
# - Refactored functions to use named parameters
#
# 2017-06-02, Lars Bilke
# - Merged with modified version from github.com/ufz/ogs
#
# 2019-05-06, Anatolii Kurotych
# - Remove unnecessary --coverage flag
#
# 2019-12-13, FeRD (Frank Dana)
# - Deprecate COVERAGE_LCOVR_EXCLUDES and COVERAGE_GCOVR_EXCLUDES lists in favor
# of tool-agnostic COVERAGE_EXCLUDES variable, or EXCLUDE setup arguments.
# - CMake 3.4+: All excludes can be specified relative to BASE_DIRECTORY
# - All setup functions: accept BASE_DIRECTORY, EXCLUDE list
# - Set lcov basedir with -b argument
# - Add automatic --demangle-cpp in lcovr, if 'c++filt' is available (can be
# overridden with NO_DEMANGLE option in setup_target_for_coverage_lcovr().)
# - Delete output dir, .info file on 'make clean'
# - Remove Python detection, since version mismatches will break gcovr
# - Minor cleanup (lowercase function names, update examples...)
#
# 2019-12-19, FeRD (Frank Dana)
# - Rename Lcov outputs, make filtered file canonical, fix cleanup for targets
#
# 2020-01-19, Bob Apthorpe
# - Added gfortran support
#
# 2020-02-17, FeRD (Frank Dana)
# - Make all add_custom_target()s VERBATIM to auto-escape wildcard characters
# in EXCLUDEs, and remove manual escaping from gcovr targets
#
# 2021-01-19, Robin Mueller
# - Add CODE_COVERAGE_VERBOSE option which will allow to print out commands which are run
# - Added the option for users to set the GCOVR_ADDITIONAL_ARGS variable to supply additional
# flags to the gcovr command
#
# 2020-05-04, Mihchael Davis
# - Add -fprofile-abs-path to make gcno files contain absolute paths
# - Fix BASE_DIRECTORY not working when defined
# - Change BYPRODUCT from folder to index.html to stop ninja from complaining about double defines
#
# 2021-05-10, Martin Stump
# - Check if the generator is multi-config before warning about non-Debug builds
#
# 2022-02-22, Marko Wehle
# - Change gcovr output from -o <filename> for --xml <filename> and --html <filename> output respectively.
# This will allow for Multiple Output Formats at the same time by making use of GCOVR_ADDITIONAL_ARGS, e.g. GCOVR_ADDITIONAL_ARGS "--txt".
#
# USAGE:
#
# 1. Copy this file into your cmake modules path.
#
# 2. Add the following line to your CMakeLists.txt (best inside an if-condition
# using a CMake option() to enable it just optionally):
# include(CodeCoverage)
#
# 3. Append necessary compiler flags for all supported source files:
# append_coverage_compiler_flags()
# Or for specific target:
# append_coverage_compiler_flags_to_target(YOUR_TARGET_NAME)
#
# 3.a (OPTIONAL) Set appropriate optimization flags, e.g. -O0, -O1 or -Og
#
# 4. If you need to exclude additional directories from the report, specify them
# using full paths in the COVERAGE_EXCLUDES variable before calling
# setup_target_for_coverage_*().
# Example:
# set(COVERAGE_EXCLUDES
# '${PROJECT_SOURCE_DIR}/src/dir1/*'
# '/path/to/my/src/dir2/*')
# Or, use the EXCLUDE argument to setup_target_for_coverage_*().
# Example:
# setup_target_for_coverage_lcov(
# NAME coverage
# EXECUTABLE testrunner
# EXCLUDE "${PROJECT_SOURCE_DIR}/src/dir1/*" "/path/to/my/src/dir2/*")
#
# 4.a NOTE: With CMake 3.4+, COVERAGE_EXCLUDES or EXCLUDE can also be set
# relative to the BASE_DIRECTORY (default: PROJECT_SOURCE_DIR)
# Example:
# set(COVERAGE_EXCLUDES "dir1/*")
# setup_target_for_coverage_gcovr_html(
# NAME coverage
# EXECUTABLE testrunner
# BASE_DIRECTORY "${PROJECT_SOURCE_DIR}/src"
# EXCLUDE "dir2/*")
#
# 5. Use the functions described below to create a custom make target which
# runs your test executable and produces a code coverage report.
#
# 6. Build a Debug build:
# cmake -DCMAKE_BUILD_TYPE=Debug ..
# make
# make my_coverage_target
#
include(CMakeParseArguments)
option(CODE_COVERAGE_VERBOSE "Verbose information" FALSE)
# Check prereqs
find_program( GCOV_PATH gcov )
find_program( LCOV_PATH NAMES lcov lcov.bat lcov.exe lcov.perl)
find_program( FASTCOV_PATH NAMES fastcov fastcov.py )
find_program( GENHTML_PATH NAMES genhtml genhtml.perl genhtml.bat )
find_program( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test)
find_program( CPPFILT_PATH NAMES c++filt )
if(NOT GCOV_PATH)
message(FATAL_ERROR "gcov not found! Aborting...")
endif() # NOT GCOV_PATH
get_property(LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)
list(GET LANGUAGES 0 LANG)
if("${CMAKE_${LANG}_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang")
if("${CMAKE_${LANG}_COMPILER_VERSION}" VERSION_LESS 3)
message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...")
endif()
elseif (CMAKE_${LANG}_COMPILER_ID STREQUAL "GNU")
# Do nothing; exit conditional without error if true
elseif(NOT CMAKE_COMPILER_IS_GNUCXX)
if("${CMAKE_Fortran_COMPILER_ID}" MATCHES "[Ff]lang")
# Do nothing; exit conditional without error if true
elseif("${CMAKE_Fortran_COMPILER_ID}" MATCHES "GNU")
# Do nothing; exit conditional without error if true
else()
message(FATAL_ERROR "Compiler is not GNU gcc! Aborting...")
endif()
endif()
set(COVERAGE_COMPILER_FLAGS "-g -fprofile-arcs -ftest-coverage"
CACHE INTERNAL "")
if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)")
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-fprofile-abs-path HAVE_fprofile_abs_path)
if(HAVE_fprofile_abs_path)
set(COVERAGE_COMPILER_FLAGS "${COVERAGE_COMPILER_FLAGS} -fprofile-abs-path")
endif()
endif()
set(CMAKE_Fortran_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the Fortran compiler during coverage builds."
FORCE )
set(CMAKE_CXX_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C++ compiler during coverage builds."
FORCE )
set(CMAKE_C_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C compiler during coverage builds."
FORCE )
set(CMAKE_EXE_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used for linking binaries during coverage builds."
FORCE )
set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used by the shared libraries linker during coverage builds."
FORCE )
mark_as_advanced(
CMAKE_Fortran_FLAGS_COVERAGE
CMAKE_CXX_FLAGS_COVERAGE
CMAKE_C_FLAGS_COVERAGE
CMAKE_EXE_LINKER_FLAGS_COVERAGE
CMAKE_SHARED_LINKER_FLAGS_COVERAGE )
get_property(GENERATOR_IS_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG))
message(WARNING "Code coverage results with an optimised (non-Debug) build may be misleading")
endif() # NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG)
if(CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
link_libraries(gcov)
endif()
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_lcov(
# NAME testrunner_coverage # New target name
# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES testrunner # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# NO_DEMANGLE # Don't demangle C++ symbols
# # even if c++filt is found
# )
function(setup_target_for_coverage_lcov)
set(options NO_DEMANGLE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES LCOV_ARGS GENHTML_ARGS)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT LCOV_PATH)
message(FATAL_ERROR "lcov not found! Aborting...")
endif() # NOT LCOV_PATH
if(NOT GENHTML_PATH)
message(FATAL_ERROR "genhtml not found! Aborting...")
endif() # NOT GENHTML_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(DEFINED Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(LCOV_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_LCOV_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND LCOV_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES LCOV_EXCLUDES)
# Conditional arguments
if(CPPFILT_PATH AND NOT ${Coverage_NO_DEMANGLE})
set(GENHTML_EXTRA_ARGS "--demangle-cpp")
endif()
# Setting up commands which will be run to generate coverage data.
# Cleanup lcov
set(LCOV_CLEAN_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -directory .
-b ${BASEDIR} --zerocounters
)
# Create baseline to make sure untouched files show up in the report
set(LCOV_BASELINE_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -c -i -d . -b
${BASEDIR} -o ${Coverage_NAME}.base
)
# Run tests
set(LCOV_EXEC_TESTS_CMD
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
)
# Capturing lcov counters and generating report
set(LCOV_CAPTURE_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --directory . -b
${BASEDIR} --capture --output-file ${Coverage_NAME}.capture
)
# add baseline counters
set(LCOV_BASELINE_COUNT_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -a ${Coverage_NAME}.base
-a ${Coverage_NAME}.capture --output-file ${Coverage_NAME}.total
)
# filter collected data to final coverage report
set(LCOV_FILTER_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --remove
${Coverage_NAME}.total ${LCOV_EXCLUDES} --output-file ${Coverage_NAME}.info
)
# Generate HTML output
set(LCOV_GEN_HTML_CMD
${GENHTML_PATH} ${GENHTML_EXTRA_ARGS} ${Coverage_GENHTML_ARGS} -o
${Coverage_NAME} ${Coverage_NAME}.info
)
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Executed command report")
message(STATUS "Command to clean up lcov: ")
string(REPLACE ";" " " LCOV_CLEAN_CMD_SPACED "${LCOV_CLEAN_CMD}")
message(STATUS "${LCOV_CLEAN_CMD_SPACED}")
message(STATUS "Command to create baseline: ")
string(REPLACE ";" " " LCOV_BASELINE_CMD_SPACED "${LCOV_BASELINE_CMD}")
message(STATUS "${LCOV_BASELINE_CMD_SPACED}")
message(STATUS "Command to run the tests: ")
string(REPLACE ";" " " LCOV_EXEC_TESTS_CMD_SPACED "${LCOV_EXEC_TESTS_CMD}")
message(STATUS "${LCOV_EXEC_TESTS_CMD_SPACED}")
message(STATUS "Command to capture counters and generate report: ")
string(REPLACE ";" " " LCOV_CAPTURE_CMD_SPACED "${LCOV_CAPTURE_CMD}")
message(STATUS "${LCOV_CAPTURE_CMD_SPACED}")
message(STATUS "Command to add baseline counters: ")
string(REPLACE ";" " " LCOV_BASELINE_COUNT_CMD_SPACED "${LCOV_BASELINE_COUNT_CMD}")
message(STATUS "${LCOV_BASELINE_COUNT_CMD_SPACED}")
message(STATUS "Command to filter collected data: ")
string(REPLACE ";" " " LCOV_FILTER_CMD_SPACED "${LCOV_FILTER_CMD}")
message(STATUS "${LCOV_FILTER_CMD_SPACED}")
message(STATUS "Command to generate lcov HTML output: ")
string(REPLACE ";" " " LCOV_GEN_HTML_CMD_SPACED "${LCOV_GEN_HTML_CMD}")
message(STATUS "${LCOV_GEN_HTML_CMD_SPACED}")
endif()
# Setup target
add_custom_target(${Coverage_NAME}
COMMAND ${LCOV_CLEAN_CMD}
COMMAND ${LCOV_BASELINE_CMD}
COMMAND ${LCOV_EXEC_TESTS_CMD}
COMMAND ${LCOV_CAPTURE_CMD}
COMMAND ${LCOV_BASELINE_COUNT_CMD}
COMMAND ${LCOV_FILTER_CMD}
COMMAND ${LCOV_GEN_HTML_CMD}
# Set output files as GENERATED (will be removed on 'make clean')
BYPRODUCTS
${Coverage_NAME}.base
${Coverage_NAME}.capture
${Coverage_NAME}.total
${Coverage_NAME}.info
${Coverage_NAME}/index.html
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
)
# Show where to find the lcov info report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Lcov code coverage info report saved in ${Coverage_NAME}.info."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
)
endfunction() # setup_target_for_coverage_lcov
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_gcovr_xml(
# NAME ctest_coverage # New target name
# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES executable_target # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# )
# The user can set the variable GCOVR_ADDITIONAL_ARGS to supply additional flags to the
# GCVOR command.
function(setup_target_for_coverage_gcovr_xml)
set(options NONE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT GCOVR_PATH)
message(FATAL_ERROR "gcovr not found! Aborting...")
endif() # NOT GCOVR_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(DEFINED Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(GCOVR_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
# Combine excludes to several -e arguments
set(GCOVR_EXCLUDE_ARGS "")
foreach(EXCLUDE ${GCOVR_EXCLUDES})
list(APPEND GCOVR_EXCLUDE_ARGS "-e")
list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
endforeach()
# Set up commands which will be run to generate coverage data
# Run tests
set(GCOVR_XML_EXEC_TESTS_CMD
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
)
# Running gcovr
set(GCOVR_XML_CMD
${GCOVR_PATH} --xml ${Coverage_NAME}.xml -r ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS}
${GCOVR_EXCLUDE_ARGS} --object-directory=${PROJECT_BINARY_DIR}
)
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Executed command report")
message(STATUS "Command to run tests: ")
string(REPLACE ";" " " GCOVR_XML_EXEC_TESTS_CMD_SPACED "${GCOVR_XML_EXEC_TESTS_CMD}")
message(STATUS "${GCOVR_XML_EXEC_TESTS_CMD_SPACED}")
message(STATUS "Command to generate gcovr XML coverage data: ")
string(REPLACE ";" " " GCOVR_XML_CMD_SPACED "${GCOVR_XML_CMD}")
message(STATUS "${GCOVR_XML_CMD_SPACED}")
endif()
add_custom_target(${Coverage_NAME}
COMMAND ${GCOVR_XML_EXEC_TESTS_CMD}
COMMAND ${GCOVR_XML_CMD}
BYPRODUCTS ${Coverage_NAME}.xml
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Running gcovr to produce Cobertura code coverage report."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Cobertura code coverage report saved in ${Coverage_NAME}.xml."
)
endfunction() # setup_target_for_coverage_gcovr_xml
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_gcovr_html(
# NAME ctest_coverage # New target name
# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES executable_target # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# )
# The user can set the variable GCOVR_ADDITIONAL_ARGS to supply additional flags to the
# GCVOR command.
function(setup_target_for_coverage_gcovr_html)
set(options NONE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT GCOVR_PATH)
message(FATAL_ERROR "gcovr not found! Aborting...")
endif() # NOT GCOVR_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(DEFINED Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(GCOVR_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
# Combine excludes to several -e arguments
set(GCOVR_EXCLUDE_ARGS "")
foreach(EXCLUDE ${GCOVR_EXCLUDES})
list(APPEND GCOVR_EXCLUDE_ARGS "-e")
list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
endforeach()
# Set up commands which will be run to generate coverage data
# Run tests
set(GCOVR_HTML_EXEC_TESTS_CMD
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
)
# Create folder
set(GCOVR_HTML_FOLDER_CMD
${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/${Coverage_NAME}
)
# Running gcovr
set(GCOVR_HTML_CMD
${GCOVR_PATH} --html ${Coverage_NAME}/index.html --html-details -r ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS}
${GCOVR_EXCLUDE_ARGS} --object-directory=${PROJECT_BINARY_DIR}
)
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Executed command report")
message(STATUS "Command to run tests: ")
string(REPLACE ";" " " GCOVR_HTML_EXEC_TESTS_CMD_SPACED "${GCOVR_HTML_EXEC_TESTS_CMD}")
message(STATUS "${GCOVR_HTML_EXEC_TESTS_CMD_SPACED}")
message(STATUS "Command to create a folder: ")
string(REPLACE ";" " " GCOVR_HTML_FOLDER_CMD_SPACED "${GCOVR_HTML_FOLDER_CMD}")
message(STATUS "${GCOVR_HTML_FOLDER_CMD_SPACED}")
message(STATUS "Command to generate gcovr HTML coverage data: ")
string(REPLACE ";" " " GCOVR_HTML_CMD_SPACED "${GCOVR_HTML_CMD}")
message(STATUS "${GCOVR_HTML_CMD_SPACED}")
endif()
add_custom_target(${Coverage_NAME}
COMMAND ${GCOVR_HTML_EXEC_TESTS_CMD}
COMMAND ${GCOVR_HTML_FOLDER_CMD}
COMMAND ${GCOVR_HTML_CMD}
BYPRODUCTS ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html # report directory
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Running gcovr to produce HTML code coverage report."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
)
endfunction() # setup_target_for_coverage_gcovr_html
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_fastcov(
# NAME testrunner_coverage # New target name
# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES testrunner # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/" "src/dir2/" # Patterns to exclude.
# NO_DEMANGLE # Don't demangle C++ symbols
# # even if c++filt is found
# SKIP_HTML # Don't create html report
# POST_CMD perl -i -pe s!${PROJECT_SOURCE_DIR}/!!g ctest_coverage.json # E.g. for stripping source dir from file paths
# )
function(setup_target_for_coverage_fastcov)
set(options NO_DEMANGLE SKIP_HTML)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES FASTCOV_ARGS GENHTML_ARGS POST_CMD)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT FASTCOV_PATH)
message(FATAL_ERROR "fastcov not found! Aborting...")
endif()
if(NOT Coverage_SKIP_HTML AND NOT GENHTML_PATH)
message(FATAL_ERROR "genhtml not found! Aborting...")
endif()
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (Patterns, not paths, for fastcov)
set(FASTCOV_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_FASTCOV_EXCLUDES})
list(APPEND FASTCOV_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES FASTCOV_EXCLUDES)
# Conditional arguments
if(CPPFILT_PATH AND NOT ${Coverage_NO_DEMANGLE})
set(GENHTML_EXTRA_ARGS "--demangle-cpp")
endif()
# Set up commands which will be run to generate coverage data
set(FASTCOV_EXEC_TESTS_CMD ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS})
set(FASTCOV_CAPTURE_CMD ${FASTCOV_PATH} ${Coverage_FASTCOV_ARGS} --gcov ${GCOV_PATH}
--search-directory ${BASEDIR}
--process-gcno
--output ${Coverage_NAME}.json
--exclude ${FASTCOV_EXCLUDES}
--exclude ${FASTCOV_EXCLUDES}
)
set(FASTCOV_CONVERT_CMD ${FASTCOV_PATH}
-C ${Coverage_NAME}.json --lcov --output ${Coverage_NAME}.info
)
if(Coverage_SKIP_HTML)
set(FASTCOV_HTML_CMD ";")
else()
set(FASTCOV_HTML_CMD ${GENHTML_PATH} ${GENHTML_EXTRA_ARGS} ${Coverage_GENHTML_ARGS}
-o ${Coverage_NAME} ${Coverage_NAME}.info
)
endif()
set(FASTCOV_POST_CMD ";")
if(Coverage_POST_CMD)
set(FASTCOV_POST_CMD ${Coverage_POST_CMD})
endif()
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Code coverage commands for target ${Coverage_NAME} (fastcov):")
message(" Running tests:")
string(REPLACE ";" " " FASTCOV_EXEC_TESTS_CMD_SPACED "${FASTCOV_EXEC_TESTS_CMD}")
message(" ${FASTCOV_EXEC_TESTS_CMD_SPACED}")
message(" Capturing fastcov counters and generating report:")
string(REPLACE ";" " " FASTCOV_CAPTURE_CMD_SPACED "${FASTCOV_CAPTURE_CMD}")
message(" ${FASTCOV_CAPTURE_CMD_SPACED}")
message(" Converting fastcov .json to lcov .info:")
string(REPLACE ";" " " FASTCOV_CONVERT_CMD_SPACED "${FASTCOV_CONVERT_CMD}")
message(" ${FASTCOV_CONVERT_CMD_SPACED}")
if(NOT Coverage_SKIP_HTML)
message(" Generating HTML report: ")
string(REPLACE ";" " " FASTCOV_HTML_CMD_SPACED "${FASTCOV_HTML_CMD}")
message(" ${FASTCOV_HTML_CMD_SPACED}")
endif()
if(Coverage_POST_CMD)
message(" Running post command: ")
string(REPLACE ";" " " FASTCOV_POST_CMD_SPACED "${FASTCOV_POST_CMD}")
message(" ${FASTCOV_POST_CMD_SPACED}")
endif()
endif()
# Setup target
add_custom_target(${Coverage_NAME}
# Cleanup fastcov
COMMAND ${FASTCOV_PATH} ${Coverage_FASTCOV_ARGS} --gcov ${GCOV_PATH}
--search-directory ${BASEDIR}
--zerocounters
COMMAND ${FASTCOV_EXEC_TESTS_CMD}
COMMAND ${FASTCOV_CAPTURE_CMD}
COMMAND ${FASTCOV_CONVERT_CMD}
COMMAND ${FASTCOV_HTML_CMD}
COMMAND ${FASTCOV_POST_CMD}
# Set output files as GENERATED (will be removed on 'make clean')
BYPRODUCTS
${Coverage_NAME}.info
${Coverage_NAME}.json
${Coverage_NAME}/index.html # report directory
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Resetting code coverage counters to zero. Processing code coverage counters and generating report."
)
set(INFO_MSG "fastcov code coverage info report saved in ${Coverage_NAME}.info and ${Coverage_NAME}.json.")
if(NOT Coverage_SKIP_HTML)
string(APPEND INFO_MSG " Open ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html in your browser to view the coverage report.")
endif()
# Show where to find the fastcov info report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E echo ${INFO_MSG}
)
endfunction() # setup_target_for_coverage_fastcov
function(append_coverage_compiler_flags)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
message(STATUS "Appending code coverage compiler flags: ${COVERAGE_COMPILER_FLAGS}")
endfunction() # append_coverage_compiler_flags
# Setup coverage for specific library
function(append_coverage_compiler_flags_to_target name)
target_compile_options(${name}
PRIVATE ${COVERAGE_COMPILER_FLAGS})
endfunction()

View File

@ -0,0 +1,22 @@
cmake_minimum_required(VERSION 3.21 FATAL_ERROR)
include("project-meta-info.in")
project(waitui-list
VERSION ${project_version}
DESCRIPTION ${project_description}
HOMEPAGE_URL ${project_homepage}
LANGUAGES C)
add_library(list OBJECT)
target_sources(list
PRIVATE
"src/list.c"
PUBLIC
"include/waitui/list.h"
"include/waitui/list_generic.h"
"include/waitui/list_generic_impl.h"
)
target_include_directories(list PUBLIC "include")

View File

@ -0,0 +1,130 @@
/**
* @file list.h
* @author rick
* @date 22.07.20
* @brief File for the List implementation
*/
#ifndef WAITUI_LIST_H
#define WAITUI_LIST_H
#include <stdbool.h>
// -----------------------------------------------------------------------------
// Public types
// -----------------------------------------------------------------------------
/**
* @brief Type representing a List node
*/
typedef struct waitui_list_node waitui_list_node;
/**
* @brief Type for element destroy function
*/
typedef void (*waitui_list_element_destroy)(void **element);
/**
* @brief Type representing a List
*/
typedef struct waitui_list waitui_list;
/**
* @brief Type representing a List iterator
*/
typedef struct waitui_list_iter waitui_list_iter;
// -----------------------------------------------------------------------------
// Public functions
// -----------------------------------------------------------------------------
/**
* @brief Create a List
* @param[in] elementDestroyCallback Function to call for element destruction
* @return A pointer to waitui_list or NULL if memory allocation failed
*/
extern waitui_list *
waitui_list_new(waitui_list_element_destroy elementDestroyCallback);
/**
* @brief Destroy a List
* @param[in,out] this The List to destroy
* @note This will free call for every element the elementDestroyCallback
*/
extern void waitui_list_destroy(waitui_list **this);
/**
* @brief Add the element to the end of the List
* @param[in,out] this The List to add the element at the end
* @param[in] element The element to add
* @note This function does steel the pointer to the element
* @retval 1 Ok
* @retval 0 Memory allocation failed
*/
extern int waitui_list_push(waitui_list *this, void *element);
/**
* @brief Remove the element from the end of the List and return it
* @param[in,out] this The List to remove the element from
* @note The caller has to destroy element on its own
* @return The element or NULL if waitui_list is empty
*/
extern void *waitui_list_pop(waitui_list *this);
/**
* @brief Add the element to the beginning of the List
* @param[in,out] this The List to add the element at the beginning
* @param[in] element The element to add
* @note This function does steel the pointer to the element
* @retval 1 Ok
* @retval 0 Memory allocation failed
*/
extern int waitui_list_unshift(waitui_list *this, void *element);
/**
* @brief Remove the element from the beginning of the List and return it
* @param[in,out] this The List to remove the element from
* @note The caller has to destroy element on its own
* @return The element or NULL if waitui_list is empty
*/
extern void *waitui_list_shift(waitui_list *this);
/**
* @brief Return the element from the end of the List, without removing it
* @param[in] this The List to get the last element from
* @warning The caller has not to destroy element on its own
* @return The element or NULL if waitui_list is empty
*/
extern void *waitui_list_peek(waitui_list *this);
/**
* @brief Return the iterator to iterate over the List
* @param[in] this The List to get the iterator for
* @return A pointer to waitui_list_iter or NULL if memory allocation failed
*/
extern waitui_list_iter *waitui_list_getIterator(waitui_list *this);
/**
* @brief Return true if the List iterator has a next element
* @param[in] this The List iterator to test for next element available
* @retval true If the iterator has a next element available
* @retval false If the iterator has no next element available
*/
extern bool waitui_list_iter_hasNext(waitui_list_iter *this);
/**
* @brief Return the next element from the List iterator
* @param[in] this The List iterator to get the next element
* @return The element or NULL if no more elements are available
*/
extern void *waitui_list_iter_next(waitui_list_iter *this);
/**
* @brief Destroy a List iterator
* @param[in,out] this The List iterator to destroy
*/
extern void waitui_list_iter_destroy(waitui_list_iter **this);
#endif//WAITUI_LIST_H

View File

@ -0,0 +1,78 @@
/**
* @file list_generic.h
* @author rick
* @date 26.07.22
* @brief File for the generic List implementation
*/
#ifndef WAITUI_LIST_GENERIC_H
#define WAITUI_LIST_GENERIC_H
// -----------------------------------------------------------------------------
// Public defines
// -----------------------------------------------------------------------------
#define INTERFACE_LIST_TYPEDEF(type) \
typedef waitui_list type##_list; \
typedef waitui_list_iter type##_list_iter
#define INTERFACE_LIST_NEW(type) extern type##_list *type##_list_new()
#define INTERFACE_LIST_DESTROY(type) \
extern void type##_list_destroy(type##_list **this)
#define INTERFACE_LIST_PUSH(type) \
extern int type##_list_push(type##_list *this, type *type##Element)
#define INTERFACE_LIST_POP(type) extern type *type##_list_pop(type##_list *this)
#define INTERFACE_LIST_UNSHIFT(type) \
extern int type##_list_unshift(type##_list *this, type *type##Element)
#define INTERFACE_LIST_SHIFT(type) \
extern type *type##_list_shift(type##_list *this)
#define INTERFACE_LIST_PEEK(type) \
extern type *type##_list_peek(type##_list *this)
#define INTERFACE_LIST_GET_ITERATOR(type) \
extern type##_list_iter *type##_list_getIterator(type##_list *this)
#define INTERFACE_LIST_ITER_HAS_NEXT(type) \
extern bool type##_list_iter_hasNext(type##_list_iter *this)
#define INTERFACE_LIST_ITER_NEXT(type) \
extern type *type##_list_iter_next(type##_list_iter *this)
#define INTERFACE_LIST_ITER_DESTROY(type) \
extern void type##_list_iter_destroy(type##_list_iter **this)
/**
* @brief Define for quickly created list implementations for a value type
* @param[in] kind Whether to create interface list definition
* or actual implementation
* @param[in] type For what type to create the list
*/
#define CREATE_LIST_TYPE(kind, type) \
kind##_LIST_TYPEDEF(type); \
kind##_LIST_NEW(type); \
kind##_LIST_DESTROY(type); \
kind##_LIST_PUSH(type); \
kind##_LIST_POP(type); \
kind##_LIST_UNSHIFT(type); \
kind##_LIST_SHIFT(type); \
kind##_LIST_PEEK(type); \
kind##_LIST_GET_ITERATOR(type); \
kind##_LIST_ITER_HAS_NEXT(type); \
kind##_LIST_ITER_NEXT(type); \
kind##_LIST_ITER_DESTROY(type);
#endif//WAITUI_LIST_GENERIC_H

View File

@ -0,0 +1,79 @@
/**
* @file list_generic_impl.h
* @author rick
* @date 26.07.22
* @brief File for the generic List implementation
*/
#ifndef WAITUI_LIST_GENERIC_IMPL_H
#define WAITUI_LIST_GENERIC_IMPL_H
#include "waitui/list_generic.h"
#include "waitui/list.h"
// -----------------------------------------------------------------------------
// Public defines
// -----------------------------------------------------------------------------
#define IMPLEMENTATION_LIST_TYPEDEF(type)
#define IMPLEMENTATION_LIST_NEW(type) \
type##_list *type##_list_new() { \
return (type##_list *) waitui_list_new( \
(waitui_list_element_destroy) type##_destroy); \
}
#define IMPLEMENTATION_LIST_DESTROY(type) \
void type##_list_destroy(type##_list **this) { \
waitui_list_destroy((waitui_list **) this); \
}
#define IMPLEMENTATION_LIST_PUSH(type) \
int type##_list_push(type##_list *this, type *type##Element) { \
return waitui_list_push((waitui_list *) this, (void *) type##Element); \
}
#define IMPLEMENTATION_LIST_POP(type) \
type *type##_list_pop(type##_list *this) { \
return (type *) waitui_list_pop((waitui_list *) this); \
}
#define IMPLEMENTATION_LIST_UNSHIFT(type) \
int type##_list_unshift(type##_list *this, type *type##Element) { \
return waitui_list_unshift((waitui_list *) this, \
(void *) type##Element); \
}
#define IMPLEMENTATION_LIST_SHIFT(type) \
type *type##_list_shift(type##_list *this) { \
return (type *) waitui_list_shift((waitui_list *) this); \
}
#define IMPLEMENTATION_LIST_PEEK(type) \
type *type##_list_peek(type##_list *this) { \
return (type *) waitui_list_peek((waitui_list *) this); \
}
#define IMPLEMENTATION_LIST_GET_ITERATOR(type) \
type##_list_iter *type##_list_getIterator(type##_list *this) { \
return (type##_list_iter *) waitui_list_getIterator( \
(waitui_list *) this); \
}
#define IMPLEMENTATION_LIST_ITER_HAS_NEXT(type) \
bool type##_list_iter_hasNext(type##_list_iter *this) { \
return waitui_list_iter_hasNext((waitui_list_iter *) this); \
}
#define IMPLEMENTATION_LIST_ITER_NEXT(type) \
type *type##_list_iter_next(type##_list_iter *this) { \
return (type *) waitui_list_iter_next((waitui_list_iter *) this); \
}
#define IMPLEMENTATION_LIST_ITER_DESTROY(type) \
void type##_list_iter_destroy(type##_list_iter **this) { \
waitui_list_iter_destroy((waitui_list_iter **) this); \
}
#endif//WAITUI_LIST_GENERIC_IMPL_H

View File

@ -0,0 +1,3 @@
set(project_version 0.0.1)
set(project_description "waitui list library")
set(project_homepage "http://example.com")

219
library/list/src/list.c Normal file
View File

@ -0,0 +1,219 @@
/**
* @file list.c
* @author rick
* @date 22.07.20
* @brief File for the List implementation
*/
#include "waitui/list.h"
#include <stdlib.h>
// -----------------------------------------------------------------------------
// Local types
// -----------------------------------------------------------------------------
/**
* @brief Struct representing a List node
*/
struct waitui_list_node {
void *element;
waitui_list_node *next;
waitui_list_node *prev;
};
/**
* @brief Struct representing a List
*/
struct waitui_list {
waitui_list_node *head;
waitui_list_node *tail;
waitui_list_element_destroy elementDestroyCallback;
unsigned long long length;
};
/**
* @brief Struct representing a List iterator
*/
struct waitui_list_iter {
waitui_list_node *node;
};
// -----------------------------------------------------------------------------
// Local functions
// -----------------------------------------------------------------------------
/**
* @brief Create a List iterator
* @param[in] node The node to use as a start for the iterator
* @return A pointer to waitui_list_iter or NULL if memory allocation failed
*/
static waitui_list_iter *waitui_list_iter_new(waitui_list_node *node) {
waitui_list_iter *this = NULL;
this = calloc(1, sizeof(*this));
if (!this) { return NULL; }
this->node = node;
return this;
}
// -----------------------------------------------------------------------------
// Public functions
// -----------------------------------------------------------------------------
waitui_list *
waitui_list_new(waitui_list_element_destroy elementDestroyCallback) {
waitui_list *this = NULL;
this = calloc(1, sizeof(*this));
if (!this) { return NULL; }
this->elementDestroyCallback = elementDestroyCallback;
return this;
}
void waitui_list_destroy(waitui_list **this) {
if (!this || !(*this)) { return; }
while ((*this)->head) {
waitui_list_node *temp = (*this)->head;
(*this)->head = (*this)->head->next;
if ((*this)->elementDestroyCallback) {
(*this)->elementDestroyCallback(&temp->element);
}
free(temp);
}
free(*this);
*this = NULL;
}
int waitui_list_push(waitui_list *this, void *element) {
waitui_list_node *node = NULL;
if (!this || !element) { return 0; }
node = calloc(1, sizeof(*node));
if (!node) { return 0; }
node->element = element;
if (this->tail == NULL) {
this->head = this->tail = node;
} else {
node->prev = this->tail;
this->tail->next = node;
this->tail = node;
}
this->length++;
return 1;
}
void *waitui_list_pop(waitui_list *this) {
waitui_list_node *node = NULL;
void *element = NULL;
if (!this || this->length == 0) { return NULL; }
node = this->tail;
element = node->element;
this->tail = this->tail->prev;
this->length--;
if (this->tail != NULL) {
this->tail->next = NULL;
} else {
this->head = NULL;
}
free(node);
return element;
}
int waitui_list_unshift(waitui_list *this, void *element) {
waitui_list_node *node = NULL;
if (!this || !element) { return 0; }
node = calloc(1, sizeof(*node));
if (!node) { return 0; }
node->element = element;
if (this->head == NULL) {
this->head = this->tail = node;
} else {
node->next = this->head;
this->head->prev = node;
this->head = node;
}
this->length++;
return 1;
}
void *waitui_list_shift(waitui_list *this) {
waitui_list_node *node = NULL;
void *element = NULL;
if (!this || this->length == 0) { return NULL; }
node = this->head;
element = node->element;
this->head = this->head->next;
this->length--;
if (this->head != NULL) {
this->head->prev = NULL;
} else {
this->tail = NULL;
}
free(node);
return element;
}
void *waitui_list_peek(waitui_list *this) {
if (!this || this->length == 0) { return NULL; }
return this->tail->element;
}
waitui_list_iter *waitui_list_getIterator(waitui_list *this) {
if (!this) { return NULL; }
return waitui_list_iter_new(this->head);
}
bool waitui_list_iter_hasNext(waitui_list_iter *this) {
if (!this) { return false; }
return this->node != NULL;
}
void *waitui_list_iter_next(waitui_list_iter *this) {
waitui_list_node *node = NULL;
if (!this) { return NULL; }
node = this->node;
this->node = this->node->next;
return node->element;
}
void waitui_list_iter_destroy(waitui_list_iter **this) {
if (!this || !(*this)) { return; }
free(*this);
*this = NULL;
}

View File

@ -1,3 +1,13 @@
include(../cmake/FetchCMocka.cmake) cmake_minimum_required(VERSION 3.21 FATAL_ERROR)
#add_subdirectory() include("project-meta-info.in")
project(waitui-tests
VERSION ${project_version}
DESCRIPTION ${project_description}
HOMEPAGE_URL ${project_homepage}
LANGUAGES C)
#option(ENABLE_TEST_COVERAGE "Enable test coverage" ON)
add_subdirectory(library/list)

164
tests/bdd-for-c-ext.h Normal file
View File

@ -0,0 +1,164 @@
//
// Created by Rick Barenthin on 09.02.22.
//
#ifndef WAITUI_BDD_FOR_C_EXT_H
#define WAITUI_BDD_FOR_C_EXT_H
#include "bdd-for-c.h"
#define __BDD_EXT_1ST_PARAM_FMT__ "'%s'"
#define __BDD_EXT_OTHER_PARAM_FMT__ ", '%s'"
/**
* Create the format based on the count passed.
* @param num The number of format string parameters
* @return
*/
static inline char *__bdd_ext_build_format__(int num) {
size_t length = (sizeof(__BDD_EXT_1ST_PARAM_FMT__) - 1) +
(num - 1) * (sizeof(__BDD_EXT_OTHER_PARAM_FMT__) - 1) + 1;
char *fmt = calloc(length, sizeof(*fmt));
if (!fmt) {
perror("calloc(__bdd_ext_build_format__)");
abort();
}
for (int i = 0; i < num; i++) {
if (i != 0) {
strcat(fmt, __BDD_EXT_OTHER_PARAM_FMT__);
} else {
strcat(fmt, __BDD_EXT_1ST_PARAM_FMT__);
}
}
return fmt;
}
/**
* Create a format string from a test description and format parameters.
*
* @param description The description of the test case
* @param num The number of format string parameters
* @param ... The format string parameters a comma
* separated arguments
* @return The created format string
*/
static inline char *__bdd_ext_format_string_params__(const char *description,
int num, ...) {
va_list args;
va_list copy;
int length = 1;
int written = 0;
char *fmt_string = NULL;
char *fmt = __bdd_ext_build_format__(num);
va_start(args, num);
va_copy(copy, args);
length += snprintf(NULL, 0, "%s [", description);
length += vsnprintf(NULL, 0, fmt, copy);
length += snprintf(NULL, 0, "]");
fmt_string = calloc(length, sizeof(*fmt_string));
if (!fmt_string) {
perror("calloc(__bdd_ext_format_string_params__)");
abort();
}
va_end(copy);
written += snprintf(fmt_string, length, "%s [", description);
written += vsnprintf(fmt_string + written, length - written, fmt, args);
written += snprintf(fmt_string + written, length - written, "]");
va_end(args);
free(fmt);
return fmt_string;
}
/**
* Create an array of `#test_param` structs.
*
* @note This macro must be used for passing test parameters to `for_it()`.
* @example: test_params({"input", "expected"}, {"input1", "expected1"})
*/
#define test_params(...) \
{ __VA_ARGS__ }
/**
* Define arguments for a format string as one macro argument.
*
* @note This macro must be used for passing test parameters to `for_it()`.
* @example: format_args(STR_FMT(&string), STR_FMT(&string1));
*/
#define format_args(...) __VA_ARGS__
/**
* Define arguments for a format string as one macro argument.
*
* The first argument must be the number of format string parameters.
*
* @example: params_format(1, "%s", "%d");
*/
#define params_format(...) __VA_ARGS__
/**
* Create a parametrized test case.
*
* Each test parameter results in an isolated test case which is
* executed independently and has its own output showing the test
* description followed by the given test parameters.
*
* @note: The given test parameters can be accessed by `#test_param`.
* @note: You must call `for_it_end()` after the test code to free
* allocated memory.
*
* @example: for_it("returns 1 and sets claim on existing claim",
* params_format(2, "%s", "%d"),
* format_args(test_param.input, test_param.expected),
* { char *input; int expected; },
* test_params(
* {"test input 1", 0},
* {"test input 2", 1},
* {"test input 4", 2},
* {"test input 5", 3}
* )
* )
*
* @param description: The description of the test
* @param params_format: A format string for printing the parameters
* of a test. Use `params_format()` macro for
* format creation.
* @param format_args: The arguments for the parameter format. Use
* `format_args()` macro for arguments creation.
* @param param_struct_body: The struct to be created holding the test
* parameters.
* @param params: The test parameters to be used
*/
#define for_it(description, params_format, format_args, param_struct_body, \
params) \
do { \
struct __bdd_ext_test_param__ param_struct_body \
__bdd_ext_test_params__[] = params; \
int __bdd_ext_input_size__ = sizeof(__bdd_ext_test_params__) / \
sizeof(__bdd_ext_test_params__[0]); \
for (int __bdd_ext_i__ = 0; __bdd_ext_i__ < __bdd_ext_input_size__; \
__bdd_ext_i__++) { \
struct __bdd_ext_test_param__ test_param = \
__bdd_ext_test_params__[__bdd_ext_i__]; \
char *__bdd_ext_param_format_string__ = \
__bdd_ext_format_string_params__(description, \
params_format); \
it(__bdd_ext_param_format_string__, format_args) {
/**
* End a parametrized test and free all resources allocated in #for_it.
*/
#define for_it_end() \
} \
free(__bdd_ext_param_format_string__); \
} \
} \
while (0)
#endif//WAITUI_BDD_FOR_C_EXT_H

673
tests/bdd-for-c.h Normal file
View File

@ -0,0 +1,673 @@
/*!
The MIT License (MIT)
Copyright (c) 2016 Dmitriy Kubyshkin <dmitriy@kubyshkin.name>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef BDD_FOR_C_H
#define BDD_FOR_C_H
#ifdef _WIN32
#include <stdio.h>
#include <Windows.h>
#include <io.h>
#define __BDD_IS_ATTY__() _isatty(_fileno(stdout))
#else
#ifndef _POSIX_C_SOURCE
// This definition is required for `fileno` to be defined
#define _POSIX_C_SOURCE 200809
#endif
#include <stdio.h>
#include <unistd.h>
#include <term.h>
#define __BDD_IS_ATTY__() isatty(fileno(stdout))
#endif
#include <stddef.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4996) // _CRT_SECURE_NO_WARNINGS
#endif
#ifndef BDD_USE_COLOR
#define BDD_USE_COLOR 1
#endif
#ifndef BDD_USE_TAP
#define BDD_USE_TAP 0
#endif
#define __BDD_COLOR_RESET__ "\x1B[0m"
#define __BDD_COLOR_RED__ "\x1B[31m"
#define __BDD_COLOR_GREEN__ "\x1B[32m"
#define __BDD_COLOR_YELLOW__ "\x1B[33m"
#define __BDD_COLOR_BOLD__ "\x1B[1m" // Bold White
#define __BDD_COLOR_MAGENTA__ "\x1B[35m"
typedef struct __bdd_array__ {
void **values;
size_t capacity;
size_t size;
} __bdd_array__;
__bdd_array__ *__bdd_array_create__() {
__bdd_array__ *arr = malloc(sizeof(__bdd_array__));
if (!arr) {
perror("malloc(array)");
abort();
}
arr->capacity = 4;
arr->size = 0;
arr->values = calloc(arr->capacity, sizeof(void *));
return arr;
}
void *__bdd_array_push__(__bdd_array__ *arr, void *item) {
if (arr->size == arr->capacity) {
arr->capacity *= 2;
void *v = realloc(arr->values, sizeof(void*) * arr->capacity);
if (!v) {
perror("realloc(array)");
abort();
}
arr->values = v;
}
arr->values[arr->size++] = item;
return item;
}
void *__bdd_array_last__(__bdd_array__ *arr) {
if (arr->size == 0) {
return NULL;
}
return arr->values[arr->size - 1];
}
void *__bdd_array_pop__(__bdd_array__ *arr) {
if (arr->size == 0) {
return NULL;
}
void *result = arr->values[arr->size - 1];
--arr->size;
return result;
}
void __bdd_array_free__(__bdd_array__ *arr) {
free(arr->values);
free(arr);
}
typedef enum __bdd_node_type__ {
__BDD_NODE_GROUP__ = 1,
__BDD_NODE_TEST__ = 2,
__BDD_NODE_INTERIM__ = 3
} __bdd_node_type__;
typedef enum __bdd_node_flags__ {
__bdd_node_flags_none__ = 0,
__bdd_node_flags_focus__ = 1 << 0,
__bdd_node_flags_skip__ = 1 << 1,
} __bdd_node_flags__;
typedef struct __bdd_test_step__ {
size_t level;
int id;
char *name;
__bdd_node_type__ type;
__bdd_node_flags__ flags;
} __bdd_test_step__;
typedef struct __bdd_node__ {
int id;
int next_node_id;
char *name;
__bdd_node_flags__ flags;
__bdd_node_type__ type;
__bdd_array__ *list_before;
__bdd_array__ *list_after;
__bdd_array__ *list_before_each;
__bdd_array__ *list_after_each;
__bdd_array__ *list_children;
} __bdd_node__;
enum __bdd_run_type__ {
__BDD_INIT_RUN__ = 1,
__BDD_TEST_RUN__ = 2
};
typedef struct __bdd_config_type__ {
enum __bdd_run_type__ run;
int id;
size_t test_index;
size_t test_tap_index;
size_t failed_test_count;
__bdd_test_step__ *current_test;
__bdd_array__ *node_stack;
__bdd_array__ *nodes;
char *error;
char *location;
bool use_color;
bool use_tap;
bool has_focus_nodes;
} __bdd_config_type__;
__bdd_test_step__ *__bdd_test_step_create__(size_t level, __bdd_node__ *node) {
__bdd_test_step__ *step = malloc(sizeof(__bdd_test_step__));
if (!step) {
perror("malloc(step)");
abort();
}
step->id = node->id;
step->level = level;
step->type = node->type;
step->name = node->name;
step->flags = node->flags;
return step;
}
__bdd_node__ *__bdd_node_create__(int id, char *name, __bdd_node_type__ type, __bdd_node_flags__ flags) {
__bdd_node__ *n = malloc(sizeof(__bdd_node__));
if (!n) {
perror("malloc(node)");
abort();
}
n->id = id;
n->next_node_id = id + 1;
n->name = name; // node takes ownership of name
n->type = type;
n->flags = flags;
n->list_before = __bdd_array_create__();
n->list_after = __bdd_array_create__();
n->list_before_each = __bdd_array_create__();
n->list_after_each = __bdd_array_create__();
n->list_children = __bdd_array_create__();
return n;
}
bool __bdd_node_is_leaf__(__bdd_node__ *node) {
return node->list_children->size == 0;
}
void __bdd_node_flatten_internal__(
__bdd_config_type__ *config,
size_t level,
__bdd_node__ *node,
__bdd_array__ *steps,
__bdd_array__ *before_each_lists,
__bdd_array__ *after_each_lists
) {
if (__bdd_node_is_leaf__(node)) {
if (config->has_focus_nodes && !(node->flags & __bdd_node_flags_focus__)) {
return;
}
for (size_t listIndex = 0; listIndex < before_each_lists->size; ++listIndex) {
__bdd_array__ *list = before_each_lists->values[listIndex];
for (size_t i = 0; i < list->size; ++i) {
__bdd_array_push__(steps, __bdd_test_step_create__(level, list->values[i]));
}
}
__bdd_array_push__(steps, __bdd_test_step_create__(level, node));
for (size_t listIndex = 0; listIndex < after_each_lists->size; ++listIndex) {
size_t reverseListIndex = after_each_lists->size - listIndex - 1;
__bdd_array__ *list = after_each_lists->values[reverseListIndex];
for (size_t i = 0; i < list->size; ++i) {
__bdd_array_push__(steps, __bdd_test_step_create__(level, list->values[i]));
}
}
return;
}
__bdd_array_push__(steps, __bdd_test_step_create__(level, node));
for (size_t i = 0; i < node->list_before->size; ++i) {
__bdd_array_push__(steps, __bdd_test_step_create__(level + 1, node->list_before->values[i]));
}
__bdd_array_push__(before_each_lists, node->list_before_each);
__bdd_array_push__(after_each_lists, node->list_after_each);
for (size_t i = 0; i < node->list_children->size; ++i) {
__bdd_node_flatten_internal__(
config, level + 1, node->list_children->values[i], steps, before_each_lists, after_each_lists
);
}
__bdd_array_pop__(before_each_lists);
__bdd_array_pop__(after_each_lists);
for (size_t i = 0; i < node->list_after->size; ++i) {
__bdd_array_push__(steps, __bdd_test_step_create__(level + 1, node->list_after->values[i]));
}
}
__bdd_array__ *__bdd_node_flatten__(__bdd_config_type__ *config, __bdd_node__ *node, __bdd_array__ *steps) {
if (node == NULL) {
return steps;
}
__bdd_array__ *before_each_lists = __bdd_array_create__();
__bdd_array__ *after_each_lists = __bdd_array_create__();
__bdd_node_flatten_internal__(config, 0, node, steps, before_each_lists, after_each_lists);
__bdd_array_free__(before_each_lists);
__bdd_array_free__(after_each_lists);
return steps;
}
void __bdd_node_free__(__bdd_node__ *n) {
free(n->name);
__bdd_array_free__(n->list_before);
__bdd_array_free__(n->list_after);
__bdd_array_free__(n->list_before_each);
__bdd_array_free__(n->list_after_each);
__bdd_array_free__(n->list_children);
free(n);
}
char *__bdd_spec_name__;
void __bdd_test_main__(__bdd_config_type__ *__bdd_config__);
char *__bdd_vformat__(const char *format, va_list va);
void __bdd_indent__(FILE *fp, size_t level) {
for (size_t i = 0; i < level; ++i) {
fprintf(fp, " ");
}
}
bool __bdd_enter_node__(__bdd_node_flags__ node_flags, __bdd_config_type__ *config, __bdd_node_type__ type, ptrdiff_t list_offset, char *fmt, ...) {
va_list va;
va_start(va, fmt);
char *name = __bdd_vformat__(fmt, va);
va_end(va);
if (config->run == __BDD_INIT_RUN__) {
__bdd_node__ *top = __bdd_array_last__(config->node_stack);
__bdd_array__ *list = *(__bdd_array__ **)((unsigned char *)top + list_offset);
int id = config->id++;
__bdd_node__ *node = __bdd_node_create__(id, name, type, node_flags);
if (node_flags & __bdd_node_flags_focus__) {
// Propagate focus to group nodes up the tree to print inly them
top->flags |= node_flags & __bdd_node_flags_focus__;
config->has_focus_nodes = true;
}
__bdd_array_push__(list, node);
__bdd_array_push__(config->nodes, node);
if (type == __BDD_NODE_GROUP__) {
__bdd_array_push__(config->node_stack, node);
return true;
}
return false;
}
if (config->id >= (int)config->nodes->size) {
fprintf(stderr, "non-deterministic spec\n");
abort();
}
__bdd_node__ *node = config->nodes->values[config->id];
if (node->type != type || strcmp(node->name, name) != 0) {
fprintf(stderr, "non-deterministic spec\n");
abort();
}
free(name);
__bdd_test_step__ *step = config->current_test;
bool should_enter = step->id >= node->id && step->id < node->next_node_id;
if (should_enter) {
__bdd_array_push__(config->node_stack, node);
config->id++;
} else {
config->id = node->next_node_id;
}
#if defined(BDD_PRINT_TRACE)
const char *color = config->use_color ? __BDD_COLOR_MAGENTA__ : "";
fprintf(stderr, "%s% 3d ", color, step->id);
__bdd_indent__(stderr, config->node_stack->size - 1 - (int)should_enter);
const char *reset = config->use_color ? __BDD_COLOR_RESET__ : "";
fprintf(stderr,
"%s [%d, %d) %s%s\n",
should_enter ? ">" : "|",
node->id,
node->next_node_id,
node->name,
reset);
#endif
return should_enter;
}
void __bdd_exit_node__(__bdd_config_type__ *config) {
__bdd_node__ *top = __bdd_array_pop__(config->node_stack);
if (config->run == __BDD_INIT_RUN__) {
top->next_node_id = config->id;
}
}
void __bdd_run__(__bdd_config_type__ *config) {
__bdd_test_step__ *step = config->current_test;
if (step->type == __BDD_NODE_GROUP__ && !config->use_tap) {
if (config->has_focus_nodes && !(step->flags & __bdd_node_flags_focus__)) {
return;
}
__bdd_indent__(stdout, step->level);
printf(
"%s%s%s\n",
config->use_color ? __BDD_COLOR_BOLD__ : "",
step->name,
config->use_color ? __BDD_COLOR_RESET__ : ""
);
return;
}
bool skipped = false;
if (step->type == __BDD_NODE_TEST__) {
if (config->has_focus_nodes && !(step->flags & __bdd_node_flags_focus__)) {
skipped = true;
} else if (step->flags & __bdd_node_flags_skip__) {
skipped = true;
}
++config->test_tap_index;
// Print the step name before running the test so it is visible
// even if the test itself crashes.
if ((!skipped || !config->has_focus_nodes) && config->run == __BDD_TEST_RUN__ && !config->use_tap) {
__bdd_indent__(stdout, step->level);
printf("%s ", step->name);
}
if (!skipped) {
__bdd_test_main__(config);
}
if (skipped) {
if (config->run == __BDD_TEST_RUN__) {
if (!config->has_focus_nodes) {
if (config->use_tap) {
// We only to report tests and not setup / teardown success
if (config->test_tap_index) {
printf("skipped %zu - %s\n", config->test_tap_index, step->name);
}
} else {
printf(
"%s(SKIP)%s\n",
config->use_color ? __BDD_COLOR_YELLOW__ : "",
config->use_color ? __BDD_COLOR_RESET__ : ""
);
}
}
}
} else if (config->error == NULL) {
if (config->run == __BDD_TEST_RUN__) {
if (config->use_tap) {
// We only to report tests and not setup / teardown success
if (config->test_tap_index) {
printf("ok %zu - %s\n", config->test_tap_index, step->name);
}
} else {
printf(
"%s(OK)%s\n",
config->use_color ? __BDD_COLOR_GREEN__ : "",
config->use_color ? __BDD_COLOR_RESET__ : ""
);
}
}
} else {
++config->failed_test_count;
if (config->use_tap) {
// We only to report tests and not setup / teardown errors
if (config->test_tap_index) {
printf("not ok %zu - %s\n", config->test_tap_index, step->name);
}
} else {
printf(
"%s(FAIL)%s\n",
config->use_color ? __BDD_COLOR_RED__ : "",
config->use_color ? __BDD_COLOR_RESET__ : ""
);
__bdd_indent__(stdout, step->level + 1);
printf("%s\n", config->error);
__bdd_indent__(stdout, step->level + 2);
printf("%s\n", config->location);
}
free(config->error);
config->error = NULL;
}
} else if (!skipped) {
__bdd_test_main__(config);
}
}
char *__bdd_vformat__(const char *format, va_list va) {
// First we over-allocate
const size_t size = 2048;
char *result = calloc(size, sizeof(char));
if (!result) {
perror("calloc(result)");
abort();
}
vsnprintf(result, size - 1, format, va);
// Then clip to an actual size
void* r = realloc(result, strlen(result) + 1);
if (!r) {
perror("realloc(result)");
abort();
}
result = r;
return result;
}
char *__bdd_format__(const char *format, ...) {
va_list va;
va_start(va, format);
char *result = __bdd_vformat__(format, va);
va_end(va);
return result;
}
bool __bdd_is_supported_term__() {
bool result;
const char *term = getenv("TERM");
result = term && strcmp(term, "") != 0;
#ifndef _WIN32
return result;
#else
if (result) {
return 1;
}
// Attempt to enable virtual terminal processing on Windows.
// See: https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (hOut == INVALID_HANDLE_VALUE) {
return 0;
}
DWORD dwMode = 0;
if (!GetConsoleMode(hOut, &dwMode)) {
return 0;
}
dwMode |= 0x4; // ENABLE_VIRTUAL_TERMINAL_PROCESSING
if (!SetConsoleMode(hOut, dwMode)) {
return 0;
}
return 1;
#endif
}
int main(void) {
struct __bdd_config_type__ config = {
.run = __BDD_INIT_RUN__,
.id = 0,
.test_index = 0,
.test_tap_index = 0,
.failed_test_count = 0,
.node_stack = __bdd_array_create__(),
.nodes = __bdd_array_create__(),
.error = NULL,
.use_color = 0,
.use_tap = 0
};
const char *tap_env = getenv("BDD_USE_TAP");
if (BDD_USE_TAP || (tap_env && strcmp(tap_env, "") != 0 && strcmp(tap_env, "0") != 0)) {
config.use_tap = 1;
}
if (!config.use_tap && BDD_USE_COLOR && __BDD_IS_ATTY__() && __bdd_is_supported_term__()) {
config.use_color = 1;
}
__bdd_node__ *root = __bdd_node_create__(-1, __bdd_spec_name__, __BDD_NODE_GROUP__, __bdd_node_flags_none__);
__bdd_array_push__(config.node_stack, root);
// During the first run we just gather the
// count of the tests and their descriptions
__bdd_test_main__(&config);
__bdd_array__ *steps = __bdd_array_create__();
__bdd_node_flatten__(&config, root, steps);
size_t test_count = 0;
for (size_t i = 0; i < steps->size; ++i) {
__bdd_test_step__ *step = steps->values[i];
if(step->type == __BDD_NODE_TEST__) {
++test_count;
}
}
// Outputting the name of the suite
if (config.use_tap) {
printf("TAP version 13\n1..%zu\n", test_count);
}
config.run = __BDD_TEST_RUN__;
for (size_t i = 0; i < steps->size; ++i) {
__bdd_test_step__ *step = steps->values[i];
config.node_stack->size = 1;
config.id = 0;
config.current_test = step;
__bdd_run__(&config);
}
for (size_t i = 0; i < config.nodes->size; ++i) {
__bdd_node_free__(config.nodes->values[i]);
}
root->name = NULL; // name is statically allocated
__bdd_node_free__(root);
for (size_t i = 0; i < steps->size; ++i) {
free(steps->values[i]);
}
__bdd_array_free__(config.nodes);
__bdd_array_free__(config.node_stack);
__bdd_array_free__(steps);
if (config.failed_test_count > 0) {
if (!config.use_tap) {
printf(
"\n%zu test%s run, %zu failed.\n",
test_count, test_count == 1 ? "" : "s", config.failed_test_count
);
}
return 1;
}
return 0;
}
#define spec(name) \
char *__bdd_spec_name__ = (name);\
void __bdd_test_main__ (__bdd_config_type__ *__bdd_config__)\
#define __BDD_NODE__(flags, node_list, type, ...)\
for(\
bool __bdd_has_run__ = 0;\
(\
!__bdd_has_run__ && \
__bdd_enter_node__(flags, __bdd_config__, (type), offsetof(struct __bdd_node__, node_list), __VA_ARGS__) \
);\
__bdd_exit_node__(__bdd_config__), \
__bdd_has_run__ = 1 \
)
#define describe(...) __BDD_NODE__(__bdd_node_flags_none__, list_children, __BDD_NODE_GROUP__, __VA_ARGS__)
#define it(...) __BDD_NODE__(__bdd_node_flags_none__, list_children, __BDD_NODE_TEST__, __VA_ARGS__)
#define it_only(...) __BDD_NODE__(__bdd_node_flags_focus__, list_children, __BDD_NODE_TEST__, __VA_ARGS__)
#define fit(...) it_only(__VA_ARGS__)
#define it_skip(...) __BDD_NODE__(__bdd_node_flags_skip__, list_children, __BDD_NODE_TEST__, __VA_ARGS__)
#define xit(...) it_skip(__VA_ARGS__)
#define before_each() __BDD_NODE__(__bdd_node_flags_none__, list_before_each, __BDD_NODE_INTERIM__, "before_each")
#define after_each() __BDD_NODE__(__bdd_node_flags_none__, list_after_each, __BDD_NODE_INTERIM__, "after_each")
#define before() __BDD_NODE__(__bdd_node_flags_none__, list_before, __BDD_NODE_INTERIM__, "before")
#define after() __BDD_NODE__(__bdd_node_flags_none__, list_after, __BDD_NODE_INTERIM__, "after")
#ifndef BDD_NO_CONTEXT_KEYWORD
#define context(name) describe(name)
#endif
#define __BDD_MACRO__(M, ...) __BDD_OVERLOAD__(M, __BDD_COUNT_ARGS__(__VA_ARGS__)) (__VA_ARGS__)
#define __BDD_OVERLOAD__(macro_name, suffix) __BDD_EXPAND_OVERLOAD__(macro_name, suffix)
#define __BDD_EXPAND_OVERLOAD__(macro_name, suffix) macro_name##suffix
#define __BDD_COUNT_ARGS__(...) __BDD_PATTERN_MATCH__(__VA_ARGS__,_,_,_,_,_,_,_,_,_,ONE__)
#define __BDD_PATTERN_MATCH__(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N, ...) N
#define __BDD_STRING_HELPER__(x) #x
#define __BDD_STRING__(x) __BDD_STRING_HELPER__(x)
#define __STRING__LINE__ __BDD_STRING__(__LINE__)
#define __BDD_FMT_COLOR__ __BDD_COLOR_RED__ "Check failed:" __BDD_COLOR_RESET__ " %s"
#define __BDD_FMT_PLAIN__ "Check failed: %s"
#define __BDD_CHECK__(condition, ...) if (!(condition))\
{\
char *message = __bdd_format__(__VA_ARGS__);\
const char *fmt = __bdd_config__->use_color ? __BDD_FMT_COLOR__ : __BDD_FMT_PLAIN__;\
__bdd_config__->location = "at " __FILE__ ":" __STRING__LINE__;\
size_t bufflen = strlen(fmt) + strlen(message) + 1;\
__bdd_config__->error = calloc(bufflen, sizeof(char));\
if (__bdd_config__->use_color) {\
snprintf(__bdd_config__->error, bufflen, __BDD_FMT_COLOR__, message);\
} else {\
snprintf(__bdd_config__->error, bufflen, __BDD_FMT_PLAIN__, message);\
}\
free(message);\
return;\
}
#define __BDD_CHECK_ONE__(condition) __BDD_CHECK__(condition, #condition)
#define check(...) do { __BDD_MACRO__(__BDD_CHECK_, __VA_ARGS__) } while (0)
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif //BDD_FOR_C_H

View File

@ -0,0 +1,15 @@
add_executable(waitui-test_list)
target_sources(waitui-test_list
PRIVATE
"test_list.c"
)
target_link_libraries(waitui-test_list PRIVATE list)
add_test(NAME waitui-test_list COMMAND waitui-test_list)
if(ENABLE_TEST_COVERAGE)
target_compile_options(list PUBLIC -O0 -g -fprofile-arcs -ftest-coverage)
target_link_options(list PUBLIC -fprofile-arcs -ftest-coverage)
endif()

View File

@ -0,0 +1,253 @@
/**
* @file test_list.c
* @author rick
* @date 09.07.21
* @brief Test for the List implementation
*/
#include "waitui/list_generic.h"
#include "waitui/list_generic_impl.h"
#include "../../bdd-for-c-ext.h"
typedef struct value {
int count;
int i;
} value;
static value *value_new(int i) {
value *this = calloc(1, sizeof(*this));
if (!this) { return NULL; }
this->i = i;
return this;
}
static void value_destroy(value **this) {
if (!this || !(*this)) { return; }
free(*this);
*this = NULL;
}
CREATE_LIST_TYPE(INTERFACE, value)
CREATE_LIST_TYPE(IMPLEMENTATION, value)
spec("list") {
context("use as a normal list") {
static value_list *list = NULL;
before_each() {
list = value_list_new();
check(list != NULL, "list should not be NULL");
}
after_each() {
value_list_destroy(&list);
check(list == NULL, "list should be NULL");
}
describe("value_list_push()") {
for_it(
"should add values to the end of the list and it should be there",
params_format(2, "start: %d", "elements: %d"),
format_args(test_param.start, test_param.count),
{
int start;
int count;
},
test_params(
{0, 0},
{0, 1},
{1, 1},
{4, 20},
)
) {
for (int i = test_param.start; i < test_param.start + test_param.count; ++i) {
check(value_list_push(list, value_new(i)) == 1);
value *value = value_list_peek(list);
check(value->i == i, "value should be %d but is %d", i, value->i);
}
for (int i = test_param.start + test_param.count - 1; i >= test_param.start; --i) {
value *value = value_list_pop(list);
check(value != NULL, "value should not be NULL");
check(value->i == i, "value should be %d but is %d", i, value->i);
value_destroy(&value);
}
}
for_it_end();
it("should return 0 with NULL as this param") {
check(value_list_push(NULL, value_new(1)) == 0, "return should not be 0");
}
it("should return 0 with NULL as valueElement param") {
check(value_list_push(list, NULL) == 0, "return should not be 0");
}
}
describe("value_list_pop()") {
it("should return NULL with NULL as this param") {
static value *value = NULL;
value = value_list_pop(NULL);
check(value == NULL, "value should be NULL");
}
it("should return NULL with an empty list as this param") {
static value *value = NULL;
value = value_list_pop(list);
check(value == NULL, "value should be NULL");
}
}
describe("value_list_unshift()") {
for_it(
"should add values to the begin of the list and it should be there",
params_format(2, "start: %d", "elements: %d"),
format_args(test_param.start, test_param.count),
{
int start;
int count;
},
test_params(
{0, 0},
{0, 1},
{1, 1},
{4, 20},
)
) {
for (int i = test_param.start; i < test_param.start + test_param.count; ++i) {
check(value_list_unshift(list, value_new(i)) == 1);
}
for (int i = test_param.start + test_param.count - 1; i >= test_param.start; --i) {
value *value = value_list_shift(list);
check(value != NULL, "value should not be NULL");
check(value->i == i, "value should be %d but is %d", i, value->i);
value_destroy(&value);
}
}
for_it_end();
it("should return 0 with NULL as this param") {
check(value_list_unshift(NULL, value_new(1)) == 0, "return should not be 0");
}
it("should return 0 with NULL as valueElement param") {
check(value_list_unshift(list, NULL) == 0, "return should not be 0");
}
}
describe("value_list_shift()") {
it("should return NULL with NULL as this param") {
static value *value = NULL;
value = value_list_shift(NULL);
check(value == NULL, "value should be NULL");
}
it("should return NULL with an empty list as this param") {
static value *value = NULL;
value = value_list_shift(list);
check(value == NULL, "value should be NULL");
}
}
describe("value_list_getIterator()") {
for_it(
"should iterate over all values from the list",
params_format(2, "start: %d", "elements: %d"),
format_args(test_param.start, test_param.count),
{
int start;
int count;
},
test_params(
{0, 0},
{0, 1},
{1, 1},
{4, 20},
)
) {
static value_list_iter *iter = NULL;
for (int i = test_param.start; i < test_param.start + test_param.count; ++i) {
check(value_list_push(list, value_new(i)) == 1);
}
iter = value_list_getIterator(list);
check(iter != NULL, "iter should not be NULL");
int i = test_param.start;
while (value_list_iter_hasNext(iter)) {
check(i < test_param.start + test_param.count, "iteration should not iterate more than values added");
value *value = value_list_iter_next(iter);
check(value != NULL, "value should not be NULL");
check(value->i == i, "value should be %d but is %d", i, value->i);
++i;
}
value_list_iter_destroy(&iter);
check(iter == NULL, "iter should be NULL");
}
for_it_end();
it("should return NULL with NULL as this param") {
static value_list_iter *iter = NULL;
iter = value_list_getIterator(NULL);
check(iter == NULL, "iter should be NULL");
}
}
describe("value_list_iter_next()") {
it("should return NULL with NULL as this param") {
static value *value = NULL;
value = value_list_iter_next(NULL);
check(value == NULL, "value should be NULL");
}
}
describe("value_list_iter_hasNext()") {
it("should return false with NULL as this param") {
check(value_list_iter_hasNext(NULL) == false, "return should be false");
}
}
describe("value_list_iter_destroy()") {
it("should work with NULL as this param") {
value_list_iter_destroy(NULL);
}
it("should work with a pointer to NULL as this param") {
static value_list_iter *empty = NULL;
value_list_iter_destroy(&empty);
check(empty == NULL, "empty should be NULL");
}
}
describe("value_list_destroy()") {
it("should work with NULL as this param") {
value_list_destroy(NULL);
}
it("should work with a pointer to NULL as this param") {
static value_list *empty = NULL;
value_list_destroy(NULL);
value_list_destroy(&empty);
check(empty == NULL, "empty should be NULL");
}
}
describe("value_list_peek()") {
it("should return NULL with NULL as this param") {
static value *value = NULL;
value = value_list_peek(NULL);
check(value == NULL, "value should be NULL");
}
it("should return NULL with an empty list as this param") {
static value *value = NULL;
value = value_list_peek(list);
check(value == NULL, "value should be NULL");
}
}
}
}

View File

@ -0,0 +1,3 @@
set(project_version 0.0.1)
set(project_description "waitui language system tests")
set(project_homepage "http://example.com")