diff --git a/.gitignore b/.gitignore index deb1de7433b..3e907cf52c9 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,5 @@ DELIVERY/ CMakeCache.txt cmake_install.cmake CMakeFiles/ +cmake_build/ +Testing/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 03ac543a450..caf33b41bee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,10 +2,25 @@ # SPDX-License-Identifier: Apache-2.0 # This is the boilerplate for Mbed OS +project(MbedOS) cmake_minimum_required(VERSION 3.19.0 FATAL_ERROR) -include(${MBED_CONFIG_PATH}/mbed_config.cmake) +option(BUILD_TESTING "Run unit tests only." OFF) + +if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) + include(CTest) +endif() + +if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING) + add_subdirectory(UNITTESTS) + set(MBED_BUILD_UNITTESTS ON CACHE BOOL "") +endif() + +if(${CMAKE_CROSSCOMPILING}) + include(${MBED_CONFIG_PATH}/mbed_config.cmake) +endif() + include(tools/cmake/set_linker_script.cmake) add_library(mbed-core INTERFACE) @@ -26,80 +41,83 @@ target_link_libraries(mbed-baremetal ) # Validate selected C library type # The C library type selected has to match the library that the target can support -if(${MBED_C_LIB} STREQUAL "small") - if(NOT "small" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS) - if("std" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS) - message(WARNING - "We noticed that target.c_lib is set to `${MBED_C_LIB}`." - " As the ${MBED_TARGET} target does not support a small C library for the ${MBED_TOOLCHAIN} toolchain," - " we are using the standard C library instead." - ) - set(MBED_C_LIB "std" CACHE STRING "") +if(${CMAKE_CROSSCOMPILING}) + if(${MBED_C_LIB} STREQUAL "small") + if(NOT "small" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS) + if("std" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS) + message(WARNING + "We noticed that target.c_lib is set to `${MBED_C_LIB}`." + " As the ${MBED_TARGET} target does not support a small C library for the ${MBED_TOOLCHAIN} toolchain," + " we are using the standard C library instead." + ) + set(MBED_C_LIB "std" CACHE STRING "") + endif() endif() + elseif(NOT ${MBED_C_LIB} IN_LIST MBED_TARGET_SUPPORTED_C_LIBS) + message(FATAL_ERROR + "Invalid `target.c_lib` ('${MBED_C_LIB}') for '${MBED_TARGET}' target." + "\nPossible value(s): ${MBED_TARGET_SUPPORTED_C_LIBS}" + ) endif() -elseif(NOT ${MBED_C_LIB} IN_LIST MBED_TARGET_SUPPORTED_C_LIBS) - message(FATAL_ERROR - "Invalid `target.c_lib` ('${MBED_C_LIB}') for '${MBED_TARGET}' target." - "\nPossible value(s): ${MBED_TARGET_SUPPORTED_C_LIBS}" - ) -endif() - -# Validate selected printf library -set(MBED_PRINTF_LIB_TYPES std minimal-printf) -if(NOT ${MBED_PRINTF_LIB} IN_LIST MBED_PRINTF_LIB_TYPES) - message(FATAL_ERROR - "Invalid printf library type '${MBED_PRINTF_LIB}'. Possible values:\n ${MBED_PRINTF_LIB_TYPES}" - ) -endif() -mbed_set_cpu_core_definitions(mbed-core) -if(${MBED_TOOLCHAIN_FILE_USED}) - mbed_set_profile_options(mbed-core ${MBED_TOOLCHAIN}) - mbed_set_c_lib(mbed-core ${MBED_C_LIB}) - mbed_set_printf_lib(mbed-core ${MBED_PRINTF_LIB}) - - target_compile_features(mbed-core - INTERFACE - c_std_11 - cxx_std_14 - ) - -endif() - -target_compile_definitions(mbed-core - INTERFACE - ${MBED_TARGET_DEFINITIONS} - ${MBED_CONFIG_DEFINITIONS} -) + # Validate selected printf library + set(MBED_PRINTF_LIB_TYPES std minimal-printf) + if(NOT ${MBED_PRINTF_LIB} IN_LIST MBED_PRINTF_LIB_TYPES) + message(FATAL_ERROR + "Invalid printf library type '${MBED_PRINTF_LIB}'. Possible values:\n ${MBED_PRINTF_LIB_TYPES}" + ) + endif() + + mbed_set_cpu_core_definitions(mbed-core) + if(${MBED_TOOLCHAIN_FILE_USED}) + message(STATUS ${MBED_TOOLCHAIN}) + mbed_set_profile_options(mbed-core ${MBED_TOOLCHAIN}) + mbed_set_c_lib(mbed-core ${MBED_C_LIB}) + mbed_set_printf_lib(mbed-core ${MBED_PRINTF_LIB}) + + target_compile_features(mbed-core + INTERFACE + c_std_11 + cxx_std_14 + ) + + endif() -# We need to generate a "response file" to pass to the C preprocessor when we preprocess the linker -# script, because of path length limitations on Windows. We set the response file and bind the path -# to a global property here. The MBED_TARGET being built queries this global property when it sets -# the linker script. -# -# We must set this global property before the targets subdirectory is added to the project. This is -# required because the MBED_TARGET depends on the response file. If the path to the response file -# is not defined when the target requests it the config definitions will not be passed to CPP. -# -# TODO: Remove this and find a more idiomatic way of passing compile definitions to CPP without -# using response files or global properties. -mbed_generate_options_for_linker(mbed-core RESPONSE_FILE_PATH) -set_property(GLOBAL PROPERTY COMPILE_DEFS_RESPONSE_FILE ${RESPONSE_FILE_PATH}) - -# Add compile definitions for backward compatibility with the toolchain -# supported. New source files should instead check for __GNUC__ and __clang__ -# for the GCC_ARM and ARM toolchains respectively. -if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") target_compile_definitions(mbed-core INTERFACE - TOOLCHAIN_GCC_ARM - TOOLCHAIN_GCC - ) -elseif(${MBED_TOOLCHAIN} STREQUAL "ARM") - target_compile_definitions(mbed-core - INTERFACE - TOOLCHAIN_ARM + ${MBED_TARGET_DEFINITIONS} + ${MBED_CONFIG_DEFINITIONS} ) + + # We need to generate a "response file" to pass to the C preprocessor when we preprocess the linker + # script, because of path length limitations on Windows. We set the response file and bind the path + # to a global property here. The MBED_TARGET being built queries this global property when it sets + # the linker script. + # + # We must set this global property before the targets subdirectory is added to the project. This is + # required because the MBED_TARGET depends on the response file. If the path to the response file + # is not defined when the target requests it the config definitions will not be passed to CPP. + # + # TODO: Remove this and find a more idiomatic way of passing compile definitions to CPP without + # using response files or global properties. + mbed_generate_options_for_linker(mbed-core RESPONSE_FILE_PATH) + set_property(GLOBAL PROPERTY COMPILE_DEFS_RESPONSE_FILE ${RESPONSE_FILE_PATH}) + + # Add compile definitions for backward compatibility with the toolchain + # supported. New source files should instead check for __GNUC__ and __clang__ + # for the GCC_ARM and ARM toolchains respectively. + if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") + target_compile_definitions(mbed-core + INTERFACE + TOOLCHAIN_GCC_ARM + TOOLCHAIN_GCC + ) + elseif(${MBED_TOOLCHAIN} STREQUAL "ARM") + target_compile_definitions(mbed-core + INTERFACE + TOOLCHAIN_ARM + ) + endif() endif() # Include mbed.h and config from generate folder @@ -122,22 +140,33 @@ add_subdirectory(platform) add_subdirectory(rtos) add_subdirectory(targets) +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(connectivity) + add_subdirectory(storage) + add_subdirectory(events) +else() + # The directories below contain optional target libraries + add_subdirectory(connectivity EXCLUDE_FROM_ALL) + add_subdirectory(storage EXCLUDE_FROM_ALL) + add_subdirectory(events EXCLUDE_FROM_ALL) +endif() + # The directories below contain optional target libraries -add_subdirectory(events EXCLUDE_FROM_ALL) -add_subdirectory(connectivity EXCLUDE_FROM_ALL) -add_subdirectory(storage EXCLUDE_FROM_ALL) add_subdirectory(drivers/device_key EXCLUDE_FROM_ALL) add_subdirectory(drivers/usb EXCLUDE_FROM_ALL) add_subdirectory(features EXCLUDE_FROM_ALL) add_subdirectory(cmsis/CMSIS_5/CMSIS/RTOS2 EXCLUDE_FROM_ALL) add_subdirectory(cmsis/device/rtos EXCLUDE_FROM_ALL) -# Ensure the words that make up the Mbed target name are separated with a hyphen, lowercase, and with the `mbed-` prefix. -string(TOLOWER ${MBED_TARGET} MBED_TARGET_CONVERTED) -string(REPLACE "_" "-" MBED_TARGET_CONVERTED ${MBED_TARGET_CONVERTED}) -string(PREPEND MBED_TARGET_CONVERTED "mbed-") -target_link_libraries(mbed-core INTERFACE ${MBED_TARGET_CONVERTED}) +if(${CMAKE_CROSSCOMPILING}) + # Ensure the words that make up the Mbed target name are separated with a hyphen, lowercase, and with the `mbed-` prefix. + string(TOLOWER ${MBED_TARGET} MBED_TARGET_CONVERTED) + string(REPLACE "_" "-" MBED_TARGET_CONVERTED ${MBED_TARGET_CONVERTED}) + string(PREPEND MBED_TARGET_CONVERTED "mbed-") + + target_link_libraries(mbed-core INTERFACE ${MBED_TARGET_CONVERTED}) +endif() # # Converts output file of `target` to binary file and to Intel HEX file. diff --git a/UNITTESTS/CMakeLists.txt b/UNITTESTS/CMakeLists.txt index 6aba4ba07ff..4303323109d 100644 --- a/UNITTESTS/CMakeLists.txt +++ b/UNITTESTS/CMakeLists.txt @@ -1,76 +1,41 @@ -cmake_minimum_required(VERSION 3.0.2) +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 -set(PROJECT_NAME unittests) -set(LIB_NAME MbedOS) - -project(${PROJECT_NAME}) +set(MBED_PATH ${CMAKE_CURRENT_SOURCE_DIR}/.. CACHE INTERNAL "") # Setup c++ standard -macro(use_cxx14) - if (CMAKE_VERSION VERSION_LESS 3.1) - if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++14") - endif() - else() - set(CMAKE_CXX_STANDARD 14) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - endif() -endmacro() - -use_cxx14() - +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) if (MINGW) - # enable PRIx formatting globally - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__STDC_FORMAT_MACROS") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__STDC_FORMAT_MACROS") + # enable PRIx formatting globally + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__STDC_FORMAT_MACROS") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__STDC_FORMAT_MACROS") endif (MINGW) #################### # GTEST #################### - -# Download and unpack googletest at configure time -configure_file(googletest-CMakeLists.txt.in googletest-download/CMakeLists.txt) -execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . - RESULT_VARIABLE result - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) -if (result) - message(FATAL_ERROR "CMake failed for google test: ${result}") -endif() -execute_process(COMMAND ${CMAKE_COMMAND} --build . - RESULT_VARIABLE result - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) -if (result) - message(FATAL_ERROR "Build failed for google test: ${result}") -endif() +include(FetchContent) +# Download and unpack googletest +FetchContent_Declare(googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG release-1.10.0 +) +FetchContent_MakeAvailable(googletest) # Prevent overriding the parent project's compiler/linker # settings on Windows set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -# Add googletest directly to our build. This defines -# the gtest and gtest_main targets. -add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src - ${CMAKE_BINARY_DIR}/googletest-build - EXCLUDE_FROM_ALL) - -# The gtest/gtest_main/gmock/gmock_main targets carry header search path -# dependencies automatically when using CMake 2.8.11 or -# later. -target_include_directories(gmock_main SYSTEM BEFORE INTERFACE - "$" - "$") #################### # TESTING #################### -include(CTest) - set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES - "${CMAKE_BINARY_DIR}/Testing" -) + "${CMAKE_BINARY_DIR}/Testing" + ) #################### # CODE COVERAGE SETUP @@ -78,19 +43,19 @@ set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES if (COVERAGE) - if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") - message(WARNING "Non-debug build may result misleading code coverage results.") - endif() + if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") + message(WARNING "Non-debug build may result misleading code coverage results.") + endif() - # Append coverage compiler flags - set(COVERAGE_COMPILER_FLAGS "-g -O0 --coverage") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}") + # Append coverage compiler flags + set(COVERAGE_COMPILER_FLAGS "-g -O0 --coverage") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}") endif(COVERAGE) if (VALGRIND) - find_program(MEMORYCHECK_COMMAND valgrind) + find_program(MEMORYCHECK_COMMAND valgrind) endif(VALGRIND) #################### @@ -100,141 +65,14 @@ endif(VALGRIND) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUNITTEST") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUNITTEST") -# Set include dirs. -set(unittest-includes-base - "${PROJECT_SOURCE_DIR}/target_h" - "${PROJECT_SOURCE_DIR}/../events/tests/UNITTESTS/target_h" - "${PROJECT_SOURCE_DIR}/../events/tests/UNITTESTS/target_h/equeue" - "${PROJECT_SOURCE_DIR}/target_h/platform" - "${PROJECT_SOURCE_DIR}/target_h/platform/cxxsupport" - "${PROJECT_SOURCE_DIR}/target_h/drivers" - "${PROJECT_SOURCE_DIR}/target_h/rtos/include" - "${PROJECT_SOURCE_DIR}/stubs" - "${PROJECT_SOURCE_DIR}/.." - "${PROJECT_SOURCE_DIR}/../features" - "${PROJECT_SOURCE_DIR}/../platform/include" - "${PROJECT_SOURCE_DIR}/../platform/include/platform" - "${PROJECT_SOURCE_DIR}/../platform/mbed-trace/include" - "${PROJECT_SOURCE_DIR}/../storage/filesystem/littlefs/include" - "${PROJECT_SOURCE_DIR}/../storage/filesystem/fat/include" - "${PROJECT_SOURCE_DIR}/../storage/blockdevice/include" - "${PROJECT_SOURCE_DIR}/../storage/filesystem/include" - "${PROJECT_SOURCE_DIR}/../storage/kvstore/include" - "${PROJECT_SOURCE_DIR}/../storage/kvstore/kv_config" - "${PROJECT_SOURCE_DIR}/../storage/kvstore/kv_config/include" - "${PROJECT_SOURCE_DIR}/../storage/kvstore/tdbstore/include" - "${PROJECT_SOURCE_DIR}/../storage/kvstore/filesystemstore/include" - "${PROJECT_SOURCE_DIR}/../storage/kvstore/kvstore_global_api/include" - "${PROJECT_SOURCE_DIR}/../drivers" - "${PROJECT_SOURCE_DIR}/../drivers/include" - "${PROJECT_SOURCE_DIR}/../drivers/include/drivers" - "${PROJECT_SOURCE_DIR}/../drivers/include/drivers/internal" - "${PROJECT_SOURCE_DIR}/../hal" - "${PROJECT_SOURCE_DIR}/../hal/include" - "${PROJECT_SOURCE_DIR}/../events/include" - "${PROJECT_SOURCE_DIR}/../events/include/events/internal" - "${PROJECT_SOURCE_DIR}/../events/source" - "${PROJECT_SOURCE_DIR}/../rtos/include" - "${PROJECT_SOURCE_DIR}/../features/frameworks" - "${PROJECT_SOURCE_DIR}/../connectivity/libraries/nanostack-libservice" - "${PROJECT_SOURCE_DIR}/../connectivity/libraries/nanostack-libservice/mbed-client-libservice" - "${PROJECT_SOURCE_DIR}/../connectivity/netsocket/include" - "${PROJECT_SOURCE_DIR}/../features/filesystem/fat" - "${PROJECT_SOURCE_DIR}/../features/filesystem/fat/ChaN" - "${PROJECT_SOURCE_DIR}/../features/filesystem/bd" - "${PROJECT_SOURCE_DIR}/../features/filesystem/" - "${PROJECT_SOURCE_DIR}/../features/filesystem/littlefs" - "${PROJECT_SOURCE_DIR}/../features/filesystem/littlefs/littlefs" - "${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/API" - "${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/AT" - "${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/device" - "${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework" - "${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/common" - "${PROJECT_SOURCE_DIR}/../connectivity" - "${PROJECT_SOURCE_DIR}/../connectivity/lorawan/include/lorawan" - "${PROJECT_SOURCE_DIR}/../connectivity/lorawan/lorastack" - "${PROJECT_SOURCE_DIR}/../connectivity/lorawan/lorastack/mac" - "${PROJECT_SOURCE_DIR}/../connectivity/lorawan/lorastack/phy" - "${PROJECT_SOURCE_DIR}/../connectivity/lorawan" - "${PROJECT_SOURCE_DIR}/../connectivity/mbedtls" - "${PROJECT_SOURCE_DIR}/../connectivity/mbedtls/include" -) - -# Create a list for test suites. -set(TEST_SUITES) - -# Get all matched tests. -file(GLOB_RECURSE unittest-file-list - "../unittest.cmake" # matches any ../**/unittest.cmake -) - -if ("${unittest-file-list}" STREQUAL "") - message(FATAL_ERROR "No tests found. Exiting...") -endif() +add_subdirectory(stubs) +add_subdirectory(fakes) -# Create unit test targets -foreach(testfile ${unittest-file-list}) - #################### - # DEFINE TARGETS - #################### - - # Init file lists. - set(unittest-includes ${unittest-includes-base}) - set(unittest-sources) - set(unittest-test-sources) - set(unittest-test-flags) - - # Get source files - include("${testfile}") - - get_filename_component(TEST_SUITE_DIR ${testfile} DIRECTORY) - - file(RELATIVE_PATH - TEST_SUITE_NAME # output - "${PROJECT_SOURCE_DIR}/.." # root - ${TEST_SUITE_DIR} #abs dirpath - ) - - string(REGEX REPLACE "/|\\\\" "-" TEST_SUITE_NAME ${TEST_SUITE_NAME}) - - set(TEST_SUITES ${TEST_SUITES} ${TEST_SUITE_NAME}) - - set(LIBS_TO_BE_LINKED gmock_main) - - # Build directories list - set(BUILD_DIRECTORIES) - - if (unittest-sources) - # Create the testable static library. - add_library("${TEST_SUITE_NAME}.${LIB_NAME}" STATIC ${unittest-sources}) - target_include_directories("${TEST_SUITE_NAME}.${LIB_NAME}" PRIVATE - ${unittest-includes}) - target_compile_options("${TEST_SUITE_NAME}.${LIB_NAME}" PRIVATE - ${unittest-test-flags}) - set(LIBS_TO_BE_LINKED ${LIBS_TO_BE_LINKED} "${TEST_SUITE_NAME}.${LIB_NAME}") - - # Append lib build directory to list - list(APPEND BUILD_DIRECTORIES "./CMakeFiles/${TEST_SUITE_NAME}.${LIB_NAME}.dir") - endif(unittest-sources) - - if (unittest-test-sources) - # Create the executable. - add_executable(${TEST_SUITE_NAME} ${unittest-test-sources}) - - target_include_directories(${TEST_SUITE_NAME} PRIVATE - ${unittest-includes}) - target_compile_options(${TEST_SUITE_NAME} PRIVATE - ${unittest-test-flags}) - - # Link the executable with the libraries. - target_link_libraries(${TEST_SUITE_NAME} ${LIBS_TO_BE_LINKED}) - - add_test(NAME "${TEST_SUITE_NAME}" COMMAND ${TEST_SUITE_NAME}) - - # Append test build directory to list - list(APPEND BUILD_DIRECTORIES "./CMakeFiles/${TEST_SUITE_NAME}.dir") - else() - message(WARNING "No test source files found for ${TEST_SUITE_NAME}.\n") - endif(unittest-test-sources) -endforeach(testfile) +macro(mbed_add_all_subdirectories subdirectories_list) + foreach(dir ${subdirectories_list}) + if(IS_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/${dir}) + add_subdirectory(${dir}) + endif() + endforeach() +endmacro() diff --git a/UNITTESTS/README.md b/UNITTESTS/README.md deleted file mode 100644 index 5dd3f04511f..00000000000 --- a/UNITTESTS/README.md +++ /dev/null @@ -1,306 +0,0 @@ -## Unit testing - -This document describes how to write and use unit tests for Arm Mbed OS. - -### Introduction - -Unit tests test code in small sections on a host machine. Unlike other testing tools, unit testing doesn't require embedded hardware or need to build a full operating system. Because of this, unit testing can result in faster tests than other tools. Unit testing happens in a build environment where you test each C or C++ class or module in isolation. Build test suites into separate test binaries and stub all access outside to remove dependencies on any specific embedded hardware or software combination. This allows you to complete tests using native compilers on the build machine. - -### Prerequisites - -Please install the following dependencies to use Mbed OS unit testing: - -* GNU toolchains. - * GCC 6 or later. We recommend you use MinGW-W64 on Windows, but any Windows port of the above GCC versions works. Default compilers can be used on Mac OS instead of GCC to shorten build times, but code coverage results can differ. -* CMake 3.0 or newer. -* Python 2.7.x, 3.5 or newer. -* Pip 10.0 or newer. -* Gcovr 4.1 or newer. -* Arm Mbed CLI 1.8.0 or newer. - -Detailed instructions for supported operating systems are below. - -#### Installing dependencies on Debian or Ubuntu - -In a terminal window: - -1. `sudo apt-get -y install build-essential cmake` -1. Install Python and Pip with: - - ``` - sudo apt-get -y install python python-setuptools - sudo easy_install pip - ``` - -1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`. - -#### Installing dependencies on macOS - -In a terminal window: - -1. Install [Homebrew](https://brew.sh/). -1. Install Xcode Command Line Tools with `xcode-select --install`. -1. Install CMake with: `brew install cmake`. -1. Install Python and Pip: - - ``` - brew install python - sudo easy_install pip - ``` - -1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`. -1. (Optional) Install GCC with `brew install gcc`. - -#### Installing dependencies on Windows - -In a terminal window: - -1. Download and install MinGW-W64 from [SourceForge](https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/). -1. Download CMake binaries from https://cmake.org/download/, and run the installer. -1. Download Python 2.7 or Python 3 from https://www.python.org/getit/, and run the installer. -1. Add MinGW, CMake and Python into system PATH. -1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`. - -### Test code structure - -Find unit tests in the Mbed OS repository under the `UNITTESTS` folder. We recommend unit test files use an identical directory path as the file under test. This makes it easier to find unit tests for a particular class or a module. For example, if the file you're testing is `some/example/path/ClassName.cpp`, then all the test files are in the `UNITTESTS/some/example/path/ClassName` directory. Each test suite needs to have its own `unittest.cmake` file for test configuration. - -All the class stubs should be located in the `UNITTESTS/stubs` directory. A single stub class can be used by multiple test suites and should follow the naming convention `ClassName_stub.cpp` for the source file, and `ClassName_stub.h` for the header file. Use the actual header files for the unit tests, and don't stub headers if possible. The stubbed headers reside in the `UNITTESTS/target_h` directory. - -#### Test discovery - -Registering unit tests to run happens automatically, and the test runner handles registration. However, test files do not automatically build. Build unit tests with a separate system that searches for unit tests under the `UNITTESTS` directory. - -For the build system to find and build any test suite automatically, include a unit test configuration file named `unittest.cmake` for each unit test suite. This configuration file lists all the source files required for the test build. - -#### Test names - -The build system automatically generates names of test suites. The name is constructed by taking a relative file path from the UNITTESTS directory to the test directory and replacing path separators with dashes. For example, the test suite name for `some/example/path/ClassName.cpp` is `some-example-path-ClassName`. Suite names are used when deciding which test suites to run. - -### Unit testing with Mbed CLI - -Mbed CLI supports unit tests through the `mbed test --unittests` command. For information on using Mbed CLI, please see the [CLI documentation](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html). - -### Writing unit tests - -A unit tests suite consists of one or more test cases. The test cases should cover all the functions in a class under test. All the external dependencies are stubbed including the other classes in the same module. Avoid stubbing header files. Finally, analyze code coverage to ensure all code is tested, and no dead code is found. - -Unit tests are written using [Google Test v1.10.0](https://github.com/google/googletest/releases/tag/release-1.10.0). - -Please see the [documentation for Google Test](https://github.com/google/googletest/blob/master/googletest/docs/primer.md) to learn how to write unit tests using its framework. See the [documentation for Google Mock](https://github.com/google/googletest/blob/master/googlemock/docs/Documentation.md) if you want to write and use C++ mock classes instead of stubs. - -#### Test suite configuration - -Create two files in the test directory for each test suite: - -* Unit test source file (`test_ClassName.cpp`). -* Unit test configuration file (`unittest.cmake`). - -List all the required files for the build in the `unittest.cmake` file with paths relative to the `UNITTESTS` folder. Use the following variables to list the source files and include paths: - -* **unittest-includes**: List of header include paths. You can use this to extend or overwrite default paths listed in `UNITTESTS/CMakeLists.txt`. -* **unittest-sources**: List of files under test. -* **unittest-test-sources**: List of test sources and stubs. - -You can also set custom compiler flags and other configurations supported by CMake in `unittest.cmake`. - -#### Example - -With the following steps, you can write a simple unit test. This example creates dummy classes to be tested, creates and configures unit tests for a class and stubs all external dependencies. - -1. Create the following dummy classes in `mbed-os/example`: - - **MyClass.h** - - ``` - #ifndef MYCLASS_H_ - #define MYCLASS_H_ - - namespace example { - - class MyClass { - public: - int myFunction(); - }; - - } - - #endif - ``` - - **MyClass.cpp** - - ``` - #include "MyClass.h" - #include "OtherClass.h" - - namespace example { - - int MyClass::myFunction() { - OtherClass o = OtherClass(); - return o.otherFunction(); - } - - } - ``` - - **OtherClass.h** - - ``` - #ifndef OTHERCLASS_H_ - #define OTHERCLASS_H_ - - namespace example { - - class OtherClass { - public: - int otherFunction(); - }; - - } - - #endif - ``` - - **OtherClass.cpp** - - ``` - #include "OtherClass.h" - - namespace example { - - int OtherClass::otherFunction() { - return 1; - } - - } - ``` - -1. Create a directory for MyClass unit tests in `UNITTESTS/example/MyClass`. -1. Create a configuration file and a source file for MyClass unit tests in `UNITTESTS/example/MyClass`: - - **unittest.cmake** - - ``` - # Add here additional test specific include paths - set(unittest-includes ${unittest-includes} - ../example - ) - - # Add here classes under test - set(unittest-sources - ../example/MyClass.cpp - ) - - # Add here test classes and stubs - set(unittest-test-sources - example/MyClass/test_MyClass.cpp - stubs/OtherClass_stub.cpp - ) - ``` - - **test_MyClass.cpp** - - ``` - #include "gtest/gtest.h" - #include "example/MyClass.h" - - class TestMyClass : public testing::Test { - protected: - example::MyClass *obj; - - virtual void SetUp() - { - obj = new example::MyClass(); - } - - virtual void TearDown() - { - delete obj; - } - }; - - TEST_F(TestMyClass, constructor) - { - EXPECT_TRUE(obj); - } - - TEST_F(TestMyClass, myfunction) - { - EXPECT_EQ(obj->myFunction(), 0); - } - ``` - -1. Stub all external dependencies. Create the following stub in `UNITTESTS/stubs`: - - **OtherClass_stub.cpp** - - ``` - #include "example/OtherClass.h" - - namespace example { - - int OtherClass::otherFunction() { - return 0; - } - - } - ``` - -This example does not use any Mbed OS code, but if your unit tests do, then remember to update header stubs in `UNITTESTS/target_h` and source stubs in `UNITTESTS/stubs` with any missing type or function declarations. - -### Building and running unit tests - -Use Mbed CLI to build and run unit tests. For advanced use, you can run CMake and a Make program directly. - -#### Build tests directly with CMake - -1. Create a build directory `mkdir UNITTESTS/build`. -1. Move to the build directory `cd UNITTESTS/build`. -1. Run CMake using a relative path to `UNITTESTS` folder as the argument. So from `UNITTESTS/build` use `cmake ..`: - * Add `-g [generator]` if generating other than Unix Makefiles such in case of MinGW use `-g "MinGW Makefiles"`. - * Add `-DCMAKE_MAKE_PROGRAM=`, `-DCMAKE_CXX_COMPILER=` and `-DCMAKE_C_COMPILER=` to use a specific Make program and compilers. - * Add `-DCMAKE_BUILD_TYPE=Debug` for a debug build. - * Add `-DCOVERAGE=True` to add coverage compiler flags. - * Add `-Dgtest_disable_pthreads=ON` to run in a single thread. - * See the [CMake manual](https://cmake.org/cmake/help/v3.0/manual/cmake.1.html) for more information. -1. Run a Make program to build tests. - -#### Run tests directly with CTest - -Run a test binary in the build directory to run a unit test suite. To run multiple test suites at once, use the CTest test runner. Run CTest with `ctest`. Add `-v` to get results for each test case. See the [CTest manual](https://cmake.org/cmake/help/v3.0/manual/ctest.1.html) for more information. - -#### Run tests with GUI test runner - -1. Install `gtest-runner` according to the [documentation](https://github.com/nholthaus/gtest-runner). -1. Run `gtest-runner`. -1. Add test executables into the list and run. - -### Debugging - -1. Use Mbed CLI to build a debug build. For advanced use, run CMake directly with `-DCMAKE_BUILD_TYPE=Debug`, and then run a Make program. -1. Run GDB with a test executable as an argument to debug unit tests. -1. Run tests with Valgrind to analyze the test memory profile. - -### Get code coverage - -Use Mbed CLI to generate code coverage reports. For advanced use, follow these steps: - -1. Run CMake with both `-DCMAKE_BUILD_TYPE=Debug` and `-DCOVERAGE=True`. -1. Run a Make program to build the tests. -1. Run the tests. -1. Run Gcovr or any other code coverage tool directly in the build directory. - -### Troubleshooting - -**Problem:** Generic problems with CMake or with the build process. -* **Solution**: Delete the build directory. Make sure that CMake, g++, GCC and a Make program can be found in the path and are correct versions. - -**Problem:** (Windows) Virus protection identifies files generated by CMake as malicious and quarantines the files. -* **Solution**: Restore false-positive files from the quarantine. - -**Problem:** (Windows) Git with shell installation adds sh.exe to the path and then CMake throws an error: sh.exe was found in your PATH. For MinGW make to work correctly, sh.exe must NOT be in your path. -* **Solution**: Remove sh.exe from the system path. - -**Problem:** (Mac OS) CMake compiler check fails on Mac OS Mojave when using GCC-8. -* **Solution**: Make sure gnm (binutils) is not installed. Uninstall binutils with `brew uninstall binutils`. diff --git a/UNITTESTS/fakes/CMakeLists.txt b/UNITTESTS/fakes/CMakeLists.txt new file mode 100644 index 00000000000..2d3b74b8633 --- /dev/null +++ b/UNITTESTS/fakes/CMakeLists.txt @@ -0,0 +1,5 @@ +# Copyright (c) 2020 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_subdirectory(ble) +add_subdirectory(events) diff --git a/UNITTESTS/fakes/ble/BLE.cpp b/UNITTESTS/fakes/ble/BLE.cpp new file mode 100644 index 00000000000..337558ed57c --- /dev/null +++ b/UNITTESTS/fakes/ble/BLE.cpp @@ -0,0 +1,163 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ble/BLE.h" +#include "GattServerImpl_mock.h" +#include "GattClientImpl_mock.h" +#include "GapImpl_mock.h" +#include "SecurityManagerImpl_mock.h" +#include "ble/GattClient.h" +#include "ble/GattServer.h" +#include "ble/SecurityManager.h" +#include "ble/Gap.h" +#include "ble_mocks.h" + +namespace ble { + +static GapMock *gap_impl = nullptr; +static GattServerMock *gatt_server_impl = nullptr; +static GattClientMock *gatt_client_impl = nullptr; +static SecurityManagerMock *security_manager_impl = nullptr; + +static Gap *gap = nullptr; +static GattServer *gatt_server = nullptr; +static GattClient *gatt_client = nullptr; +static SecurityManager *security_manager = nullptr; + +GapMock& gap_mock() { + return *ble::gap_impl; +} + +GattServerMock& gatt_server_mock() { + return *ble::gatt_server_impl; +} + +GattClientMock& gatt_client_mock() { + return *ble::gatt_client_impl; +} + +SecurityManagerMock& security_manager_mock() { + return *ble::security_manager_impl; +} + +void init_mocks() { + if (gap_impl) { + /* we are already initialised */ + return; + } + + /* mocks */ + gap_impl = new GapMock(); + gatt_server_impl = new GattServerMock(); + gatt_client_impl = new GattClientMock(); + security_manager_impl = new SecurityManagerMock(); + /* user APIS */ + gap = new Gap(gap_impl); + gatt_server = new GattServer(gatt_server_impl); + gatt_client = new GattClient(gatt_client_impl); + security_manager = new SecurityManager(security_manager_impl); +} + +void delete_mocks() { + delete gap; + delete gap_impl; + delete gatt_server; + delete gatt_server_impl; + delete gatt_client; + delete gatt_client_impl; + delete security_manager; + delete security_manager_impl; + + gap = nullptr; + gap_impl = nullptr; + gatt_server = nullptr; + gatt_server_impl = nullptr; + gatt_client = nullptr; + gatt_client_impl = nullptr; + security_manager = nullptr; + security_manager_impl = nullptr; +} + +class BLEInstanceBase { +}; + +BLE::BLE(ble::BLEInstanceBase &transport) : transport(transport) +{ +} + +BLE& BLE::Instance() +{ + static ble::BLEInstanceBase transport; + static BLE instance(transport); + init_mocks(); + return instance; +} + +ble::Gap &BLE::gap() +{ + init_mocks(); + return *ble::gap; +} + +ble::GattServer &BLE::gattServer() +{ + init_mocks(); + return *ble::gatt_server; +} + +ble::GattClient &BLE::gattClient() +{ + init_mocks(); + return *ble::gatt_client; +} + +ble::SecurityManager &BLE::securityManager() +{ + init_mocks(); + return *ble::security_manager; +} + +const ble::Gap &BLE::gap() const +{ + auto &self = const_cast(*this); + return const_cast(self.gap()); +} + +const ble::GattServer &BLE::gattServer() const +{ + auto &self = const_cast(*this); + return const_cast(self.gattServer()); +} + +const ble::GattClient &BLE::gattClient() const +{ + auto &self = const_cast(*this); + return const_cast(self.gattClient()); +} + +const ble::SecurityManager &BLE::securityManager() const +{ + auto &self = const_cast(*this); + return const_cast(self.securityManager()); +} + +void BLE::processEvents() +{ + +} + +} \ No newline at end of file diff --git a/UNITTESTS/fakes/ble/CMakeLists.txt b/UNITTESTS/fakes/ble/CMakeLists.txt new file mode 100644 index 00000000000..62aa99eb73b --- /dev/null +++ b/UNITTESTS/fakes/ble/CMakeLists.txt @@ -0,0 +1,41 @@ +# Copyright (c) 2020 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-fakes-ble) + +target_include_directories(mbed-fakes-ble + PUBLIC + ${MBED_PATH}/UNITTESTS/fakes/ble/ + ${MBED_PATH}/connectivity/FEATURE_BLE/include + ${MBED_PATH}/connectivity/FEATURE_BLE/include/ble + ${MBED_PATH}/connectivity/FEATURE_BLE/source + PRIVATE + ${gtest_SOURCE_DIR}/include + ${gmock_SOURCE_DIR}/include +) + +target_sources(mbed-fakes-ble + PRIVATE + ${MBED_PATH}/connectivity/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp + ${MBED_PATH}/connectivity/FEATURE_BLE/source/gap/AdvertisingParameters.cpp + ${MBED_PATH}/connectivity/FEATURE_BLE/source/gap/ConnectionParameters.cpp + ${MBED_PATH}/connectivity/FEATURE_BLE/source/gatt/DiscoveredCharacteristic.cpp + ${MBED_PATH}/connectivity/FEATURE_BLE/source/Gap.cpp + ${MBED_PATH}/connectivity/FEATURE_BLE/source/GattClient.cpp + ${MBED_PATH}/connectivity/FEATURE_BLE/source/GattServer.cpp + ${MBED_PATH}/connectivity/FEATURE_BLE/source/SecurityManager.cpp + ${MBED_PATH}/UNITTESTS/fakes/ble/BLE.cpp + ${MBED_PATH}/UNITTESTS/fakes/ble/source/GattServerImpl_mock.cpp + ${MBED_PATH}/UNITTESTS/fakes/ble/ble_mocks.h + ${MBED_PATH}/UNITTESTS/fakes/ble/GapImpl_mock.h + ${MBED_PATH}/UNITTESTS/fakes/ble/GattClientImpl_mock.h + ${MBED_PATH}/UNITTESTS/fakes/ble/GattServerImpl_mock.h + ${MBED_PATH}/UNITTESTS/fakes/ble/SecurityManagerImpl_mock.h +) + +target_link_libraries(mbed-fakes-ble + PRIVATE + mbed-headers + mbed-stubs-headers + gcov +) diff --git a/UNITTESTS/fakes/ble/GapImpl_mock.h b/UNITTESTS/fakes/ble/GapImpl_mock.h new file mode 100644 index 00000000000..b59461da140 --- /dev/null +++ b/UNITTESTS/fakes/ble/GapImpl_mock.h @@ -0,0 +1,91 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GAPMOCK_H +#define BLE_GAPMOCK_H + +#include "gmock/gmock.h" +#include "source/generic/GapImpl.h" + +namespace ble { + +class GapMock : public ble::impl::Gap { +public: + GapMock() {}; + GapMock(const GapMock&) = delete; + GapMock& operator=(const GapMock&) = delete; + virtual ~GapMock() {}; + + MOCK_METHOD((ble_error_t), reset, (), (override)); + MOCK_METHOD(void, setEventHandler, (EventHandler *handler), (override)); + MOCK_METHOD(bool, isFeatureSupported, (controller_supported_features_t feature), (override)); + MOCK_METHOD(uint8_t, getMaxAdvertisingSetNumber, (), (override)); + MOCK_METHOD(uint16_t, getMaxAdvertisingDataLength, (), (override)); + MOCK_METHOD(uint16_t, getMaxConnectableAdvertisingDataLength, (), (override)); + MOCK_METHOD(uint16_t, getMaxActiveSetAdvertisingDataLength, (), (override)); + MOCK_METHOD(ble_error_t, createAdvertisingSet, (advertising_handle_t *handle, const AdvertisingParameters ¶meters), (override)); + MOCK_METHOD(ble_error_t, destroyAdvertisingSet, (advertising_handle_t handle), (override)); + MOCK_METHOD(ble_error_t, setAdvertisingParameters, (advertising_handle_t handle, const AdvertisingParameters ¶ms), (override)); + MOCK_METHOD(ble_error_t, setAdvertisingPayload, (advertising_handle_t handle, mbed::Span payload), (override)); + MOCK_METHOD(ble_error_t, setAdvertisingScanResponse, (advertising_handle_t handle, mbed::Span response), (override)); + MOCK_METHOD(ble_error_t, startAdvertising, (advertising_handle_t handle, adv_duration_t maxDuration, uint8_t maxEvents), (override)); + MOCK_METHOD(ble_error_t, stopAdvertising, (advertising_handle_t handle), (override)); + MOCK_METHOD(bool, isAdvertisingActive, (advertising_handle_t handle), (override)); + MOCK_METHOD(ble_error_t, setPeriodicAdvertisingParameters, (advertising_handle_t handle, periodic_interval_t periodicAdvertisingIntervalMin, periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower), (override)); + MOCK_METHOD(ble_error_t, setPeriodicAdvertisingPayload, (advertising_handle_t handle, mbed::Span payload), (override)); + MOCK_METHOD(ble_error_t, startPeriodicAdvertising, (advertising_handle_t handle), (override)); + MOCK_METHOD(ble_error_t, stopPeriodicAdvertising, (advertising_handle_t handle), (override)); + MOCK_METHOD(bool, isPeriodicAdvertisingActive, (advertising_handle_t handle), (override)); + MOCK_METHOD(ble_error_t, setScanParameters, (const ScanParameters ¶ms), (override)); + MOCK_METHOD(ble_error_t, startScan, (scan_duration_t duration, duplicates_filter_t filtering, scan_period_t period), (override)); + MOCK_METHOD(ble_error_t, initiate_scan, (), (override)); + MOCK_METHOD(ble_error_t, stopScan, (), (override)); + MOCK_METHOD(ble_error_t, createSync, (peer_address_type_t peerAddressType, const address_t &peerAddress, uint8_t sid, slave_latency_t maxPacketSkip, sync_timeout_t timeout), (override)); + MOCK_METHOD(ble_error_t, createSync, (slave_latency_t maxPacketSkip, sync_timeout_t timeout), (override)); + MOCK_METHOD(ble_error_t, cancelCreateSync, (), (override)); + MOCK_METHOD(ble_error_t, terminateSync, (periodic_sync_handle_t handle), (override)); + MOCK_METHOD(ble_error_t, addDeviceToPeriodicAdvertiserList, (peer_address_type_t peerAddressType, const address_t &peerAddress, advertising_sid_t sid), (override)); + MOCK_METHOD(ble_error_t, removeDeviceFromPeriodicAdvertiserList, (peer_address_type_t peerAddressType, const address_t &peerAddress, advertising_sid_t sid), (override)); + MOCK_METHOD(ble_error_t, clearPeriodicAdvertiserList, (), (override)); + MOCK_METHOD(ble_error_t, connect, (peer_address_type_t peerAddressType, const address_t &peerAddress, const ConnectionParameters &connectionParams), (override)); + MOCK_METHOD(ble_error_t, cancelConnect, (), (override)); + MOCK_METHOD(ble_error_t, updateConnectionParameters, (connection_handle_t connectionHandle, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, slave_latency_t slaveLatency, supervision_timeout_t supervision_timeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength), (override)); + MOCK_METHOD(ble_error_t, manageConnectionParametersUpdateRequest, (bool userManageConnectionUpdateRequest), (override)); + MOCK_METHOD(ble_error_t, acceptConnectionParametersUpdate, (connection_handle_t connectionHandle, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, slave_latency_t slaveLatency, supervision_timeout_t supervision_timeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength), (override)); + MOCK_METHOD(ble_error_t, rejectConnectionParametersUpdate, (connection_handle_t connectionHandle), (override)); + MOCK_METHOD(ble_error_t, disconnect, (connection_handle_t connectionHandle, local_disconnection_reason_t reason), (override)); + MOCK_METHOD(ble_error_t, readPhy, (connection_handle_t connection), (override)); + MOCK_METHOD(ble_error_t, setPreferredPhys, (const phy_set_t *txPhys, const phy_set_t *rxPhys), (override)); + MOCK_METHOD(ble_error_t, setPhy, (connection_handle_t connection, const phy_set_t *txPhys, const phy_set_t *rxPhys, coded_symbol_per_bit_t codedSymbol), (override)); + MOCK_METHOD(ble_error_t, enablePrivacy, (bool enable), (override)); + MOCK_METHOD(ble_error_t, setPeripheralPrivacyConfiguration, (const peripheral_privacy_configuration_t *configuration), (override)); + MOCK_METHOD(ble_error_t, getPeripheralPrivacyConfiguration, (peripheral_privacy_configuration_t *configuration), (override)); + MOCK_METHOD(ble_error_t, setCentralPrivacyConfiguration, (const central_privacy_configuration_t *configuration), (override)); + MOCK_METHOD(ble_error_t, getCentralPrivacyConfiguration, (central_privacy_configuration_t *configuration), (override)); + MOCK_METHOD(uint8_t, getMaxWhitelistSize, (), (const, override)); + MOCK_METHOD(ble_error_t, getWhitelist, (whitelist_t &whitelist), (const, override)); + MOCK_METHOD(ble_error_t, setWhitelist, (const whitelist_t &whitelist), (override)); + MOCK_METHOD(ble_error_t, getAddress, (own_address_type_t &typeP, address_t &address), (override)); + MOCK_METHOD(void, onShutdown, (const GapShutdownCallback_t &callback), (override)); + MOCK_METHOD(GapShutdownCallbackChain_t&, onShutdown, (), (override)); + MOCK_METHOD(ble_error_t, setRandomStaticAddress, (const ble::address_t &address), (override)); + MOCK_METHOD(ble::address_t, getRandomStaticAddress, (), (override)); +}; + +} + +#endif //BLE_GAPMOCK_H diff --git a/UNITTESTS/fakes/ble/GattClientImpl_mock.h b/UNITTESTS/fakes/ble/GattClientImpl_mock.h new file mode 100644 index 00000000000..6150ad1697e --- /dev/null +++ b/UNITTESTS/fakes/ble/GattClientImpl_mock.h @@ -0,0 +1,62 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GATTCLIENTMOCK_H +#define BLE_GATTCLIENTMOCK_H + +#include "gmock/gmock.h" +#include "source/generic/GattClientImpl.h" + +namespace ble { + +class GattClientMock : public ble::impl::GattClient { +public: + GattClientMock() {}; + GattClientMock(const GattClientMock&) = delete; + GattClientMock& operator=(const GattClientMock&) = delete; + virtual ~GattClientMock() {}; + + MOCK_METHOD(ble_error_t, reset, (), (override)); + MOCK_METHOD(void, setEventHandler, (EventHandler *handler), (override)); + MOCK_METHOD(ble_error_t, launchServiceDiscovery, (ble::connection_handle_t connectionHandle, ServiceDiscovery::ServiceCallback_t sc, ServiceDiscovery::CharacteristicCallback_t cc, const UUID &matchingServiceUUID, const UUID &matchingCharacteristicUUIDIn), (override)); + MOCK_METHOD(ble_error_t, discoverServices, (ble::connection_handle_t connectionHandle, ServiceDiscovery::ServiceCallback_t callback, const UUID &matchingServiceUUID), (override)); + MOCK_METHOD(ble_error_t, discoverServices, (ble::connection_handle_t connectionHandle, ServiceDiscovery::ServiceCallback_t callback, GattAttribute::Handle_t startHandle, GattAttribute::Handle_t endHandle), (override)); + MOCK_METHOD(bool, isServiceDiscoveryActive, (), (const, override)); + MOCK_METHOD(void, terminateServiceDiscovery, (), (override)); + MOCK_METHOD(ble_error_t, read, (ble::connection_handle_t connHandle, GattAttribute::Handle_t attributeHandle, uint16_t offset), (const, override)); + MOCK_METHOD(ble_error_t, write, (GattClient::WriteOp_t cmd, ble::connection_handle_t connHandle, GattAttribute::Handle_t attributeHandle, size_t length, const uint8_t *value), (const, override)); + MOCK_METHOD(void, onDataRead, (ReadCallback_t callback), (override)); + MOCK_METHOD(ReadCallbackChain_t&, onDataRead, (), (override)); + MOCK_METHOD(void, onDataWritten, (WriteCallback_t callback), (override)); + MOCK_METHOD(WriteCallbackChain_t&, onDataWritten, (), (override)); + MOCK_METHOD(void, onServiceDiscoveryTermination, (ServiceDiscovery::TerminationCallback_t callback), (override)); + MOCK_METHOD(ble_error_t, discoverCharacteristicDescriptors, (const DiscoveredCharacteristic &characteristic, const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback, const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback), (override)); + MOCK_METHOD(bool, isCharacteristicDescriptorDiscoveryActive, (const DiscoveredCharacteristic &characteristic), (const, override)); + MOCK_METHOD(void, terminateCharacteristicDescriptorDiscovery, (const DiscoveredCharacteristic &characteristic), (override)); + MOCK_METHOD(ble_error_t, negotiateAttMtu, (ble::connection_handle_t connection), (override)); + MOCK_METHOD(void, onHVX, (HVXCallback_t callback), (override)); + MOCK_METHOD(void, onShutdown, (const GattClientShutdownCallback_t &callback), (override)); + MOCK_METHOD(GattClientShutdownCallbackChain_t&, onShutdown, (), (override)); + MOCK_METHOD(HVXCallbackChain_t&, onHVX, (), (override)); + MOCK_METHOD(void, processReadResponse, (const GattReadCallbackParams *params), (override)); + MOCK_METHOD(void, processWriteResponse, (const GattWriteCallbackParams *params), (override)); + MOCK_METHOD(void, processHVXEvent, (const GattHVXCallbackParams *params), (override)); +}; + +} + +#endif //BLE_GATTCLIENTMOCK_H diff --git a/UNITTESTS/fakes/ble/GattServerImpl_mock.h b/UNITTESTS/fakes/ble/GattServerImpl_mock.h new file mode 100644 index 00000000000..bfafb524005 --- /dev/null +++ b/UNITTESTS/fakes/ble/GattServerImpl_mock.h @@ -0,0 +1,105 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GATTSERVERMOCK_H +#define BLE_GATTSERVERMOCK_H + +#include "gmock/gmock.h" +#include "source/GattServerImpl.h" + +namespace ble { + +class GattServerMock : public ble::impl::GattServer { +public: + GattServerMock(); + GattServerMock(const GattServerMock&) = delete; + GattServerMock& operator=(const GattServerMock&) = delete; + virtual ~GattServerMock(); + + MOCK_METHOD(ble_error_t, reset, (ble::GattServer* server), (override)); + MOCK_METHOD(void, setEventHandler, (EventHandler *handler), (override)); + MOCK_METHOD(ble_error_t, addService, (GattService &service), (override)); + MOCK_METHOD(ble_error_t, read, (GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP), (override)); + MOCK_METHOD(ble_error_t, read, (ble::connection_handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP), (override)); + MOCK_METHOD(ble_error_t, write, (GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly), (override)); + MOCK_METHOD(ble_error_t, write, (ble::connection_handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly), (override)); + MOCK_METHOD(ble_error_t, areUpdatesEnabled, (const GattCharacteristic &characteristic, bool *enabledP), (override)); + MOCK_METHOD(ble_error_t, areUpdatesEnabled, (ble::connection_handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP), (override)); + MOCK_METHOD(ble::Gap::PreferredConnectionParams_t, getPreferredConnectionParams, (), (override)); + MOCK_METHOD(void, setPreferredConnectionParams, (const ble::Gap::PreferredConnectionParams_t ¶ms), (override)); + MOCK_METHOD(bool, isOnDataReadAvailable, (), (const, override)); + MOCK_METHOD(void, onDataSent, (const DataSentCallback_t &callback), (override)); + MOCK_METHOD(DataSentCallbackChain_t&, onDataSent, (), (override)); + MOCK_METHOD(void, onDataWritten, (const DataWrittenCallback_t &callback), (override)); + MOCK_METHOD(DataWrittenCallbackChain_t&, onDataWritten, (), (override)); + MOCK_METHOD(ble_error_t, onDataRead, (const DataReadCallback_t &callback), (override)); + MOCK_METHOD(DataReadCallbackChain_t&, onDataRead, (), (override)); + MOCK_METHOD(void, onShutdown, (const GattServerShutdownCallback_t &callback), (override)); + MOCK_METHOD(GattServerShutdownCallbackChain_t&, onShutdown, (), (override)); + MOCK_METHOD(void, onUpdatesEnabled, (EventCallback_t callback), (override)); + MOCK_METHOD(void, onUpdatesDisabled, (EventCallback_t callback), (override)); + MOCK_METHOD(void, onConfirmationReceived, (EventCallback_t callback), (override)); + MOCK_METHOD(void, handleDataWrittenEvent, (const GattWriteCallbackParams *params), (override)); + MOCK_METHOD(void, handleDataReadEvent, (const GattReadCallbackParams *params), (override)); + MOCK_METHOD(void, handleEvent, (GattServerEvents::gattEvent_e type, ble::connection_handle_t connHandle, GattAttribute::Handle_t attributeHandle), (override)); + MOCK_METHOD(void, handleDataSentEvent, (unsigned count), (override)); + + // Fake part + // Descriptor representation of a descriptor registered with ble::test::register_services + struct descriptor_t { + UUID uuid; + ble::attribute_handle_t handle; + ble::att_security_requirement_t read_security = ble::att_security_requirement_t::NONE; + ble::att_security_requirement_t write_security = ble::att_security_requirement_t::NONE; + bool is_readable; + bool is_writable; + std::vector value; // Use capacity to determine the max size. + }; + + // Characteristic representation of a characteristic registered with ble::test::register_services + struct characteristic_t { + UUID uuid; + ble::attribute_handle_t value_handle; + uint8_t properties; + ble::att_security_requirement_t read_security = ble::att_security_requirement_t::NONE; + ble::att_security_requirement_t write_security = ble::att_security_requirement_t::NONE; + ble::att_security_requirement_t update_security = ble::att_security_requirement_t::NONE; + FunctionPointerWithContext + read_cb; + FunctionPointerWithContext + write_cb; + bool has_variable_len; + std::vector value; // Use capacity to determine the max size. + std::vector descriptors; + }; + + // Service representation of a service registered with ble::test::register_services + struct service_t { + UUID uuid; + ble::attribute_handle_t handle; + std::vector characteristics; + }; + + void fake_register_services(GattService& gattService); + + std::vector services; + ble::attribute_handle_t current_handle = 1; +}; + +} + +#endif //BLE_GATTSERVERMOCK_H diff --git a/UNITTESTS/fakes/ble/SecurityManagerImpl_mock.h b/UNITTESTS/fakes/ble/SecurityManagerImpl_mock.h new file mode 100644 index 00000000000..3f1007e4fa5 --- /dev/null +++ b/UNITTESTS/fakes/ble/SecurityManagerImpl_mock.h @@ -0,0 +1,73 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SECURITYMANAGERMOCK_H +#define SECURITYMANAGERMOCK_H + +#include "gmock/gmock.h" +#include "source/generic/SecurityManagerImpl.h" + +namespace ble { + +class SecurityManagerMock : public ble::impl::SecurityManager { +public: + SecurityManagerMock() {}; + SecurityManagerMock(const GattServerMock&) = delete; + SecurityManagerMock& operator=(const GattServerMock&) = delete; + virtual ~SecurityManagerMock() {}; + + MOCK_METHOD(ble_error_t, reset, (), (override)); + MOCK_METHOD(ble_error_t, init, (bool enableBonding, bool requireMITM, SecurityIOCapabilities_t iocaps, const Passkey_t passkey, bool signing, const char *dbFilepath), (override)); + MOCK_METHOD(ble_error_t, setDatabaseFilepath, (const char *dbFilepath), (override)); + MOCK_METHOD(ble_error_t, preserveBondingStateOnReset, (bool enable), (override)); + MOCK_METHOD(ble_error_t, purgeAllBondingState, (), (override)); + MOCK_METHOD(ble_error_t, generateWhitelistFromBondTable, (::ble::whitelist_t *whitelist), (const, override)); + MOCK_METHOD(ble_error_t, requestPairing, (ble::connection_handle_t connectionHandle), (override)); + MOCK_METHOD(ble_error_t, acceptPairingRequest, (ble::connection_handle_t connectionHandle), (override)); + MOCK_METHOD(ble_error_t, cancelPairingRequest, (ble::connection_handle_t connectionHandle), (override)); + MOCK_METHOD(ble_error_t, setPairingRequestAuthorisation, (bool required), (override)); + MOCK_METHOD(ble_error_t, getPeerIdentity, (ble::connection_handle_t connectionHandle), (override)); + MOCK_METHOD(ble_error_t, allowLegacyPairing, (bool allow), (override)); + MOCK_METHOD(ble_error_t, getSecureConnectionsSupport, (bool *enabled), (override)); + MOCK_METHOD(ble_error_t, setIoCapability, (SecurityIOCapabilities_t iocaps), (override)); + MOCK_METHOD(ble_error_t, setDisplayPasskey, (const Passkey_t passkey), (override)); + MOCK_METHOD(ble_error_t, setLinkSecurity, (ble::connection_handle_t connectionHandle, SecurityMode_t securityMode), (override)); + MOCK_METHOD(ble_error_t, setKeypressNotification, (bool enabled), (override)); + MOCK_METHOD(ble_error_t, enableSigning, (ble::connection_handle_t connectionHandle, bool enabled), (override)); + MOCK_METHOD(ble_error_t, setHintFutureRoleReversal, (bool enable), (override)); + MOCK_METHOD(ble_error_t, getLinkEncryption, (ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption), (override)); + MOCK_METHOD(ble_error_t, setLinkEncryption, (ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption), (override)); + MOCK_METHOD(ble_error_t, setEncryptionKeyRequirements, (uint8_t minimumByteSize, uint8_t maximumByteSize), (override)); + MOCK_METHOD(ble_error_t, getEncryptionKeySize, (connection_handle_t connectionHandle, uint8_t *size), (override)); + MOCK_METHOD(ble_error_t, requestAuthentication, (ble::connection_handle_t connectionHandle), (override)); + MOCK_METHOD(ble_error_t, generateOOB, (const ble::address_t *address), (override)); + MOCK_METHOD(ble_error_t, setOOBDataUsage, (ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM), (override)); + MOCK_METHOD(ble_error_t, passkeyEntered, (ble::connection_handle_t connectionHandle, Passkey_t passkey), (override)); + MOCK_METHOD(ble_error_t, legacyPairingOobReceived, (const ble::address_t *address, const ble::oob_tk_t *tk), (override)); + MOCK_METHOD(ble_error_t, confirmationEntered, (ble::connection_handle_t connectionHandle, bool confirmation), (override)); + MOCK_METHOD(ble_error_t, sendKeypressNotification, (ble::connection_handle_t connectionHandle, ble::Keypress_t keypress), (override)); + MOCK_METHOD(ble_error_t, oobReceived, (const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm), (override)); + MOCK_METHOD(ble_error_t, getSigningKey, (ble::connection_handle_t connectionHandle, bool authenticated), (override)); + MOCK_METHOD(ble_error_t, setPrivateAddressTimeout, (uint16_t timeout_in_seconds), (override)); + MOCK_METHOD(void, onShutdown, (const SecurityManagerShutdownCallback_t &callback), (override)); + MOCK_METHOD(SecurityManagerShutdownCallbackChain_t&, onShutdown, (), (override)); + MOCK_METHOD(void, setSecurityManagerEventHandler, (EventHandler *handler), (override)); +}; + +} + +#endif //SECURITYMANAGERMOCK_H diff --git a/UNITTESTS/fakes/ble/ble_mocks.h b/UNITTESTS/fakes/ble/ble_mocks.h new file mode 100644 index 00000000000..efeac598c14 --- /dev/null +++ b/UNITTESTS/fakes/ble/ble_mocks.h @@ -0,0 +1,45 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_MOCKS_H +#define BLE_MOCKS_H + +#include "GattServerImpl_mock.h" +#include "GattClientImpl_mock.h" +#include "GapImpl_mock.h" +#include "SecurityManagerImpl_mock.h" + +/*** + * You must use delete_mocks() at the end of the test. BLE::Instance(), ble::gap() etc. inits the mocks. Do not cache + * pointers between tests. Call BLE::Instance() at the start of the tests, otherwise call init_mocks() yourself. + * To access mocks use: + * gap_mock(), gatt_server_mock(), gatt_client_mock(), security_manager_mock(). + * All functions are in namespace ble. + */ +namespace ble { + +void init_mocks(); +void delete_mocks(); + +GapMock& gap_mock(); +GattServerMock& gatt_server_mock(); +GattClientMock& gatt_client_mock(); +SecurityManagerMock& security_manager_mock(); + +} + +#endif // BLE_MOCKS_H \ No newline at end of file diff --git a/UNITTESTS/fakes/ble/source/GattServerImpl.h b/UNITTESTS/fakes/ble/source/GattServerImpl.h new file mode 100644 index 00000000000..d4b43490d37 --- /dev/null +++ b/UNITTESTS/fakes/ble/source/GattServerImpl.h @@ -0,0 +1,137 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GATTSERVERSTUB_H +#define BLE_GATTSERVERSTUB_H + +#include "ble/GattServer.h" +#include "generic/GattServerEvents.h" +#include "ble/Gap.h" + +namespace ble { +namespace impl { + +class GattServer { +public: + GattServer() {}; + GattServer(const GattServer&) = delete; + GattServer& operator=(const GattServer&) = delete; + virtual ~GattServer() {}; + + using EventHandler = ble::GattServer::EventHandler; + using DataSentCallback_t = ble::GattServer::DataSentCallback_t ; + using DataSentCallbackChain_t = ble::GattServer::DataSentCallbackChain_t ; + using DataWrittenCallback_t = ble::GattServer::DataWrittenCallback_t ; + using DataWrittenCallbackChain_t = ble::GattServer::DataWrittenCallbackChain_t ; + using DataReadCallback_t = ble::GattServer::DataReadCallback_t; + using DataReadCallbackChain_t = ble::GattServer::DataReadCallbackChain_t; + using GattServerShutdownCallback_t = ble::GattServer::GattServerShutdownCallback_t; + using GattServerShutdownCallbackChain_t = ble::GattServer::GattServerShutdownCallbackChain_t; + using EventCallback_t = ble::GattServer::EventCallback_t; + + virtual void setEventHandler(EventHandler *handler) { }; + + virtual ble_error_t reset(ble::GattServer* server) { return BLE_ERROR_NONE; }; + + virtual ble_error_t addService(GattService &service) { return BLE_ERROR_NONE; }; + + virtual ble_error_t read( + GattAttribute::Handle_t attributeHandle, + uint8_t buffer[], + uint16_t *lengthP + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t read( + ble::connection_handle_t connectionHandle, + GattAttribute::Handle_t attributeHandle, + uint8_t *buffer, + uint16_t *lengthP + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t write( + GattAttribute::Handle_t attributeHandle, + const uint8_t *value, + uint16_t size, + bool localOnly = false + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t write( + ble::connection_handle_t connectionHandle, + GattAttribute::Handle_t attributeHandle, + const uint8_t *value, + uint16_t size, + bool localOnly = false + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t areUpdatesEnabled( + const GattCharacteristic &characteristic, + bool *enabledP + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t areUpdatesEnabled( + ble::connection_handle_t connectionHandle, + const GattCharacteristic &characteristic, + bool *enabledP + ) { return BLE_ERROR_NONE; }; + + virtual ble::Gap::PreferredConnectionParams_t getPreferredConnectionParams() { + ble::Gap::PreferredConnectionParams_t params = {0}; return params; + }; + + virtual void setPreferredConnectionParams(const ble::Gap::PreferredConnectionParams_t ¶ms) { }; + + virtual bool isOnDataReadAvailable() const { return true; }; + + virtual void onDataSent(const DataSentCallback_t &callback) { }; + + virtual DataSentCallbackChain_t &onDataSent() { static DataSentCallbackChain_t chain; return chain; }; + + virtual void onDataWritten(const DataWrittenCallback_t &callback) { }; + + virtual DataWrittenCallbackChain_t &onDataWritten() { static DataWrittenCallbackChain_t chain; return chain; }; + + virtual ble_error_t onDataRead(const DataReadCallback_t &callback) { return BLE_ERROR_NONE; }; + + virtual DataReadCallbackChain_t &onDataRead() { static DataReadCallbackChain_t chain; return chain; }; + + virtual void onShutdown(const GattServerShutdownCallback_t &callback) { }; + + virtual GattServerShutdownCallbackChain_t &onShutdown() { static GattServerShutdownCallbackChain_t chain; return chain; }; + + virtual void onUpdatesEnabled(EventCallback_t callback) { }; + + virtual void onUpdatesDisabled(EventCallback_t callback) { }; + + virtual void onConfirmationReceived(EventCallback_t callback) { }; + + virtual void handleDataWrittenEvent(const GattWriteCallbackParams *params) { }; + + virtual void handleDataReadEvent(const GattReadCallbackParams *params) { }; + + virtual void handleEvent( + GattServerEvents::gattEvent_e type, + ble::connection_handle_t connHandle, + GattAttribute::Handle_t attributeHandle + ) { }; + + virtual void handleDataSentEvent(unsigned count) { }; +}; + +} +} + +#endif //BLE_GATTSERVERSTUB_H diff --git a/UNITTESTS/fakes/ble/source/GattServerImpl_mock.cpp b/UNITTESTS/fakes/ble/source/GattServerImpl_mock.cpp new file mode 100644 index 00000000000..baf6d0c8a6f --- /dev/null +++ b/UNITTESTS/fakes/ble/source/GattServerImpl_mock.cpp @@ -0,0 +1,96 @@ +/* mbed Microcontroller Library + * Copyright (c) 2021 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "GattServerImpl_mock.h" + +namespace ble { + +GattServerMock::GattServerMock() +{ + ON_CALL(*this, addService).WillByDefault([this](GattService &service) { + // Fake registration, it populates the handles of the input and store its + // representation in the services field. + fake_register_services(service); + return BLE_ERROR_NONE; + }); +} + +GattServerMock::~GattServerMock() {}; + +void GattServerMock::fake_register_services(GattService& gattService) +{ + gattService.setHandle(current_handle++); + service_t result { + gattService.getUUID(), + gattService.getHandle() + }; + + for (size_t i = 0; i < gattService.getCharacteristicCount(); ++i) { + current_handle++; // Increment for the characteristic declaration handle + auto& ref = *gattService.getCharacteristic(i); + ref.getValueAttribute().setHandle(current_handle++); + + characteristic_t c; + c.uuid = ref.getValueAttribute().getUUID(); + c.value_handle = ref.getValueHandle(); + c.properties = ref.getProperties(); + c.read_security = ref.getReadSecurityRequirement(); + c.write_security = ref.getWriteSecurityRequirement(); + c.update_security = ref.getUpdateSecurityRequirement(); + c.read_cb = ref.getReadAuthorizationCallback(); + c.write_cb = ref.getWriteAuthorizationCallback(); + c.value.reserve(ref.getValueAttribute().getMaxLength()); + c.value.resize(ref.getValueAttribute().getLength()); + { + auto value_ptr = ref.getValueAttribute().getValuePtr(); + if (value_ptr) { + std::copy(value_ptr, value_ptr + c.value.size(), c.value.begin()); + } + } + c.has_variable_len = ref.getValueAttribute().hasVariableLength(); + + for (size_t j = 0; j < ref.getDescriptorCount(); ++j) { + auto& ref_desc = *ref.getDescriptor(j); + ref_desc.setHandle(current_handle++); + + descriptor_t d; + d.uuid = ref_desc.getUUID(); + d.handle = ref_desc.getHandle(); + d.read_security = ref_desc.getReadSecurityRequirement(); + d.write_security = ref_desc.getWriteSecurityRequirement(); + d.is_readable = ref_desc.isReadAllowed(); + d.is_writable = ref_desc.isWriteAllowed(); + d.value.reserve(ref_desc.getMaxLength()); + d.value.resize(ref_desc.getLength()); + { + auto value_ptr = ref_desc.getValuePtr(); + if (value_ptr) { + std::copy(value_ptr, value_ptr + d.value.size(), d.value.begin()); + } + } + + c.descriptors.push_back(d); + } + + result.characteristics.push_back(c); + } + + services.push_back(result); +} + + +} diff --git a/UNITTESTS/fakes/ble/source/generic/GapImpl.h b/UNITTESTS/fakes/ble/source/generic/GapImpl.h new file mode 100644 index 00000000000..6cd3bbf41f9 --- /dev/null +++ b/UNITTESTS/fakes/ble/source/generic/GapImpl.h @@ -0,0 +1,317 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GAPSTUB_H +#define BLE_GAPSTUB_H + +namespace ble { +namespace impl { + +class Gap { +public: + Gap() {}; + Gap(const Gap&) = delete; + Gap& operator=(const Gap&) = delete; + virtual ~Gap() {}; + + using EventHandler = ::ble::Gap::EventHandler; + using GapShutdownCallback_t = ::ble::Gap::GapShutdownCallback_t; + using GapShutdownCallbackChain_t = ::ble::Gap::GapShutdownCallbackChain_t ; + using PreferredConnectionParams_t = ::ble::Gap::PreferredConnectionParams_t ; + +#if BLE_FEATURE_PRIVACY +#if BLE_ROLE_BROADCASTER + static const peripheral_privacy_configuration_t default_peripheral_privacy_configuration; +#endif // BLE_ROLE_BROADCASTER + +#if BLE_ROLE_OBSERVER + /** + * Default peripheral privacy configuration. + */ + static const central_privacy_configuration_t default_central_privacy_configuration; +#endif // BLE_ROLE_OBSERVER +#endif // BLE_FEATURE_PRIVACY + +public: + virtual void setEventHandler(EventHandler *handler) { }; + + virtual bool isFeatureSupported(controller_supported_features_t feature) { return true; }; + + /* advertising */ +#if BLE_ROLE_BROADCASTER + + virtual uint8_t getMaxAdvertisingSetNumber() { return 1; }; + + virtual uint16_t getMaxAdvertisingDataLength() { return 23; }; + + virtual uint16_t getMaxConnectableAdvertisingDataLength() { return 21; }; + + virtual uint16_t getMaxActiveSetAdvertisingDataLength() { return 21; }; + +#if BLE_FEATURE_EXTENDED_ADVERTISING + + virtual ble_error_t createAdvertisingSet( + advertising_handle_t *handle, + const AdvertisingParameters ¶meters + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t destroyAdvertisingSet(advertising_handle_t handle) { return BLE_ERROR_NONE; }; + +#endif // BLE_FEATURE_EXTENDED_ADVERTISING + + virtual ble_error_t setAdvertisingParameters( + advertising_handle_t handle, + const AdvertisingParameters ¶ms + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setAdvertisingPayload( + advertising_handle_t handle, + mbed::Span payload + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setAdvertisingScanResponse( + advertising_handle_t handle, + mbed::Span response + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t startAdvertising( + advertising_handle_t handle, + adv_duration_t maxDuration = adv_duration_t::forever(), + uint8_t maxEvents = 0 + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t stopAdvertising(advertising_handle_t handle) { return BLE_ERROR_NONE; }; + + virtual bool isAdvertisingActive(advertising_handle_t handle) { return true; }; + +#endif // BLE_ROLE_BROADCASTER + +#if BLE_ROLE_BROADCASTER +#if BLE_FEATURE_PERIODIC_ADVERTISING + + virtual ble_error_t setPeriodicAdvertisingParameters( + advertising_handle_t handle, + periodic_interval_t periodicAdvertisingIntervalMin, + periodic_interval_t periodicAdvertisingIntervalMax, + bool advertiseTxPower = true + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setPeriodicAdvertisingPayload( + advertising_handle_t handle, + mbed::Span payload + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t startPeriodicAdvertising(advertising_handle_t handle) { return BLE_ERROR_NONE; }; + + virtual ble_error_t stopPeriodicAdvertising(advertising_handle_t handle) { return BLE_ERROR_NONE; }; + + virtual bool isPeriodicAdvertisingActive(advertising_handle_t handle) { return true; }; + +#endif // BLE_ROLE_BROADCASTER +#endif // BLE_FEATURE_PERIODIC_ADVERTISING + + /* scanning */ +#if BLE_ROLE_OBSERVER + + virtual ble_error_t setScanParameters(const ScanParameters ¶ms) { return BLE_ERROR_NONE; }; + + virtual ble_error_t startScan( + scan_duration_t duration = scan_duration_t::forever(), + duplicates_filter_t filtering = duplicates_filter_t::DISABLE, + scan_period_t period = scan_period_t(0) + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t initiate_scan() { return BLE_ERROR_NONE; }; + + virtual ble_error_t stopScan() { return BLE_ERROR_NONE; }; + +#endif // BLE_ROLE_OBSERVER + +#if BLE_ROLE_OBSERVER +#if BLE_FEATURE_PERIODIC_ADVERTISING + + virtual ble_error_t createSync( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + uint8_t sid, + slave_latency_t maxPacketSkip, + sync_timeout_t timeout + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t createSync( + slave_latency_t maxPacketSkip, + sync_timeout_t timeout + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t cancelCreateSync() { return BLE_ERROR_NONE; }; + + virtual ble_error_t terminateSync(periodic_sync_handle_t handle) { return BLE_ERROR_NONE; }; + + virtual ble_error_t addDeviceToPeriodicAdvertiserList( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t clearPeriodicAdvertiserList() { return BLE_ERROR_NONE; }; + + uint8_t getMaxPeriodicAdvertiserListSize() { return 1; }; + +#endif // BLE_ROLE_OBSERVER +#endif // BLE_FEATURE_PERIODIC_ADVERTISING + +#if BLE_ROLE_CENTRAL + + virtual ble_error_t connect( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + const ConnectionParameters &connectionParams + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t cancelConnect() { return BLE_ERROR_NONE; }; + +#endif // BLE_ROLE_CENTRAL + +#if BLE_FEATURE_CONNECTABLE + + virtual ble_error_t updateConnectionParameters( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervision_timeout, + conn_event_length_t minConnectionEventLength = conn_event_length_t(0), + conn_event_length_t maxConnectionEventLength = conn_event_length_t(0) + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t manageConnectionParametersUpdateRequest( + bool userManageConnectionUpdateRequest + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t acceptConnectionParametersUpdate( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervision_timeout, + conn_event_length_t minConnectionEventLength = conn_event_length_t(0), + conn_event_length_t maxConnectionEventLength = conn_event_length_t(0) + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t rejectConnectionParametersUpdate( + connection_handle_t connectionHandle + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t disconnect( + connection_handle_t connectionHandle, + local_disconnection_reason_t reason + ) { return BLE_ERROR_NONE; }; + +#endif // BLE_FEATURE_CONNECTABLE +#if BLE_FEATURE_PHY_MANAGEMENT + + virtual ble_error_t readPhy(connection_handle_t connection) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setPreferredPhys( + const phy_set_t *txPhys, + const phy_set_t *rxPhys + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setPhy( + connection_handle_t connection, + const phy_set_t *txPhys, + const phy_set_t *rxPhys, + coded_symbol_per_bit_t codedSymbol + ) { return BLE_ERROR_NONE; }; + +#endif // BLE_FEATURE_PHY_MANAGEMENT + +#if BLE_FEATURE_PRIVACY + + virtual ble_error_t enablePrivacy(bool enable) { return BLE_ERROR_NONE; }; + +#if BLE_ROLE_BROADCASTER + + virtual ble_error_t setPeripheralPrivacyConfiguration( + const peripheral_privacy_configuration_t *configuration + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t getPeripheralPrivacyConfiguration( + peripheral_privacy_configuration_t *configuration + ) { return BLE_ERROR_NONE; }; + +#endif // BLE_ROLE_BROADCASTER + +#if BLE_ROLE_OBSERVER + + virtual ble_error_t setCentralPrivacyConfiguration( + const central_privacy_configuration_t *configuration + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t getCentralPrivacyConfiguration( + central_privacy_configuration_t *configuration + ) { return BLE_ERROR_NONE; }; + +#endif // BLE_ROLE_OBSERVER +#endif // BLE_FEATURE_PRIVACY + +#if BLE_FEATURE_WHITELIST + + virtual uint8_t getMaxWhitelistSize() const { return 1; }; + + virtual ble_error_t getWhitelist(whitelist_t &whitelist) const { return BLE_ERROR_NONE; }; + + virtual ble_error_t setWhitelist(const whitelist_t &whitelist) { return BLE_ERROR_NONE; }; + +#endif // BLE_FEATURE_WHITELIST + + virtual ble_error_t getAddress( + own_address_type_t &typeP, + address_t &address + ) { return BLE_ERROR_NONE; }; + + static ble_error_t getRandomAddressType( + ble::address_t address, + ble::random_address_type_t *addressType + ) { return BLE_ERROR_NONE;}; + + virtual ble_error_t reset() { return BLE_ERROR_NONE; }; + + virtual void onShutdown(const GapShutdownCallback_t &callback) { }; + + virtual GapShutdownCallbackChain_t &onShutdown() { static GapShutdownCallbackChain_t chain; return chain; }; + + /* + * API reserved for the controller driver to set the random static address. + * Setting a new random static address while the controller is operating is + * forbidden by the Bluetooth specification. + */ + virtual ble_error_t setRandomStaticAddress(const ble::address_t &address) { return BLE_ERROR_NONE; }; + + virtual ble::address_t getRandomStaticAddress() { return ble::address_t(); }; +}; + +} +} + +#endif //BLE_GAPSTUB_H diff --git a/UNITTESTS/fakes/ble/source/generic/GattClientImpl.h b/UNITTESTS/fakes/ble/source/generic/GattClientImpl.h new file mode 100644 index 00000000000..2795ffeec9e --- /dev/null +++ b/UNITTESTS/fakes/ble/source/generic/GattClientImpl.h @@ -0,0 +1,133 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GATTCLIENTSTUB_H +#define BLE_GATTCLIENTSTUB_H + +#include "events/EventQueue.h" + +namespace ble { +namespace impl { + +class GattClient { +public: + using EventHandler = ble::GattClient::EventHandler; + using WriteOp_t = ble::GattClient::WriteOp_t; + using HVXCallback_t = ble::GattClient::HVXCallback_t ; + using GattClientShutdownCallback_t = ble::GattClient::GattClientShutdownCallback_t ; + using GattClientShutdownCallbackChain_t = ble::GattClient::GattClientShutdownCallbackChain_t ; + using HVXCallbackChain_t = ble::GattClient::HVXCallbackChain_t ; + using ReadCallbackChain_t = ble::GattClient::ReadCallbackChain_t ; + using WriteCallbackChain_t = ble::GattClient::WriteCallbackChain_t ; + + GattClient() {}; + GattClient(const GattClient&) = delete; + GattClient& operator=(const GattClient&) = delete; + virtual ~GattClient() {}; + + virtual void setEventHandler(EventHandler *handler) { }; + + virtual ble_error_t launchServiceDiscovery( + ble::connection_handle_t connectionHandle, + ServiceDiscovery::ServiceCallback_t sc = nullptr, + ServiceDiscovery::CharacteristicCallback_t cc = nullptr, + const UUID &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN), + const UUID &matchingCharacteristicUUIDIn = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN) + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t discoverServices( + ble::connection_handle_t connectionHandle, + ServiceDiscovery::ServiceCallback_t callback, + const UUID &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN) + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t discoverServices( + ble::connection_handle_t connectionHandle, + ServiceDiscovery::ServiceCallback_t callback, + GattAttribute::Handle_t startHandle, + GattAttribute::Handle_t endHandle + ) { return BLE_ERROR_NONE; }; + + virtual bool isServiceDiscoveryActive(void) const { return true; }; + + virtual void terminateServiceDiscovery(void) { }; + + virtual ble_error_t read( + ble::connection_handle_t connHandle, + GattAttribute::Handle_t attributeHandle, + uint16_t offset + ) const { return BLE_ERROR_NONE; }; + + virtual ble_error_t write( + GattClient::WriteOp_t cmd, + ble::connection_handle_t connHandle, + GattAttribute::Handle_t attributeHandle, + size_t length, + const uint8_t *value + ) const { return BLE_ERROR_NONE; }; + + /* Event callback handlers. */ + + virtual void onDataRead(ReadCallback_t callback) { }; + + virtual ReadCallbackChain_t &onDataRead() { static ReadCallbackChain_t chain; return chain; }; + + virtual void onDataWritten(WriteCallback_t callback) { }; + + virtual WriteCallbackChain_t &onDataWritten() { static WriteCallbackChain_t chain; return chain; }; + + virtual void onServiceDiscoveryTermination( + ServiceDiscovery::TerminationCallback_t callback + ) { }; + + virtual ble_error_t discoverCharacteristicDescriptors( + const DiscoveredCharacteristic &characteristic, + const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback, + const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback + ) { return BLE_ERROR_NONE; }; + + virtual bool isCharacteristicDescriptorDiscoveryActive( + const DiscoveredCharacteristic &characteristic + ) const { return true; }; + + virtual void terminateCharacteristicDescriptorDiscovery( + const DiscoveredCharacteristic &characteristic + ) { }; + + virtual ble_error_t negotiateAttMtu(ble::connection_handle_t connection) { return BLE_ERROR_NONE; }; + + virtual void onHVX(HVXCallback_t callback) { }; + + virtual void onShutdown(const GattClientShutdownCallback_t &callback) { }; + + virtual GattClientShutdownCallbackChain_t &onShutdown() { static GattClientShutdownCallbackChain_t chain; return chain; }; + + virtual HVXCallbackChain_t &onHVX() { static HVXCallbackChain_t chain; return chain; }; + + virtual ble_error_t reset(void) { return BLE_ERROR_NONE; }; + + virtual void processReadResponse(const GattReadCallbackParams *params) { }; + + virtual void processWriteResponse(const GattWriteCallbackParams *params) { }; + + virtual void processHVXEvent(const GattHVXCallbackParams *params) { }; +}; + +} +} + +#endif //BLE_GATTCLIENTSTUB_H diff --git a/UNITTESTS/fakes/ble/source/generic/SecurityManagerImpl.h b/UNITTESTS/fakes/ble/source/generic/SecurityManagerImpl.h new file mode 100644 index 00000000000..35e4de51178 --- /dev/null +++ b/UNITTESTS/fakes/ble/source/generic/SecurityManagerImpl.h @@ -0,0 +1,186 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SECURITYMANAGERSTUB_H +#define SECURITYMANAGERSTUB_H + +namespace ble { +namespace impl { + +class SecurityManager { +public: + SecurityManager() {}; + SecurityManager(const SecurityManager&) = delete; + SecurityManager& operator=(const SecurityManager&) = delete; + virtual ~SecurityManager() {}; + + using SecurityIOCapabilities_t = ble::SecurityManager::SecurityIOCapabilities_t; + using SecurityMode_t = ble::SecurityManager::SecurityMode_t; + using SecurityManagerShutdownCallback_t = ble::SecurityManager::SecurityManagerShutdownCallback_t; + using SecurityManagerShutdownCallbackChain_t = ble::SecurityManager::SecurityManagerShutdownCallbackChain_t; + using EventHandler = ble::SecurityManager::EventHandler; + using Passkey_t = ble::SecurityManager::Passkey_t ; + + static auto constexpr IO_CAPS_NONE = ble::SecurityManager::IO_CAPS_NONE; + + virtual ble_error_t init( + bool enableBonding = true, + bool requireMITM = true, + SecurityIOCapabilities_t iocaps = IO_CAPS_NONE, + const Passkey_t passkey = nullptr, + bool signing = true, + const char *dbFilepath = nullptr + ) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setDatabaseFilepath(const char *dbFilepath = nullptr) { return BLE_ERROR_NONE; }; + + virtual ble_error_t reset() { return BLE_ERROR_NONE; }; + + virtual ble_error_t preserveBondingStateOnReset(bool enable) { return BLE_ERROR_NONE; }; + + //////////////////////////////////////////////////////////////////////////// + // List management + // + + virtual ble_error_t purgeAllBondingState() { return BLE_ERROR_NONE; }; + + virtual ble_error_t generateWhitelistFromBondTable(::ble::whitelist_t *whitelist) const { return BLE_ERROR_NONE; }; + + //////////////////////////////////////////////////////////////////////////// + // Pairing + // + +#if BLE_ROLE_CENTRAL + virtual ble_error_t requestPairing(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; }; +#endif // BLE_ROLE_CENTRAL + +#if BLE_ROLE_PERIPHERAL + virtual ble_error_t acceptPairingRequest(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; }; +#endif // BLE_ROLE_PERIPHERAL + + virtual ble_error_t cancelPairingRequest(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setPairingRequestAuthorisation(bool required = true) { return BLE_ERROR_NONE; }; + + virtual ble_error_t getPeerIdentity(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; }; + + //////////////////////////////////////////////////////////////////////////// + // Feature support + // +#if BLE_FEATURE_SECURE_CONNECTIONS + virtual ble_error_t allowLegacyPairing(bool allow = true) { return BLE_ERROR_NONE; }; + + virtual ble_error_t getSecureConnectionsSupport(bool *enabled) { return BLE_ERROR_NONE; }; +#endif // BLE_FEATURE_SECURE_CONNECTIONS + + //////////////////////////////////////////////////////////////////////////// + // Security settings + // + + virtual ble_error_t setIoCapability(SecurityIOCapabilities_t iocaps) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setDisplayPasskey(const Passkey_t passkey) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setLinkSecurity(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setKeypressNotification(bool enabled = true) { return BLE_ERROR_NONE; }; + +#if BLE_FEATURE_SIGNING + + virtual ble_error_t enableSigning(ble::connection_handle_t connectionHandle, bool enabled = true) { return BLE_ERROR_NONE; }; + +#endif // BLE_FEATURE_SIGNING + + virtual ble_error_t setHintFutureRoleReversal(bool enable = true) { return BLE_ERROR_NONE; }; + + //////////////////////////////////////////////////////////////////////////// + // Encryption + // + + virtual ble_error_t getLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setEncryptionKeyRequirements(uint8_t minimumByteSize, uint8_t maximumByteSize) { return BLE_ERROR_NONE; }; + + virtual ble_error_t getEncryptionKeySize( + connection_handle_t connectionHandle, + uint8_t *size + ) { return BLE_ERROR_NONE; }; + + //////////////////////////////////////////////////////////////////////////// + // Authentication + // + + virtual ble_error_t requestAuthentication(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; }; + + //////////////////////////////////////////////////////////////////////////// + // MITM + // + + virtual ble_error_t generateOOB(const ble::address_t *address) { return BLE_ERROR_NONE; }; + + virtual ble_error_t setOOBDataUsage(ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM = true) { return BLE_ERROR_NONE; }; + + virtual ble_error_t passkeyEntered(ble::connection_handle_t connectionHandle, Passkey_t passkey) { return BLE_ERROR_NONE; }; + + virtual ble_error_t legacyPairingOobReceived(const ble::address_t *address, const ble::oob_tk_t *tk) { return BLE_ERROR_NONE; }; +#if BLE_FEATURE_SECURE_CONNECTIONS + virtual ble_error_t confirmationEntered(ble::connection_handle_t connectionHandle, bool confirmation) { return BLE_ERROR_NONE; }; + + virtual ble_error_t sendKeypressNotification(ble::connection_handle_t connectionHandle, ble::Keypress_t keypress) { return BLE_ERROR_NONE; }; + + virtual ble_error_t oobReceived( + const ble::address_t *address, + const ble::oob_lesc_value_t *random, + const ble::oob_confirm_t *confirm + ) { return BLE_ERROR_NONE; }; +#endif // BLE_FEATURE_SECURE_CONNECTIONS + + //////////////////////////////////////////////////////////////////////////// + // Keys + // +#if BLE_FEATURE_SIGNING + virtual ble_error_t getSigningKey(ble::connection_handle_t connectionHandle, bool authenticated) { return BLE_ERROR_NONE; }; +#endif // BLE_FEATURE_SIGNING + //////////////////////////////////////////////////////////////////////////// + // Privacy + // + +#if BLE_FEATURE_PRIVACY + virtual ble_error_t setPrivateAddressTimeout( + uint16_t timeout_in_seconds + ) { return BLE_ERROR_NONE; }; +#endif // BLE_FEATURE_PRIVACY + + /* Event callback handlers. */ +public: + + virtual void onShutdown(const SecurityManagerShutdownCallback_t &callback) { }; + + template + void onShutdown(T *objPtr, void (T::*memberPtr)(const SecurityManager *)) { }; + + virtual SecurityManagerShutdownCallbackChain_t &onShutdown() { static SecurityManagerShutdownCallbackChain_t chain; return chain; }; + + virtual void setSecurityManagerEventHandler(EventHandler *handler) { }; +}; + +} +} + +#endif //SECURITYMANAGERSTUB_H diff --git a/UNITTESTS/fakes/events/CMakeLists.txt b/UNITTESTS/fakes/events/CMakeLists.txt new file mode 100644 index 00000000000..e50f30ac10f --- /dev/null +++ b/UNITTESTS/fakes/events/CMakeLists.txt @@ -0,0 +1,20 @@ +# Copyright (c) 2020 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-fakes-event-queue) + +target_sources(mbed-fakes-event-queue + PRIVATE + events/EventQueue.cpp +) + +target_include_directories(mbed-fakes-event-queue + PUBLIC + . +) + +target_link_libraries(mbed-fakes-event-queue + PRIVATE + mbed-headers + gcov +) diff --git a/UNITTESTS/fakes/events/events/EventQueue.cpp b/UNITTESTS/fakes/events/events/EventQueue.cpp new file mode 100644 index 00000000000..4f937c240cb --- /dev/null +++ b/UNITTESTS/fakes/events/events/EventQueue.cpp @@ -0,0 +1,120 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "EventQueue.h" + +namespace events { + +handle_t EventQueue::call_handler(function_t handler) +{ + return call_handler_in(0, handler); +} + +handle_t EventQueue::call_handler_in(tick_t ms, function_t handler) +{ + _handler_id++; + + _handlers.push_back( + internal_event{ + std::unique_ptr(new function_t(handler)), + _now + ms, + _handler_id + } + ); + + return _handler_id; +} + +bool EventQueue::cancel_handler(handle_t handle) +{ + if (!handle) { + return false; + } + + auto found = std::remove_if( + _handlers.begin(), + _handlers.end(), + [handle](internal_event& element) -> bool { + return (handle == element.handle); + } + ); + + if (found != _handlers.end()) { + _handlers.erase( + found, + _handlers.end() + ); + return true; + } + + return false; +} + +void EventQueue::process_events(tick_t duration_ms) +{ + // execute all events during the duration + for (uint64_t i = 0; i < duration_ms; ++i) { + process_events(); + _now++; + } + + // last round to execute immediate events + process_events(); +} + +void EventQueue::process_events() { + while (true) { + if (_handlers.empty()) { + return; + } + + /* to guarantee order we only dispatch one tick at a time*/ + auto smallest = std::min_element( + _handlers.begin(), + _handlers.end(), + [](internal_event& element, internal_event& smallest){ + return (element.tick < smallest.tick); + } + ); + tick_t earliest_tick = smallest->tick; + + /* stop if all elements happen later */ + if (earliest_tick > _now) { + return; + } + + /* dispatch all handlers that happen at this time */ + auto found = std::remove_if( + _handlers.begin(), + _handlers.end(), + [earliest_tick](internal_event& element) -> bool { + if (earliest_tick >= element.tick) { + (*(element.handler))(); + return true; + } else { + return false; + } + } + ); + + if (found != _handlers.end()) { + _handlers.erase(found, _handlers.end()); + } + } +} + +} diff --git a/UNITTESTS/fakes/events/events/EventQueue.h b/UNITTESTS/fakes/events/events/EventQueue.h new file mode 100644 index 00000000000..6958298654f --- /dev/null +++ b/UNITTESTS/fakes/events/events/EventQueue.h @@ -0,0 +1,137 @@ +/* mbed Microcontroller Library + * Copyright (c) 2020 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef EVENTQUEUE_FAKE_H +#define EVENTQUEUE_FAKE_H + +#include +#include +#include +#include +#include +#include "events/EventQueue.h" +#include +#include + +namespace events { + +typedef int handle_t; +typedef std::function function_t; +typedef unsigned tick_t; + +class EventQueue { + using duration = std::chrono::duration; + +public: + EventQueue(unsigned size = 0, unsigned char *buffer = NULL) { delete buffer; }; + + ~EventQueue() { }; + + /** This will advence time by given amount of milliseonds and then dispatch all events that were set to happen in that time. + * + * @param ms number of miliseconds to advance time + */ + void dispatch(int milliseconds = -1) { + if (milliseconds > 0) { + process_events(milliseconds); + } else { + _now = (tick_t)-1; + process_events(); + _now = 0; + } + }; + + tick_t tick() { + return _now; + }; + + bool cancel(handle_t id) { + return cancel_handler(id); + }; + + /** Get number of events in queue. + * + * @return Number of events waiting in the queue. + */ + size_t size() const { + return _handlers.size(); + } + + template + handle_t call(F f, ArgTs... args) { + return call_handler( + [f, args = mstd::make_tuple(args...)]() { + mstd::apply(f, args); + } + ); + } + + template + handle_t call_in(duration ms, F f, ArgTs... args) { + return call_handler_in( + ms.count(), + [f, args = mstd::make_tuple(args...)]() { + mstd::apply(f, args); + } + ); + } + + template + int call(T *obj, R(T::*method)(ArgTs...), ArgTs... args) { + return call_handler( + [obj, method, args = mstd::make_tuple(args...)]() { + mstd::apply(method, obj, args); + } + ); + } + + template + int call_in(duration ms, T *obj, R(T::*method)(ArgTs...), ArgTs... args) { + return call_handler_in( + ms.count(), + [obj, method, args = mstd::make_tuple(args...)]() { + mstd::apply(method, obj, args); + } + ); + } + +private: + handle_t call_handler(function_t handler); + + handle_t call_handler_in(tick_t ms, function_t handler); + + bool cancel_handler(handle_t handle); + + void process_events(tick_t duration_ms); + + void process_events(); + +private: + struct internal_event { + std::unique_ptr handler; + tick_t tick; + handle_t handle; + }; + + std::vector _handlers; + tick_t _now = 0; + handle_t _handler_id = 0; +}; + +} + +#endif //EVENTQUEUE_FAKE_H diff --git a/UNITTESTS/stubs/CMakeLists.txt b/UNITTESTS/stubs/CMakeLists.txt new file mode 100644 index 00000000000..2c196e66c32 --- /dev/null +++ b/UNITTESTS/stubs/CMakeLists.txt @@ -0,0 +1,145 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-headers INTERFACE) +add_library(mbed-headers INTERFACE) +add_library(mbed-headers-base INTERFACE) +add_library(mbed-headers-platform INTERFACE) +add_library(mbed-headers-connectivity INTERFACE) +add_library(mbed-headers-storage INTERFACE) +add_library(mbed-headers-drivers INTERFACE) +add_library(mbed-headers-hal INTERFACE) +add_library(mbed-headers-events INTERFACE) +add_library(mbed-headers-rtos INTERFACE) + +target_link_libraries(mbed-headers + INTERFACE + mbed-headers-base + mbed-headers-platform + mbed-headers-connectivity + mbed-headers-storage + mbed-headers-drivers + mbed-headers-hal + mbed-headers-events + mbed-headers-rtos +) + +target_include_directories(mbed-headers-platform + INTERFACE + ${MBED_PATH}/platform/include + ${MBED_PATH}/platform/include/platform + ${MBED_PATH}/platform/randlib/include/mbed-client-randlib/ + ${MBED_PATH}/platform/randlib/include/ + ${MBED_PATH}/platform/mbed-trace/include +) + +target_include_directories(mbed-headers-base + INTERFACE + ${MBED_PATH}/UNITTESTS/target_h + ${MBED_PATH}/UNITTESTS/target_h/platform + ${MBED_PATH}/UNITTESTS/target_h/platform/cxxsupport + ${MBED_PATH}/UNITTESTS/target_h/drivers + ${MBED_PATH}/UNITTESTS/target_h/rtos/include + ${MBED_PATH}/UNITTESTS/target_h/rtos + ${MBED_PATH}/UNITTESTS/target_h/sys +) + +target_include_directories(mbed-headers-storage + INTERFACE + ${MBED_PATH}/storage/filesystem/fat/include + ${MBED_PATH}/storage/filesystem/fat/ChaN + ${MBED_PATH}/storage/filesystem/littlefs/include + ${MBED_PATH}/storage/filesystem/littlefsv2/littlefs + ${MBED_PATH}/storage/filesystem/littlefsv2/littlefs/bd + ${MBED_PATH}/storage/filesystem/littlefs/littlefs + ${MBED_PATH}/storage/blockdevice/include + ${MBED_PATH}/storage/filesystem/include + ${MBED_PATH}/storage/kvstore/include + ${MBED_PATH}/storage/kvstore/kv_config + ${MBED_PATH}/storage/kvstore/kv_config/include + ${MBED_PATH}/storage/kvstore/tdbstore/include + ${MBED_PATH}/storage/kvstore/filesystemstore/include + ${MBED_PATH}/storage/kvstore/kvstore_global_api/include + ${MBED_PATH}/storage/blockdevice/include/blockdevice +) + +target_include_directories(mbed-headers-connectivity + INTERFACE + ${MBED_PATH}/connectivity/libraries/nanostack-libservice + ${MBED_PATH}/connectivity/libraries/nanostack-libservice/mbed-client-libservice + ${MBED_PATH}/connectivity/netsocket/include + ${MBED_PATH}/connectivity/cellular/include/cellular/framework/API + ${MBED_PATH}/connectivity/cellular/include/cellular/framework/AT + ${MBED_PATH}/connectivity/cellular/include/cellular/framework/device + ${MBED_PATH}/connectivity/cellular/include/cellular/framework + ${MBED_PATH}/connectivity/cellular/include/cellular/framework/common + ${MBED_PATH}/connectivity + ${MBED_PATH}/connectivity/lorawan/include/lorawan + ${MBED_PATH}/connectivity/lorawan/lorastack + ${MBED_PATH}/connectivity/lorawan/lorastack/mac + ${MBED_PATH}/connectivity/lorawan/lorastack/phy + ${MBED_PATH}/connectivity/lorawan + ${MBED_PATH}/connectivity/mbedtls + ${MBED_PATH}/connectivity/mbedtls/include + ${MBED_PATH}/connectivity/FEATURE_BLE/include + ${MBED_PATH}/connectivity/FEATURE_BLE/include/ble +) + +target_include_directories(mbed-headers-drivers + INTERFACE + ${MBED_PATH}/drivers + ${MBED_PATH}/drivers/include + ${MBED_PATH}/drivers/include/drivers +) + +target_include_directories(mbed-headers-events + INTERFACE + ${MBED_PATH}/events/tests/UNITTESTS/target_h + ${MBED_PATH}/events/tests/UNITTESTS/target_h/equeue + ${MBED_PATH}/events/include + ${MBED_PATH}/events/include/events/internal +) + +target_include_directories(mbed-headers-hal + INTERFACE + ${MBED_PATH}/hal + ${MBED_PATH}/hal/include +) + +target_include_directories(mbed-headers-rtos + INTERFACE + ${MBED_PATH}/rtos/include + ${MBED_PATH}/rtos/include/rtos +) + +target_include_directories(mbed-headers + INTERFACE + ${MBED_PATH}/features + ${MBED_PATH}/features/frameworks +) + +target_include_directories(mbed-stubs-headers + INTERFACE + . +) + +add_subdirectory(connectivity) +add_subdirectory(drivers) +add_subdirectory(events) +add_subdirectory(hal) +add_subdirectory(platform) +add_subdirectory(rtos) +add_subdirectory(storage) + +add_library(mbed-stubs INTERFACE) + +target_link_libraries(mbed-stubs + INTERFACE + mbed-stubs-connectivity + mbed-stubs-drivers + mbed-stubs-events + mbed-stubs-hal + mbed-stubs-platform + mbed-stubs-rtos + mbed-stubs-storage +) diff --git a/UNITTESTS/stubs/ATHandler_stub.cpp b/UNITTESTS/stubs/connectivity/ATHandler_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ATHandler_stub.cpp rename to UNITTESTS/stubs/connectivity/ATHandler_stub.cpp diff --git a/UNITTESTS/stubs/AT_CellularContext_stub.cpp b/UNITTESTS/stubs/connectivity/AT_CellularContext_stub.cpp similarity index 100% rename from UNITTESTS/stubs/AT_CellularContext_stub.cpp rename to UNITTESTS/stubs/connectivity/AT_CellularContext_stub.cpp diff --git a/UNITTESTS/stubs/AT_CellularDevice_stub.cpp b/UNITTESTS/stubs/connectivity/AT_CellularDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/AT_CellularDevice_stub.cpp rename to UNITTESTS/stubs/connectivity/AT_CellularDevice_stub.cpp diff --git a/UNITTESTS/stubs/AT_CellularInformation_stub.cpp b/UNITTESTS/stubs/connectivity/AT_CellularInformation_stub.cpp similarity index 100% rename from UNITTESTS/stubs/AT_CellularInformation_stub.cpp rename to UNITTESTS/stubs/connectivity/AT_CellularInformation_stub.cpp diff --git a/UNITTESTS/stubs/AT_CellularNetwork_stub.cpp b/UNITTESTS/stubs/connectivity/AT_CellularNetwork_stub.cpp similarity index 100% rename from UNITTESTS/stubs/AT_CellularNetwork_stub.cpp rename to UNITTESTS/stubs/connectivity/AT_CellularNetwork_stub.cpp diff --git a/UNITTESTS/stubs/AT_CellularSMS_stub.cpp b/UNITTESTS/stubs/connectivity/AT_CellularSMS_stub.cpp similarity index 100% rename from UNITTESTS/stubs/AT_CellularSMS_stub.cpp rename to UNITTESTS/stubs/connectivity/AT_CellularSMS_stub.cpp diff --git a/UNITTESTS/stubs/AT_CellularStack_stub.cpp b/UNITTESTS/stubs/connectivity/AT_CellularStack_stub.cpp similarity index 100% rename from UNITTESTS/stubs/AT_CellularStack_stub.cpp rename to UNITTESTS/stubs/connectivity/AT_CellularStack_stub.cpp diff --git a/UNITTESTS/stubs/AT_ControlPlane_netif_stub.cpp b/UNITTESTS/stubs/connectivity/AT_ControlPlane_netif_stub.cpp similarity index 100% rename from UNITTESTS/stubs/AT_ControlPlane_netif_stub.cpp rename to UNITTESTS/stubs/connectivity/AT_ControlPlane_netif_stub.cpp diff --git a/UNITTESTS/stubs/connectivity/CMakeLists.txt b/UNITTESTS/stubs/connectivity/CMakeLists.txt new file mode 100644 index 00000000000..e3cdfc7415e --- /dev/null +++ b/UNITTESTS/stubs/connectivity/CMakeLists.txt @@ -0,0 +1,62 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-connectivity) + +target_compile_definitions(mbed-stubs-connectivity + PRIVATE + DEVICE_SERIAL=1 + DEVICE_INTERRUPTIN=1 + MBED_CONF_CELLULAR_USE_SMS=1 + MBED_CONF_NSAPI_DEFAULT_CELLULAR_APN=NULL + MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE=115200 + MBED_CONF_LORA_OVER_THE_AIR_ACTIVATION=true + MBED_CONF_LORA_AUTOMATIC_UPLINK_MESSAGE=true + MBED_CONF_LORA_TX_MAX_SIZE=255 + MDMTXD=NC + MDMRXD=NC +) + +target_sources(mbed-stubs-connectivity + PRIVATE + aes_stub.c + AT_CellularContext_stub.cpp + AT_CellularDevice_stub.cpp + AT_CellularInformation_stub.cpp + AT_CellularNetwork_stub.cpp + AT_CellularSMS_stub.cpp + AT_CellularStack_stub.cpp + AT_ControlPlane_netif_stub.cpp + ATHandler_stub.cpp + CellularContext_stub.cpp + CellularDevice_stub.cpp + CellularInterface_stub.cpp + CellularStateMachine_stub.cpp + CellularUtil_stub.cpp + cipher_stub.c + cmac_stub.c + ip4tos_stub.c + LoRaMacChannelPlan_stub.cpp + LoRaMacCommand_stub.cpp + LoRaMacCrypto_stub.cpp + LoRaMac_stub.cpp + LoRaPHYEU868_stub.cpp + LoRaPHY_stub.cpp + LoRaWANStack_stub.cpp + LoRaWANTimer_stub.cpp + MeshInterface_stub.cpp + NetworkInterfaceDefaults_stub.cpp + NetworkInterface_stub.cpp + NetworkStack_stub.cpp + nsapi_dns_stub.cpp + SocketAddress_stub.cpp + SocketStats_Stub.cpp + stoip4_stub.c +) + +target_link_libraries(mbed-stubs-connectivity + PRIVATE + mbed-headers + mbed-stubs-headers + gtest +) diff --git a/UNITTESTS/stubs/CellularContext_stub.cpp b/UNITTESTS/stubs/connectivity/CellularContext_stub.cpp similarity index 100% rename from UNITTESTS/stubs/CellularContext_stub.cpp rename to UNITTESTS/stubs/connectivity/CellularContext_stub.cpp diff --git a/UNITTESTS/stubs/CellularDevice_stub.cpp b/UNITTESTS/stubs/connectivity/CellularDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/CellularDevice_stub.cpp rename to UNITTESTS/stubs/connectivity/CellularDevice_stub.cpp diff --git a/UNITTESTS/stubs/CellularInterface_stub.cpp b/UNITTESTS/stubs/connectivity/CellularInterface_stub.cpp similarity index 100% rename from UNITTESTS/stubs/CellularInterface_stub.cpp rename to UNITTESTS/stubs/connectivity/CellularInterface_stub.cpp diff --git a/UNITTESTS/stubs/CellularStateMachine_stub.cpp b/UNITTESTS/stubs/connectivity/CellularStateMachine_stub.cpp similarity index 100% rename from UNITTESTS/stubs/CellularStateMachine_stub.cpp rename to UNITTESTS/stubs/connectivity/CellularStateMachine_stub.cpp diff --git a/UNITTESTS/stubs/CellularUtil_stub.cpp b/UNITTESTS/stubs/connectivity/CellularUtil_stub.cpp similarity index 100% rename from UNITTESTS/stubs/CellularUtil_stub.cpp rename to UNITTESTS/stubs/connectivity/CellularUtil_stub.cpp diff --git a/UNITTESTS/stubs/LoRaMacChannelPlan_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaMacChannelPlan_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaMacChannelPlan_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaMacChannelPlan_stub.cpp diff --git a/UNITTESTS/stubs/LoRaMacCommand_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaMacCommand_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaMacCommand_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaMacCommand_stub.cpp diff --git a/UNITTESTS/stubs/LoRaMacCrypto_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaMacCrypto_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaMacCrypto_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaMacCrypto_stub.cpp diff --git a/UNITTESTS/stubs/LoRaMac_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaMac_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaMac_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaMac_stub.cpp diff --git a/UNITTESTS/stubs/LoRaPHYEU868_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaPHYEU868_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaPHYEU868_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaPHYEU868_stub.cpp diff --git a/UNITTESTS/stubs/LoRaPHY_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaPHY_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaPHY_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaPHY_stub.cpp diff --git a/UNITTESTS/stubs/LoRaWANStack_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaWANStack_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaWANStack_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaWANStack_stub.cpp diff --git a/UNITTESTS/stubs/LoRaWANTimer_stub.cpp b/UNITTESTS/stubs/connectivity/LoRaWANTimer_stub.cpp similarity index 100% rename from UNITTESTS/stubs/LoRaWANTimer_stub.cpp rename to UNITTESTS/stubs/connectivity/LoRaWANTimer_stub.cpp diff --git a/UNITTESTS/stubs/MeshInterface_stub.cpp b/UNITTESTS/stubs/connectivity/MeshInterface_stub.cpp similarity index 100% rename from UNITTESTS/stubs/MeshInterface_stub.cpp rename to UNITTESTS/stubs/connectivity/MeshInterface_stub.cpp diff --git a/UNITTESTS/stubs/NetworkInterfaceDefaults_stub.cpp b/UNITTESTS/stubs/connectivity/NetworkInterfaceDefaults_stub.cpp similarity index 100% rename from UNITTESTS/stubs/NetworkInterfaceDefaults_stub.cpp rename to UNITTESTS/stubs/connectivity/NetworkInterfaceDefaults_stub.cpp diff --git a/UNITTESTS/stubs/NetworkInterface_stub.cpp b/UNITTESTS/stubs/connectivity/NetworkInterface_stub.cpp similarity index 100% rename from UNITTESTS/stubs/NetworkInterface_stub.cpp rename to UNITTESTS/stubs/connectivity/NetworkInterface_stub.cpp diff --git a/UNITTESTS/stubs/NetworkStack_stub.cpp b/UNITTESTS/stubs/connectivity/NetworkStack_stub.cpp similarity index 100% rename from UNITTESTS/stubs/NetworkStack_stub.cpp rename to UNITTESTS/stubs/connectivity/NetworkStack_stub.cpp diff --git a/UNITTESTS/stubs/SocketAddress_stub.cpp b/UNITTESTS/stubs/connectivity/SocketAddress_stub.cpp similarity index 100% rename from UNITTESTS/stubs/SocketAddress_stub.cpp rename to UNITTESTS/stubs/connectivity/SocketAddress_stub.cpp diff --git a/UNITTESTS/stubs/SocketStats_Stub.cpp b/UNITTESTS/stubs/connectivity/SocketStats_Stub.cpp similarity index 100% rename from UNITTESTS/stubs/SocketStats_Stub.cpp rename to UNITTESTS/stubs/connectivity/SocketStats_Stub.cpp diff --git a/UNITTESTS/stubs/aes_stub.c b/UNITTESTS/stubs/connectivity/aes_stub.c similarity index 100% rename from UNITTESTS/stubs/aes_stub.c rename to UNITTESTS/stubs/connectivity/aes_stub.c diff --git a/UNITTESTS/stubs/cipher_stub.c b/UNITTESTS/stubs/connectivity/cipher_stub.c similarity index 100% rename from UNITTESTS/stubs/cipher_stub.c rename to UNITTESTS/stubs/connectivity/cipher_stub.c diff --git a/UNITTESTS/stubs/cmac_stub.c b/UNITTESTS/stubs/connectivity/cmac_stub.c similarity index 100% rename from UNITTESTS/stubs/cmac_stub.c rename to UNITTESTS/stubs/connectivity/cmac_stub.c diff --git a/UNITTESTS/stubs/ip4tos_stub.c b/UNITTESTS/stubs/connectivity/ip4tos_stub.c similarity index 100% rename from UNITTESTS/stubs/ip4tos_stub.c rename to UNITTESTS/stubs/connectivity/ip4tos_stub.c diff --git a/UNITTESTS/stubs/nsapi_dns_stub.cpp b/UNITTESTS/stubs/connectivity/nsapi_dns_stub.cpp similarity index 100% rename from UNITTESTS/stubs/nsapi_dns_stub.cpp rename to UNITTESTS/stubs/connectivity/nsapi_dns_stub.cpp diff --git a/UNITTESTS/stubs/stoip4_stub.c b/UNITTESTS/stubs/connectivity/stoip4_stub.c similarity index 100% rename from UNITTESTS/stubs/stoip4_stub.c rename to UNITTESTS/stubs/connectivity/stoip4_stub.c diff --git a/UNITTESTS/stubs/BufferedSerial_stub.cpp b/UNITTESTS/stubs/drivers/BufferedSerial_stub.cpp similarity index 100% rename from UNITTESTS/stubs/BufferedSerial_stub.cpp rename to UNITTESTS/stubs/drivers/BufferedSerial_stub.cpp diff --git a/UNITTESTS/stubs/drivers/CMakeLists.txt b/UNITTESTS/stubs/drivers/CMakeLists.txt new file mode 100644 index 00000000000..139fa28451d --- /dev/null +++ b/UNITTESTS/stubs/drivers/CMakeLists.txt @@ -0,0 +1,23 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-drivers) + +target_sources(mbed-stubs-drivers + PRIVATE + BufferedSerial_stub.cpp + SerialBase_stub.cpp +) + +target_compile_definitions(mbed-stubs-drivers + PRIVATE + DEVICE_SERIAL=1 + DEVICE_INTERRUPTIN=1 + MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE=115200 +) + +target_link_libraries(mbed-stubs-drivers + PRIVATE + mbed-headers + mbed-stubs-headers +) diff --git a/UNITTESTS/stubs/SerialBase_stub.cpp b/UNITTESTS/stubs/drivers/SerialBase_stub.cpp similarity index 100% rename from UNITTESTS/stubs/SerialBase_stub.cpp rename to UNITTESTS/stubs/drivers/SerialBase_stub.cpp diff --git a/UNITTESTS/stubs/events/CMakeLists.txt b/UNITTESTS/stubs/events/CMakeLists.txt new file mode 100644 index 00000000000..161563c8d44 --- /dev/null +++ b/UNITTESTS/stubs/events/CMakeLists.txt @@ -0,0 +1,18 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-events) + +target_sources(mbed-stubs-events + PRIVATE + equeue_stub.c + EventFlags_stub.cpp + EventQueue_stub.cpp + mbed_shared_queues_stub.cpp +) + +target_link_libraries(mbed-stubs-events + PRIVATE + mbed-headers + mbed-stubs-headers +) diff --git a/UNITTESTS/stubs/EventFlags_stub.cpp b/UNITTESTS/stubs/events/EventFlags_stub.cpp similarity index 100% rename from UNITTESTS/stubs/EventFlags_stub.cpp rename to UNITTESTS/stubs/events/EventFlags_stub.cpp diff --git a/UNITTESTS/stubs/EventQueue_stub.cpp b/UNITTESTS/stubs/events/EventQueue_stub.cpp similarity index 100% rename from UNITTESTS/stubs/EventQueue_stub.cpp rename to UNITTESTS/stubs/events/EventQueue_stub.cpp diff --git a/UNITTESTS/stubs/equeue_stub.c b/UNITTESTS/stubs/events/equeue_stub.c similarity index 100% rename from UNITTESTS/stubs/equeue_stub.c rename to UNITTESTS/stubs/events/equeue_stub.c diff --git a/UNITTESTS/stubs/mbed_shared_queues_stub.cpp b/UNITTESTS/stubs/events/mbed_shared_queues_stub.cpp similarity index 100% rename from UNITTESTS/stubs/mbed_shared_queues_stub.cpp rename to UNITTESTS/stubs/events/mbed_shared_queues_stub.cpp diff --git a/UNITTESTS/stubs/hal/CMakeLists.txt b/UNITTESTS/stubs/hal/CMakeLists.txt new file mode 100644 index 00000000000..50d93669208 --- /dev/null +++ b/UNITTESTS/stubs/hal/CMakeLists.txt @@ -0,0 +1,24 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-hal) + +target_compile_definitions(mbed-stubs-hal + PRIVATE + DEVICE_PWMOUT + DEVICE_WATCHDOG + MBED_WDOG_ASSERT=1 +) + +target_sources(mbed-stubs-hal + PRIVATE + pwmout_api_stub.c + us_ticker_stub.cpp + watchdog_api_stub.c +) + +target_link_libraries(mbed-stubs-hal + PRIVATE + mbed-headers + mbed-stubs-headers +) diff --git a/UNITTESTS/stubs/pwmout_api_stub.c b/UNITTESTS/stubs/hal/pwmout_api_stub.c similarity index 100% rename from UNITTESTS/stubs/pwmout_api_stub.c rename to UNITTESTS/stubs/hal/pwmout_api_stub.c diff --git a/UNITTESTS/stubs/us_ticker_stub.cpp b/UNITTESTS/stubs/hal/us_ticker_stub.cpp similarity index 100% rename from UNITTESTS/stubs/us_ticker_stub.cpp rename to UNITTESTS/stubs/hal/us_ticker_stub.cpp diff --git a/UNITTESTS/stubs/watchdog_api_stub.c b/UNITTESTS/stubs/hal/watchdog_api_stub.c similarity index 100% rename from UNITTESTS/stubs/watchdog_api_stub.c rename to UNITTESTS/stubs/hal/watchdog_api_stub.c diff --git a/UNITTESTS/stubs/platform/CMakeLists.txt b/UNITTESTS/stubs/platform/CMakeLists.txt new file mode 100644 index 00000000000..e03919fe060 --- /dev/null +++ b/UNITTESTS/stubs/platform/CMakeLists.txt @@ -0,0 +1,24 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-platform) + +target_sources(mbed-stubs-platform + PRIVATE + mbed_critical_stub.c + mbed_atomic_stub.c + mbed_error.c + mbed_poll_stub.cpp + mbed_assert_stub.cpp + mbed_wait_api_stub.cpp + mbed_retarget_stub.cpp + nvic_wrapper_stub.c + randLIB_stub.c + randLIB_stub.cpp +) + +target_link_libraries(mbed-stubs-platform + PRIVATE + mbed-headers + mbed-stubs-headers +) diff --git a/UNITTESTS/stubs/mbed_assert_stub.cpp b/UNITTESTS/stubs/platform/mbed_assert_stub.cpp similarity index 100% rename from UNITTESTS/stubs/mbed_assert_stub.cpp rename to UNITTESTS/stubs/platform/mbed_assert_stub.cpp diff --git a/UNITTESTS/stubs/mbed_atomic_stub.c b/UNITTESTS/stubs/platform/mbed_atomic_stub.c similarity index 100% rename from UNITTESTS/stubs/mbed_atomic_stub.c rename to UNITTESTS/stubs/platform/mbed_atomic_stub.c diff --git a/UNITTESTS/stubs/mbed_critical_stub.c b/UNITTESTS/stubs/platform/mbed_critical_stub.c similarity index 100% rename from UNITTESTS/stubs/mbed_critical_stub.c rename to UNITTESTS/stubs/platform/mbed_critical_stub.c diff --git a/UNITTESTS/stubs/mbed_error.c b/UNITTESTS/stubs/platform/mbed_error.c similarity index 100% rename from UNITTESTS/stubs/mbed_error.c rename to UNITTESTS/stubs/platform/mbed_error.c diff --git a/UNITTESTS/stubs/mbed_poll_stub.cpp b/UNITTESTS/stubs/platform/mbed_poll_stub.cpp similarity index 100% rename from UNITTESTS/stubs/mbed_poll_stub.cpp rename to UNITTESTS/stubs/platform/mbed_poll_stub.cpp diff --git a/UNITTESTS/stubs/mbed_retarget_stub.cpp b/UNITTESTS/stubs/platform/mbed_retarget_stub.cpp similarity index 100% rename from UNITTESTS/stubs/mbed_retarget_stub.cpp rename to UNITTESTS/stubs/platform/mbed_retarget_stub.cpp diff --git a/UNITTESTS/stubs/mbed_wait_api_stub.cpp b/UNITTESTS/stubs/platform/mbed_wait_api_stub.cpp similarity index 100% rename from UNITTESTS/stubs/mbed_wait_api_stub.cpp rename to UNITTESTS/stubs/platform/mbed_wait_api_stub.cpp diff --git a/UNITTESTS/stubs/nvic_wrapper_stub.c b/UNITTESTS/stubs/platform/nvic_wrapper_stub.c similarity index 100% rename from UNITTESTS/stubs/nvic_wrapper_stub.c rename to UNITTESTS/stubs/platform/nvic_wrapper_stub.c diff --git a/UNITTESTS/stubs/randLIB_stub.c b/UNITTESTS/stubs/platform/randLIB_stub.c similarity index 100% rename from UNITTESTS/stubs/randLIB_stub.c rename to UNITTESTS/stubs/platform/randLIB_stub.c diff --git a/UNITTESTS/stubs/randLIB_stub.cpp b/UNITTESTS/stubs/platform/randLIB_stub.cpp similarity index 100% rename from UNITTESTS/stubs/randLIB_stub.cpp rename to UNITTESTS/stubs/platform/randLIB_stub.cpp diff --git a/UNITTESTS/stubs/rtos/CMakeLists.txt b/UNITTESTS/stubs/rtos/CMakeLists.txt new file mode 100644 index 00000000000..fc9a759b8d6 --- /dev/null +++ b/UNITTESTS/stubs/rtos/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-rtos) + +target_sources(mbed-stubs-rtos + PRIVATE + ConditionVariable_stub.cpp + Kernel_stub.cpp + mbed_rtos_rtx_stub.c + Mutex_stub.cpp + rtx_mutex_stub.c + Semaphore_stub.cpp + ThisThread_stub.cpp + Thread_stub.cpp +) + +target_link_libraries(mbed-stubs-rtos + PRIVATE + mbed-headers + mbed-stubs-headers +) diff --git a/UNITTESTS/stubs/ConditionVariable_stub.cpp b/UNITTESTS/stubs/rtos/ConditionVariable_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ConditionVariable_stub.cpp rename to UNITTESTS/stubs/rtos/ConditionVariable_stub.cpp diff --git a/UNITTESTS/stubs/Kernel_stub.cpp b/UNITTESTS/stubs/rtos/Kernel_stub.cpp similarity index 100% rename from UNITTESTS/stubs/Kernel_stub.cpp rename to UNITTESTS/stubs/rtos/Kernel_stub.cpp diff --git a/UNITTESTS/stubs/Mutex_stub.cpp b/UNITTESTS/stubs/rtos/Mutex_stub.cpp similarity index 100% rename from UNITTESTS/stubs/Mutex_stub.cpp rename to UNITTESTS/stubs/rtos/Mutex_stub.cpp diff --git a/UNITTESTS/stubs/Semaphore_stub.cpp b/UNITTESTS/stubs/rtos/Semaphore_stub.cpp similarity index 100% rename from UNITTESTS/stubs/Semaphore_stub.cpp rename to UNITTESTS/stubs/rtos/Semaphore_stub.cpp diff --git a/UNITTESTS/stubs/ThisThread_stub.cpp b/UNITTESTS/stubs/rtos/ThisThread_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ThisThread_stub.cpp rename to UNITTESTS/stubs/rtos/ThisThread_stub.cpp diff --git a/UNITTESTS/stubs/Thread_stub.cpp b/UNITTESTS/stubs/rtos/Thread_stub.cpp similarity index 100% rename from UNITTESTS/stubs/Thread_stub.cpp rename to UNITTESTS/stubs/rtos/Thread_stub.cpp diff --git a/UNITTESTS/stubs/mbed_rtos_rtx_stub.c b/UNITTESTS/stubs/rtos/mbed_rtos_rtx_stub.c similarity index 96% rename from UNITTESTS/stubs/mbed_rtos_rtx_stub.c rename to UNITTESTS/stubs/rtos/mbed_rtos_rtx_stub.c index aa45009fa51..889065cbcbd 100644 --- a/UNITTESTS/stubs/mbed_rtos_rtx_stub.c +++ b/UNITTESTS/stubs/rtos/mbed_rtos_rtx_stub.c @@ -15,6 +15,6 @@ * limitations under the License. */ -#include "cmsis_os2.h" +#include "mbed_rtos_types.h" osMutexId_t singleton_mutex_id; diff --git a/UNITTESTS/stubs/rtx_mutex_stub.c b/UNITTESTS/stubs/rtos/rtx_mutex_stub.c similarity index 96% rename from UNITTESTS/stubs/rtx_mutex_stub.c rename to UNITTESTS/stubs/rtos/rtx_mutex_stub.c index de5aed92bd1..916be3ee955 100644 --- a/UNITTESTS/stubs/rtx_mutex_stub.c +++ b/UNITTESTS/stubs/rtos/rtx_mutex_stub.c @@ -15,7 +15,7 @@ * limitations under the License. */ -#include "cmsis_os2.h" +#include "mbed_rtos_types.h" osStatus_t osMutexAcquire(osMutexId_t mutex_id, uint32_t timeout) { diff --git a/UNITTESTS/stubs/BufferedBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/BufferedBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/BufferedBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/BufferedBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/storage/CMakeLists.txt b/UNITTESTS/stubs/storage/CMakeLists.txt new file mode 100644 index 00000000000..8f10c63378a --- /dev/null +++ b/UNITTESTS/stubs/storage/CMakeLists.txt @@ -0,0 +1,27 @@ +# Copyright (c) 2021 ARM Limited. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(mbed-stubs-storage) + +target_sources(mbed-stubs-storage + PRIVATE + BufferedBlockDevice_stub.cpp + ChainingBlockDevice_stub.cpp + EmulatedSD.cpp + ExhaustibleBlockDevice_stub.cpp + FileHandle_stub.cpp + FlashSimBlockDevice_stub.cpp + HeapBlockDevice_stub.cpp + #MBRBlockDevice_stub.cpp + ObservingBlockDevice_stub.cpp + ProfilingBlockDevice_stub.cpp + ReadOnlyBlockDevice_stub.cpp + SlicingBlockDevice_stub.cpp + kv_config_stub.cpp +) + +target_link_libraries(mbed-stubs-storage + PRIVATE + mbed-headers + mbed-stubs-headers +) diff --git a/UNITTESTS/stubs/ChainingBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/ChainingBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ChainingBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/ChainingBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/EmulatedSD.cpp b/UNITTESTS/stubs/storage/EmulatedSD.cpp similarity index 100% rename from UNITTESTS/stubs/EmulatedSD.cpp rename to UNITTESTS/stubs/storage/EmulatedSD.cpp diff --git a/UNITTESTS/stubs/ExhaustibleBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/ExhaustibleBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ExhaustibleBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/ExhaustibleBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/FileHandle_stub.cpp b/UNITTESTS/stubs/storage/FileHandle_stub.cpp similarity index 100% rename from UNITTESTS/stubs/FileHandle_stub.cpp rename to UNITTESTS/stubs/storage/FileHandle_stub.cpp diff --git a/UNITTESTS/stubs/FlashSimBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/FlashSimBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/FlashSimBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/FlashSimBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/HeapBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/HeapBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/HeapBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/HeapBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/MBRBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/MBRBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/MBRBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/MBRBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/ObservingBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/ObservingBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ObservingBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/ObservingBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/ProfilingBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/ProfilingBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ProfilingBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/ProfilingBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/ReadOnlyBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/ReadOnlyBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/ReadOnlyBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/ReadOnlyBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/SlicingBlockDevice_stub.cpp b/UNITTESTS/stubs/storage/SlicingBlockDevice_stub.cpp similarity index 100% rename from UNITTESTS/stubs/SlicingBlockDevice_stub.cpp rename to UNITTESTS/stubs/storage/SlicingBlockDevice_stub.cpp diff --git a/UNITTESTS/stubs/kv_config_stub.cpp b/UNITTESTS/stubs/storage/kv_config_stub.cpp similarity index 100% rename from UNITTESTS/stubs/kv_config_stub.cpp rename to UNITTESTS/stubs/storage/kv_config_stub.cpp diff --git a/UNITTESTS/target_h/platform/cxxsupport/mstd_tuple b/UNITTESTS/target_h/platform/cxxsupport/mstd_tuple new file mode 100644 index 00000000000..d9e926aa57d --- /dev/null +++ b/UNITTESTS/target_h/platform/cxxsupport/mstd_tuple @@ -0,0 +1,93 @@ +/* mbed Microcontroller Library + * Copyright (c) 2019 ARM Limited + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES LEOR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MSTD_TUPLE_ +#define MSTD_TUPLE_ + +/* + * + * - includes toolchain's + * - For all toolchains, C++17 backports: + * - mstd::apply + * - mstd::make_from_tuple + */ + +#include + +#if __cpp_lib_apply < 201603 || __cpp_lib_make_from_tuple < 201606 +#include // integer_sequence +#endif +#if __cpp_lib_apply < 201603 +#include // invoke +#endif + +namespace mstd { +using std::tuple; +using std::ignore; +using std::make_tuple; +using std::forward_as_tuple; +using std::tie; +using std::tuple_cat; +using std::tuple_size; +using std::tuple_element; +using std::tuple_element_t; +using std::get; + +// [tuple.apply] +#if __cpp_lib_apply >= 201603 +using std::apply; +#else +namespace impl { +template +invoke_result_t...> apply(F&& f, Tuple&& t, std::index_sequence) +{ + return mstd::invoke(std::forward(f), std::get(std::forward(t))...); +} +} + +// apply - works also for tuple-like objects such as array or pair +// user-defined types can specialize std::get and std::tuple_size to make this work +template +auto apply(F&& f, Tuple&& t) -> +decltype(impl::apply(std::forward(f), std::forward(t), std::make_index_sequence>::value>{})) +{ + return impl::apply(std::forward(f), std::forward(t), + std::make_index_sequence>::value>{}); +} +#endif + +#if __cpp_lib_make_from_tuple >= 201606 +using std::make_from_tuple; +#else +namespace impl { +template +T make_from_tuple(Tuple&& t, std::index_sequence) +{ + return T(std::get(std::forward(t))...); +} +} + +template +T make_from_tuple(Tuple&& t) +{ + return impl::make_from_tuple(std::forward(t), + std::make_index_sequence>::value>{}); +} +#endif + +} // namespace mstd + +#endif // MSTD_TUPLE_ diff --git a/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/CMakeLists.txt b/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/CMakeLists.txt index e742f1483d2..3695d5bd1e2 100644 --- a/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/CMakeLists.txt +++ b/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/CMakeLists.txt @@ -1,47 +1,49 @@ # Copyright (c) 2020-2021 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -function(_mbed_get_cortex_m_exception_handlers toolchain_dir) - foreach(key ${MBED_TARGET_LABELS}) - if(${key} STREQUAL CORTEX_A) - set(STARTUP_RTX_FILE TARGET_CORTEX_A/irq_ca.S) - elseif(${key} STREQUAL M0) - set(STARTUP_RTX_FILE TARGET_M0/irq_cm0.S) - elseif(${key} STREQUAL M0P) - set(STARTUP_RTX_FILE TARGET_M0P/irq_cm0.S) - elseif(${key} STREQUAL M23) - set(STARTUP_RTX_FILE TARGET_M23/irq_armv8mbl.S) - elseif(${key} STREQUAL M3) - set(STARTUP_RTX_FILE TARGET_M3/irq_cm3.S) - elseif(${key} STREQUAL M33) - set(STARTUP_RTX_FILE TARGET_M33/irq_armv8mml.S) - elseif(${key} STREQUAL M55) - set(STARTUP_RTX_FILE TARGET_M33/irq_armv8mml.S) - elseif(${key} STREQUAL RTOS_M4_M7) - set(STARTUP_RTX_FILE TARGET_RTOS_M4_M7/irq_cm4f.S) - endif() +if(${CMAKE_CROSSCOMPILING}) + function(_mbed_get_cortex_m_exception_handlers toolchain_dir) + foreach(key ${MBED_TARGET_LABELS}) + if(${key} STREQUAL CORTEX_A) + set(STARTUP_RTX_FILE TARGET_CORTEX_A/irq_ca.S) + elseif(${key} STREQUAL M0) + set(STARTUP_RTX_FILE TARGET_M0/irq_cm0.S) + elseif(${key} STREQUAL M0P) + set(STARTUP_RTX_FILE TARGET_M0P/irq_cm0.S) + elseif(${key} STREQUAL M23) + set(STARTUP_RTX_FILE TARGET_M23/irq_armv8mbl.S) + elseif(${key} STREQUAL M3) + set(STARTUP_RTX_FILE TARGET_M3/irq_cm3.S) + elseif(${key} STREQUAL M33) + set(STARTUP_RTX_FILE TARGET_M33/irq_armv8mml.S) + elseif(${key} STREQUAL M55) + set(STARTUP_RTX_FILE TARGET_M33/irq_armv8mml.S) + elseif(${key} STREQUAL RTOS_M4_M7) + set(STARTUP_RTX_FILE TARGET_RTOS_M4_M7/irq_cm4f.S) + endif() - target_sources(mbed-rtos - INTERFACE - Source/${toolchain_dir}/${STARTUP_RTX_FILE} - ) - endforeach() -endfunction() - -function(_mbed_get_cortex_a_exception_handlers) - foreach(key ${MBED_TARGET_LABELS}) - if(${key} STREQUAL CORTEX_A) - target_sources(mbed-rtos INTERFACE Config/TARGET_CORTEX_A/handlers.c) - endif() - endforeach() -endfunction() - -_mbed_get_cortex_a_exception_handlers() - -if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") - _mbed_get_cortex_m_exception_handlers(TOOLCHAIN_GCC) -elseif(${MBED_TOOLCHAIN} STREQUAL "ARM") - _mbed_get_cortex_m_exception_handlers(TOOLCHAIN_ARM) + target_sources(mbed-rtos + INTERFACE + Source/${toolchain_dir}/${STARTUP_RTX_FILE} + ) + endforeach() + endfunction() + + function(_mbed_get_cortex_a_exception_handlers) + foreach(key ${MBED_TARGET_LABELS}) + if(${key} STREQUAL CORTEX_A) + target_sources(mbed-rtos INTERFACE Config/TARGET_CORTEX_A/handlers.c) + endif() + endforeach() + endfunction() + + _mbed_get_cortex_a_exception_handlers() + + if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") + _mbed_get_cortex_m_exception_handlers(TOOLCHAIN_GCC) + elseif(${MBED_TOOLCHAIN} STREQUAL "ARM") + _mbed_get_cortex_m_exception_handlers(TOOLCHAIN_ARM) + endif() endif() target_include_directories(mbed-rtos diff --git a/cmsis/device/rtos/CMakeLists.txt b/cmsis/device/rtos/CMakeLists.txt index 024cf56218c..34cd1623e43 100644 --- a/cmsis/device/rtos/CMakeLists.txt +++ b/cmsis/device/rtos/CMakeLists.txt @@ -1,16 +1,18 @@ # Copyright (c) 2020-2021 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") - target_sources(mbed-rtos - INTERFACE - TOOLCHAIN_GCC_ARM/mbed_boot_gcc_arm.c - ) -elseif(${MBED_TOOLCHAIN} STREQUAL "ARM") - target_sources(mbed-rtos - INTERFACE - TOOLCHAIN_ARM_STD/mbed_boot_arm_std.c - ) +if(${CMAKE_CROSSCOMPILING}) + if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") + target_sources(mbed-rtos + INTERFACE + TOOLCHAIN_GCC_ARM/mbed_boot_gcc_arm.c + ) + elseif(${MBED_TOOLCHAIN} STREQUAL "ARM") + target_sources(mbed-rtos + INTERFACE + TOOLCHAIN_ARM_STD/mbed_boot_arm_std.c + ) + endif() endif() target_include_directories(mbed-rtos diff --git a/connectivity/FEATURE_BLE/include/ble/common/BLERoles.h b/connectivity/FEATURE_BLE/include/ble/common/BLERoles.h index 2c28eadbd5b..3ef6371da81 100644 --- a/connectivity/FEATURE_BLE/include/ble/common/BLERoles.h +++ b/connectivity/FEATURE_BLE/include/ble/common/BLERoles.h @@ -19,6 +19,49 @@ #ifndef MBED_BLE_ROLES_H__ #define MBED_BLE_ROLES_H__ +#if !defined(BLE_ROLE_OBSERVER) +#define BLE_ROLE_OBSERVER 1 +#endif +#if !defined(BLE_ROLE_BROADCASTER) +#define BLE_ROLE_BROADCASTER 1 +#endif +#if !defined(BLE_ROLE_CENTRAL) +#define BLE_ROLE_CENTRAL 1 +#endif +#if !defined(BLE_ROLE_PERIPHERAL) +#define BLE_ROLE_PERIPHERAL 1 +#endif +#if !defined(BLE_FEATURE_GATT_CLIENT) +#define BLE_FEATURE_GATT_CLIENT 1 +#endif +#if !defined(BLE_FEATURE_GATT_SERVER) +#define BLE_FEATURE_GATT_SERVER 1 +#endif +#if !defined(BLE_FEATURE_SECURITY) +#define BLE_FEATURE_SECURITY 1 +#endif +#if !defined(BLE_FEATURE_SECURE_CONNECTIONS) +#define BLE_FEATURE_SECURE_CONNECTIONS 1 +#endif +#if !defined(BLE_FEATURE_SIGNING) +#define BLE_FEATURE_SIGNING 1 +#endif +#if !defined(BLE_FEATURE_WHITELIST) +#define BLE_FEATURE_WHITELIST 1 +#endif +#if !defined(BLE_FEATURE_PRIVACY) +#define BLE_FEATURE_PRIVACY 1 +#endif +#if !defined(BLE_FEATURE_PHY_MANAGEMENT) +#define BLE_FEATURE_PHY_MANAGEMENT 1 +#endif +#if !defined(BLE_FEATURE_EXTENDED_ADVERTISING) +#define BLE_FEATURE_EXTENDED_ADVERTISING 1 +#endif +#if !defined(BLE_FEATURE_PERIODIC_ADVERTISING) +#define BLE_FEATURE_PERIODIC_ADVERTISING 1 +#endif + #if !(BLE_ROLE_OBSERVER) && !(BLE_ROLE_BROADCASTER) #error "BLE requires at least one role 'BROADCASTER' or 'OBSERVER' to be enabled" #endif diff --git a/connectivity/cellular/CMakeLists.txt b/connectivity/cellular/CMakeLists.txt index 00b5d7a84ae..4b6718d1999 100644 --- a/connectivity/cellular/CMakeLists.txt +++ b/connectivity/cellular/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + add_subdirectory(source/framework) target_include_directories(mbed-cellular diff --git a/connectivity/drivers/wifi/TARGET_WICED/CMakeLists.txt b/connectivity/drivers/wifi/TARGET_WICED/CMakeLists.txt index c6f83e6b9cb..8bcf3677e36 100644 --- a/connectivity/drivers/wifi/TARGET_WICED/CMakeLists.txt +++ b/connectivity/drivers/wifi/TARGET_WICED/CMakeLists.txt @@ -3,13 +3,15 @@ add_library(mbed-wiced INTERFACE) -if(${MBED_TOOLCHAIN} STREQUAL "ARM") - set(LIB_WICED_DRIVERS TOOLCHAIN_ARMC6/TARGET_WIO_EMW3166/libwiced_drivers.ar) -elseif(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") - set(LIB_WICED_DRIVERS TOOLCHAIN_GCC_ARM/TARGET_WIO_EMW3166/libwiced_drivers.a) -endif() +if(${CMAKE_CROSSCOMPILING}) + if(${MBED_TOOLCHAIN} STREQUAL "ARM") + set(LIB_WICED_DRIVERS TOOLCHAIN_ARMC6/TARGET_WIO_EMW3166/libwiced_drivers.ar) + elseif(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM") + set(LIB_WICED_DRIVERS TOOLCHAIN_GCC_ARM/TARGET_WIO_EMW3166/libwiced_drivers.a) + endif() target_link_libraries(mbed-wiced INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/${LIB_WICED_DRIVERS}) +endif() target_include_directories(mbed-wiced INTERFACE diff --git a/connectivity/lorawan/CMakeLists.txt b/connectivity/lorawan/CMakeLists.txt index 743a0ff9ae8..6d0a3da7067 100644 --- a/connectivity/lorawan/CMakeLists.txt +++ b/connectivity/lorawan/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + add_subdirectory(lorastack) add_subdirectory(system) diff --git a/connectivity/netsocket/CMakeLists.txt b/connectivity/netsocket/CMakeLists.txt index f99ae1dbaad..ce6faec2ab8 100644 --- a/connectivity/netsocket/CMakeLists.txt +++ b/connectivity/netsocket/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + # TODO CMake: Perhaps move this/these file(s) into connectivity/drivers/cellular target_sources(mbed-cellular INTERFACE diff --git a/drivers/CMakeLists.txt b/drivers/CMakeLists.txt index 83bb2223098..1d5d090e449 100644 --- a/drivers/CMakeLists.txt +++ b/drivers/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + target_include_directories(mbed-core INTERFACE . diff --git a/events/CMakeLists.txt b/events/CMakeLists.txt index 591b01259ad..b6aaafd9311 100644 --- a/events/CMakeLists.txt +++ b/events/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + add_library(mbed-events INTERFACE) target_include_directories(mbed-events diff --git a/platform/CMakeLists.txt b/platform/CMakeLists.txt index c68f8152235..fb4d7d2dd58 100644 --- a/platform/CMakeLists.txt +++ b/platform/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + # List of all optional platform libraries available. add_library(mbed-psa INTERFACE) diff --git a/storage/blockdevice/CMakeLists.txt b/storage/blockdevice/CMakeLists.txt index 6181735cd3b..50347278f16 100644 --- a/storage/blockdevice/CMakeLists.txt +++ b/storage/blockdevice/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + if("DATAFLASH" IN_LIST MBED_TARGET_LABELS) add_subdirectory(COMPONENT_DATAFLASH) endif() diff --git a/storage/kvstore/filesystemstore/CMakeLists.txt b/storage/kvstore/filesystemstore/CMakeLists.txt index 116a5abf2a0..f4dfa9c5f2f 100644 --- a/storage/kvstore/filesystemstore/CMakeLists.txt +++ b/storage/kvstore/filesystemstore/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + target_include_directories(mbed-storage-filesystemstore INTERFACE . diff --git a/storage/kvstore/tdbstore/CMakeLists.txt b/storage/kvstore/tdbstore/CMakeLists.txt index 38a992a488a..24817078222 100644 --- a/storage/kvstore/tdbstore/CMakeLists.txt +++ b/storage/kvstore/tdbstore/CMakeLists.txt @@ -1,6 +1,10 @@ # Copyright (c) 2020 ARM Limited. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +if(${MBED_BUILD_UNITTESTS}) + add_subdirectory(tests/UNITTESTS) +endif() + target_include_directories(mbed-storage-tdbstore INTERFACE .